<?php
class ReceiptsController extends Controller
{
    public function indexAction()
    {
        $m         = new Receipts();
        $projectId = (int)($_GET['project_id'] ?? 0);
        $rows      = $m->list((string)($_GET['type'] ?? ''), $projectId);

        $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('Receipts/index', [
            'page_title'           => 'Customer Receipts',
            'rows'                 => $rows,
            'type'                 => (string)($_GET['type'] ?? ''),
            'types'                => Receipts::TYPES(),
            'filter_project'       => $projectId,
            'filter_project_label' => $projName,
        ]);
    }

    public function recordAction($sale_id = 0)
    {
        $db = new DB();
        $sale = null;
        if ((int)$sale_id > 0) {
            $sm   = new Sales();
            $sale = $sm->byId((int)$sale_id);
            if (!$sale) {
                $this->view->setLayout($this->roleLayout());
                $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-danger">Sale not found.</div>']);
                return;
            }
            if ($sale['invoice_workflow_status'] !== 'ISSUED') {
                $this->view->setLayout($this->roleLayout());
                $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-warning">Sale ' . htmlspecialchars($sale['sale_no'] ?: $sale['invoice_ref']) . ' is not ISSUED — cannot receive payment.</div>']);
                return;
            }
        }
        $banks   = $db->mySelect("SELECT c0d, account_name, bank_name, account_number, currency FROM bank_accounts WHERE is_active = 1 ORDER BY bank_name, account_name", []) ?: [];
        $efds    = $db->mySelect("SELECT c0d, device_serial, device_model, location FROM efd_devices WHERE is_active = 1 ORDER BY device_serial", []) ?: [];

        $this->view->setLayout($this->roleLayout());
        $this->view->render('Receipts/record', [
            'page_title' => 'Record Receipt' . ($sale ? ' · ' . ($sale['sale_no'] ?: $sale['invoice_ref']) : ''),
            'sale'       => $sale,
            'banks'      => $banks,
            'efds'       => $efds,
            'types'      => Receipts::TYPES(),
            'fb_msg'     => '',
            'form'       => [],
        ]);
    }

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

        $m = new Receipts();
        $r = $m->record($_POST, $this->currentUserId(), $_SESSION['full_name'] ?? '');
        if (!$r['ok']) {
            // Re-render form with error
            $db    = new DB();
            $sid   = (int)($_POST['sale_id'] ?? 0);
            $sale  = null;
            if ($sid > 0) { $sm = new Sales(); $sale = $sm->byId($sid); }
            $banks = $db->mySelect("SELECT c0d, account_name, bank_name, account_number, currency FROM bank_accounts WHERE is_active = 1 ORDER BY bank_name, account_name", []) ?: [];
            $efds  = $db->mySelect("SELECT c0d, device_serial, device_model, location FROM efd_devices WHERE is_active = 1 ORDER BY device_serial", []) ?: [];
            $this->view->setLayout($this->roleLayout());
            $this->view->render('Receipts/record', [
                'page_title' => 'Record Receipt',
                'sale'       => $sale,
                'banks'      => $banks,
                'efds'       => $efds,
                'types'      => Receipts::TYPES(),
                'fb_msg'     => '<div class="alert alert-danger">' . htmlspecialchars($r['msg']) . '</div>',
                'form'       => $_POST,
            ]);
            return;
        }
        Router::redirect('Receipts/view/' . (int)$r['id']);
    }

    public function viewAction($id = 0)
    {
        $m = new Receipts();
        $r = $m->byId((int)$id);
        if (!$r) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-danger">Receipt not found.</div>']);
            return;
        }
        $je = [];
        $jls = [];
        if ((int)$r['journal_entry_id'] > 0) {
            $jp  = new JournalPosting();
            $je  = $jp->byId((int)$r['journal_entry_id']);
            $jls = $jp->linesForJe((int)$r['journal_entry_id']);
        }
        $this->view->setLayout($this->roleLayout());
        $this->view->render('Receipts/view', [
            'page_title' => $r['receipt_no'],
            'r'          => $r,
            'types'      => Receipts::TYPES(),
            'je'         => $je,
            'je_lines'   => $jls,
        ]);
    }
}
