<?php
class PaymentVouchersController extends Controller
{
    public function indexAction()
    {
        $m    = new PaymentVouchers();
        $rows = $m->list((string)($_GET['status'] ?? ''));
        $this->view->setLayout($this->roleLayout());
        $this->view->render('PaymentVouchers/index', [
            'page_title' => 'Payment Vouchers',
            'rows'       => $rows,
            'status'     => (string)($_GET['status'] ?? ''),
        ]);
    }

    public function viewAction($id = 0)
    {
        $m  = new PaymentVouchers();
        $pv = $m->byId((int)$id);
        if (!$pv) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-danger">PV not found.</div>']);
            return;
        }
        $db    = new DB();
        $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", []) ?: [];
        $payments = $db->mySelect(
            "SELECT p.*, ba.account_name AS bank_account_name, ba.bank_name
               FROM payments p LEFT JOIN bank_accounts ba ON ba.c0d = p.bank_account_id
              WHERE p.payment_voucher_id = :id AND p.deleted = 0 ORDER BY p.c0d DESC",
            [':id' => (int)$id]
        ) ?: [];

        $group     = strtolower($this->currentUserGroup());
        $canPrep   = in_array($group, ['accountant','administrator'], true);
        $canSched  = in_array($group, ['accountant','finance manager','administrator'], true);
        $canRecord = in_array($group, ['finance manager','accountant','administrator'], true);

        $this->view->setLayout($this->roleLayout());
        $this->view->render('PaymentVouchers/view', [
            'page_title' => $pv['pv_no'] . ' · ' . $pv['payee_name'],
            'pv'         => $pv,
            'banks'      => $banks,
            'payments'   => $payments,
            'can_sched'  => $canSched,
            'can_record' => $canRecord,
        ]);
    }

    /** Prep a DRAFT PV from an APPROVED LPO (Accountant / Admin). */
    public function prepAjAction()
    {
        $lpo_id = (int)($_POST['lpo_id'] ?? 0);
        $notes  = (string)($_POST['notes'] ?? '');
        $group  = strtolower($this->currentUserGroup());
        if (!in_array($group, ['accountant','administrator'], true)) {
            $this->jsonResponse(['ok' => false, 'msg' => 'Only Accountant / Administrator can prepare a PV.']); return;
        }
        $m = new PaymentVouchers();
        $r = $m->prepFromLpo($lpo_id, $this->currentUserId(), $_SESSION['full_name'] ?? '', $notes);
        $this->jsonResponse($r);
    }

    /** Schedule a DRAFT PV (Accountant / FM / Admin). */
    public function scheduleAjAction()
    {
        $pv_id           = (int)($_POST['pv_id'] ?? 0);
        $scheduled_on    = (string)($_POST['scheduled_on'] ?? '');
        $bank_account_id = (int)($_POST['bank_account_id'] ?? 0);
        $notes           = (string)($_POST['notes'] ?? '');
        $group = strtolower($this->currentUserGroup());
        if (!in_array($group, ['accountant','finance manager','administrator'], true)) {
            $this->jsonResponse(['ok' => false, 'msg' => 'Only Accountant / FM / Administrator can schedule.']); return;
        }
        $m = new PaymentVouchers();
        $r = $m->schedule($pv_id, $scheduled_on, $bank_account_id, $this->currentUserId(), $_SESSION['full_name'] ?? '', $notes);
        $this->jsonResponse($r);
    }

    /** Record an actual payment (FM / Accountant / Admin). */
    public function recordPaymentAjAction()
    {
        $pv_id = (int)($_POST['pv_id'] ?? 0);
        $group = strtolower($this->currentUserGroup());
        if (!in_array($group, ['finance manager','accountant','administrator'], true)) {
            $this->jsonResponse(['ok' => false, 'msg' => 'Only FM / Accountant / Administrator can record a payment.']); return;
        }
        $m = new PaymentVouchers();
        $r = $m->recordPayment($pv_id, $_POST, $this->currentUserId());
        $this->jsonResponse($r);
    }
}
