<?php
class GoodsCustomerDeliveriesController extends Controller
{
    public function indexAction()
    {
        $m           = new GoodsCustomerDelivery();
        $projectId   = (int)($_GET['project_id'] ?? 0);
        $assignedMe  = strtolower((string)($_GET['assigned'] ?? '')) === 'me';
        $assignedUid = $assignedMe ? $this->currentUserId() : 0;
        $rows        = $m->list($projectId, $assignedUid);

        $projName = '';
        if ($projectId > 0) {
            $db = new DB();
            $r = $db->mySelect("SELECT project_no, project_name FROM c_projects WHERE c0d = :id", [':id' => $projectId]);
            if (!empty($r)) $projName = $r[0]['project_no'] . ' · ' . $r[0]['project_name'];
        }

        $this->view->setLayout($this->roleLayout());
        $this->view->render('GoodsCustomerDeliveries/index', [
            'page_title'           => 'Customer Delivery Notes',
            'rows'                 => $rows,
            'filter_project'       => $projectId,
            'filter_project_label' => $projName,
            'filter_assigned_me'   => $assignedMe,
        ]);
    }

    /** Deliver form pre-filled from a Client PO's outstanding lines. */
    public function deliverAction($cpo_id = 0)
    {
        $cpoId = (int)$cpo_id;
        if ($cpoId <= 0) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-danger">client_po_id required.</div>']);
            return;
        }
        $cm  = new GoodsClientPos();
        $cpo = $cm->byId($cpoId);
        if (!$cpo) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-danger">Client PO not found.</div>']);
            return;
        }
        if (in_array($cpo['status'], ['CANCELLED','CLOSED'], true)) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-info">Client PO is <code>' . htmlspecialchars($cpo['status']) . '</code>. Nothing more to deliver. <a href="' . PROOT . 'GoodsClientPos/view/' . $cpoId . '">Back to PO</a>.</div>']);
            return;
        }
        $items = $cm->itemsFor($cpoId);
        $this->view->setLayout($this->roleLayout());
        $this->view->render('GoodsCustomerDeliveries/deliver', [
            'page_title' => 'Deliver · ' . $cpo['client_po_no'],
            'cpo'        => $cpo,
            'items'      => $items,
        ]);
    }

    public function saveAction()
    {
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('GoodsCustomerDeliveries'); return; }

        $ids  = $_POST['line_id']         ?? [];
        $qds  = $_POST['qty_delivered']   ?? [];
        $cns  = $_POST['condition_notes'] ?? [];
        $items = [];
        for ($i = 0; $i < count($ids); $i++) {
            $qd = (float)($qds[$i] ?? 0);
            if ($qd <= 0) continue;
            $items[] = [
                'client_po_item_id' => (int)$ids[$i],
                'qty_delivered'     => $qd,
                'condition_notes'   => (string)($cns[$i] ?? ''),
            ];
        }
        $d = [
            'client_po_id'           => (int)($_POST['client_po_id'] ?? 0),
            'delivery_date'          => (string)($_POST['delivery_date'] ?? date('Y-m-d')),
            'delivered_to'           => (string)($_POST['delivered_to'] ?? ''),
            'delivered_to_phone'     => (string)($_POST['delivered_to_phone'] ?? ''),
            'delivered_to_signature' => (string)($_POST['delivered_to_signature'] ?? ''),
            'notes'                  => (string)($_POST['notes'] ?? ''),
            'items'                  => $items,
        ];

        $m = new GoodsCustomerDelivery();
        $r = $m->create($d, $this->currentUserId(), $_SESSION['full_name'] ?? '');
        if (!$r['ok']) {
            $cm    = new GoodsClientPos();
            $cpo   = $cm->byId((int)$d['client_po_id']);
            $items = $cm->itemsFor((int)$d['client_po_id']);
            $this->view->setLayout($this->roleLayout());
            $this->view->render('GoodsCustomerDeliveries/deliver', [
                'page_title' => 'Deliver',
                'cpo'        => $cpo,
                'items'      => $items,
                'fb_msg'     => '<div class="alert alert-danger">' . htmlspecialchars($r['msg']) . '</div>',
                'form'       => $_POST,
            ]);
            return;
        }
        Router::redirect('GoodsCustomerDeliveries/view/' . (int)$r['id']);
    }

    public function viewAction($id = 0)
    {
        $m  = new GoodsCustomerDelivery();
        $dn = $m->byId((int)$id);
        if (!$dn) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-danger">DN not found.</div>']);
            return;
        }
        $items  = $m->itemsFor((int)$id);
        $photos = $m->photosFor((int)$id);
        $this->view->setLayout($this->roleLayout());
        $this->view->render('GoodsCustomerDeliveries/view', [
            'page_title' => $dn['dn_no'],
            'dn'         => $dn,
            'items'      => $items,
            'photos'     => $photos,
        ]);
    }

    /* ── Slice 8Z-x · Delivery photo endpoints ─────────────────────── */

    public function addPhotoAjAction()
    {
        header('Content-Type: application/json');
        try {
            $dnId = (int)($_POST['dn_id'] ?? 0);
            if ($dnId <= 0) throw new InvalidArgumentException('dn_id required.');
            $file = $_FILES['photo'] ?? null;
            if (!$file || empty($file['tmp_name'])) throw new InvalidArgumentException('No photo uploaded.');
            $id = (new GoodsCustomerDelivery())->addPhoto(
                $dnId, $file,
                (string)($_POST['kind'] ?? 'DELIVERY'),
                (string)($_POST['caption'] ?? ''),
                $this->currentUserId(), $_SESSION['full_name'] ?? ''
            );
            echo json_encode(['ok' => true, 'photo_id' => $id]);
        } catch (\Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    public function removePhotoAjAction()
    {
        header('Content-Type: application/json');
        try {
            $id = (int)($_POST['photo_id'] ?? 0);
            if ($id <= 0) throw new InvalidArgumentException('photo_id required.');
            (new GoodsCustomerDelivery())->removePhoto($id);
            echo json_encode(['ok' => true]);
        } catch (\Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    public function photoDownloadAction($id = 0)
    {
        $id = (int)$id;
        if ($id <= 0) { http_response_code(400); echo 'Bad request.'; return; }
        $p = (new GoodsCustomerDelivery())->findPhoto($id);
        if (empty($p)) { http_response_code(404); echo 'Not found.'; return; }
        $abs = ROOT . '/' . ltrim((string)$p['file_path'], '/');
        if (!is_file($abs)) { http_response_code(404); echo 'File missing.'; return; }
        header('Content-Type: ' . (string)($p['mime'] ?: 'application/octet-stream'));
        header('Content-Length: ' . (int)filesize($abs));
        header('Content-Disposition: inline; filename="' . str_replace('"', '', (string)($p['original_name'] ?: basename($abs))) . '"');
        readfile($abs); exit();
    }
}
