<?php
class PettyCashController extends Controller
{
    public function raiseAction()
    {
        $db       = new DB();
        $projects = $db->mySelect(
            "SELECT c0d, project_no, project_name, project_type
               FROM c_projects
              WHERE deleted = 0 AND (crm_status = 'APPROVED' OR migrated_flag = 1)
              ORDER BY project_no DESC",
            []
        ) ?: [];
        $cats = $db->mySelect(
            "SELECT c0d, category_name, category_code FROM budget_item_categories WHERE is_active = 1 ORDER BY category_name ASC",
            []
        ) ?: [];

        $this->view->setLayout($this->roleLayout());
        $this->view->render('PettyCash/raise', [
            'page_title' => 'Raise Petty Cash',
            'projects'   => $projects,
            'categories' => $cats,
            'fb_msg'     => '',
            'form'       => [],
        ]);
    }

    public function saveAction()
    {
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
            Router::redirect('PettyCash/raise');
            return;
        }
        // Petty cash defaults --------------------------------------------------
        $d = [
            'lpo_type'           => 'PETTY_CASH',
            'source_module'      => 'central',
            'project_id'         => (int)($_POST['project_id'] ?? 0),
            'payee_type'         => 'employee',
            'payee_id'           => $this->currentUserId(),
            'payee_name'         => $_SESSION['full_name'] ?? '',
            'amount'             => (float)($_POST['amount'] ?? 0),
            'currency'           => (string)($_POST['currency'] ?? 'TZS'),
            'purpose'            => (string)($_POST['purpose'] ?? ''),
            'budget_category_id' => (int)($_POST['budget_category_id'] ?? 0),
            // Supplier EFD / VAT capture (payables-side) ---------------------
            'supplier_receipt_type' => (string)($_POST['supplier_receipt_type'] ?? 'NORMAL'),
            'supplier_efd_number'   => (string)($_POST['supplier_efd_number'] ?? ''),
            'supplier_tin'          => (string)($_POST['supplier_tin']         ?? ''),
            'supplier_efd_date'     => (string)($_POST['supplier_efd_date']    ?? ''),
            'vat_amount'            => (float) ($_POST['vat_amount']           ?? 0),
            'vat_inclusive_flag'    => !empty($_POST['vat_inclusive_flag']) ? 1 : 0,
        ];

        $m = new Lpos();
        $r = $m->create($d, $this->currentUserId(), $_SESSION['full_name'] ?? '');
        if (!$r['ok']) {
            $db       = new DB();
            $projects = $db->mySelect("SELECT c0d, project_no, project_name, project_type FROM c_projects WHERE deleted=0 AND (crm_status='APPROVED' OR migrated_flag=1) ORDER BY project_no DESC", []) ?: [];
            $cats     = $db->mySelect("SELECT c0d, category_name, category_code FROM budget_item_categories WHERE is_active=1 ORDER BY category_name ASC", []) ?: [];
            $this->view->setLayout($this->roleLayout());
            $this->view->render('PettyCash/raise', [
                'page_title' => 'Raise Petty Cash',
                'projects'   => $projects,
                'categories' => $cats,
                'fb_msg'     => '<div class="alert alert-danger">' . htmlspecialchars($r['msg']) . '</div>',
                'form'       => $_POST,
            ]);
            return;
        }

        // Auto-submit into PETTY_CASH_APPROVAL chain ---------------------------
        $ac   = new ApprovalChain();
        $l    = $m->byId((int)$r['id']);
        $ref  = $l['lpo_no'] . ' · ' . ($l['payee_name'] ?: '(no payee)') . ' · ' . $l['currency'] . ' ' . number_format((float)$l['amount']);
        $sres = $ac->submit([
            'chain_key'    => 'PETTY_CASH_APPROVAL',
            'entity_type'  => 'lpo',
            'entity_id'    => (int)$r['id'],
            'ref_label'    => $ref,
            'return_url'   => 'Lpos/view/' . (int)$r['id'],
            'user_id'      => $this->currentUserId(),
            'user_name'    => $_SESSION['full_name']       ?? '',
            'user_group'   => $_SESSION['user_group_name'] ?? '',
            'comment'      => 'Petty cash request submitted.',
        ]);
        if ($sres['ok']) {
            $m->markSubmitted((int)$r['id'], (int)$sres['approval_id']);
        }

        Router::redirect('Lpos/view/' . (int)$r['id']);
    }
}
