<?php
class SupplierPaymentsController extends Controller
{
    public function indexAction($page = 1)
    {
        $page    = max(1, (int)$page);
        $perPage = defined('ROWS_PER_PAGE') ? ROWS_PER_PAGE : 20;

        $filters = [
            'q'         => trim((string)($_GET['q']         ?? '')),
            'status'    => trim((string)($_GET['status']    ?? '')),
            'vendor_id' => (int)   ($_GET['vendor_id']      ?? 0),
            'from_date' => trim((string)($_GET['from_date'] ?? '')),
            'to_date'   => trim((string)($_GET['to_date']   ?? '')),
            'method'    => trim((string)($_GET['method']    ?? '')),
        ];

        $m = new SupplierPayments();
        $result = $m->listPaginated($page, $perPage, $filters);

        $qs      = http_build_query(array_filter($filters, fn($v) => $v !== '' && $v !== 0));
        $baseUrl = PROOT . 'SupplierPayments/index/';
        $pg      = Pagination::paginate($result['total'], $perPage, $page, $baseUrl);
        $pgHtml  = $pg['html'];
        if ($qs && $pgHtml) {
            $pgHtml = preg_replace('~href=\'([^\']+)\'~', "href='$1?" . htmlspecialchars($qs) . "'", $pgHtml);
        }

        $this->view->setLayout($this->roleLayout());
        $this->view->render('SupplierPayments/index', [
            'page_title' => 'Supplier Payments',
            'rows'       => $result['rows'],
            'suppliers'  => (new Suppliers())->allActive(),
            'filters'    => $filters,
            'pg_html'    => $pgHtml,
        ]);
    }

    public function recordAction()
    {
        // Optional pre-selected vendor via ?vendor_id=N
        $vendorId = (int)($_GET['vendor_id'] ?? 0);
        $bills    = $vendorId > 0 ? (new SupplierBills())->openBillsForVendor($vendorId) : [];

        $this->view->setLayout($this->roleLayout());
        $this->view->render('SupplierPayments/record', [
            'page_title' => 'Record Supplier Payment',
            'suppliers'  => (new Suppliers())->allActive(),
            'vendor_id'  => $vendorId,
            'bills'      => $bills,
            'form'       => [],
            'fb_msg'     => '',
        ]);
    }

    public function saveAction()
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('SupplierPayments/record'); return; }

        // Marshal allocations from posted arrays
        $allocs = [];
        foreach ((array)($_POST['alloc_bill_id'] ?? []) as $i => $bid) {
            $applied = (float)($_POST['alloc_amount'][$i] ?? 0);
            if ((int)$bid > 0 && $applied > 0) {
                $allocs[] = ['bill_id' => (int)$bid, 'amount_applied' => $applied];
            }
        }
        $body = $_POST + ['allocations' => $allocs];

        $r = (new SupplierPayments())->record($body, $this->currentUserId(), $_SESSION['full_name'] ?? '');
        if (!$r['ok']) {
            $vid = (int)($body['vendor_id'] ?? 0);
            $this->view->setLayout($this->roleLayout());
            $this->view->render('SupplierPayments/record', [
                'page_title' => 'Record Supplier Payment',
                'suppliers'  => (new Suppliers())->allActive(),
                'vendor_id'  => $vid,
                'bills'      => $vid > 0 ? (new SupplierBills())->openBillsForVendor($vid) : [],
                'form'       => $body,
                'fb_msg'     => '<div class="alert alert-danger">' . htmlspecialchars($r['msg']) . '</div>',
            ]);
            return;
        }
        $_SESSION['flash_tenant_msg']  = $r['msg'];
        $_SESSION['flash_tenant_type'] = 'success';
        Router::redirect('SupplierPayments/view/' . $r['id']);
    }

    public function viewAction($id = 0)
    {
        $m = new SupplierPayments();
        $p = $m->byId((int)$id);
        if (!$p) { $this->notFound('Payment'); return; }

        $this->view->setLayout($this->roleLayout());
        $this->view->render('SupplierPayments/view', [
            'page_title'  => $p['payment_no'] . ' · Payment',
            'p'           => $p,
            'allocations' => $m->allocationsFor((int)$id),
        ]);
    }

    public function voidPaymentAction($id = 0)
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('SupplierPayments/view/' . (int)$id); return; }
        $reason = trim((string)($_POST['reason'] ?? ''));
        if ($reason === '') { $_SESSION['flash_tenant_msg'] = 'Reason required.'; $_SESSION['flash_tenant_type'] = 'danger';
            Router::redirect('SupplierPayments/view/' . (int)$id); return; }
        $r = (new SupplierPayments())->voidPayment((int)$id, $reason, $this->currentUserId(), $_SESSION['full_name'] ?? '');
        $_SESSION['flash_tenant_msg']  = $r['msg'];
        $_SESSION['flash_tenant_type'] = $r['ok'] ? 'success' : 'danger';
        Router::redirect('SupplierPayments/view/' . (int)$id);
    }

    private function notFound(string $what): void
    {
        $this->view->setLayout($this->roleLayout());
        $this->view->render('generals/fb_page', [
            'page_title' => 'Not found',
            'fb_msg'     => '<div class="alert alert-danger">' . htmlspecialchars($what) . ' not found.</div>',
        ]);
    }
}
