<?php
class PayablesController extends Controller
{
    /**
     * Unified Payables queue: every LPO regardless of type/module that is
     * APPROVED and awaiting PV prep (Accountant) or scheduling (FM).
     */
    public function indexAction()
    {
        $db = new DB();
        $rows = $db->mySelect(
            "SELECT l.c0d, l.lpo_no, l.lpo_type, l.source_module, l.payee_name, l.amount, l.currency,
                    l.purpose, l.cash_out_status, l.requested_by_name, l.requested_on,
                    l.approval_id,
                    p.project_no, p.project_name,
                    (SELECT COUNT(*) FROM payment_vouchers pv WHERE pv.lpo_id = l.c0d AND pv.deleted = 0) AS pv_count
               FROM lpos l
          LEFT JOIN c_projects p ON p.c0d = l.project_id
              WHERE l.deleted = 0
                AND l.cash_out_status IN ('APPROVED','ISSUED')
              ORDER BY l.edited_on DESC, l.c0d DESC",
            []
        ) ?: [];

        // Buckets ----------------------------------------------------------
        $needsPv = array_values(array_filter($rows, fn($r) => (int)$r['pv_count'] === 0));
        $hasPv   = array_values(array_filter($rows, fn($r) => (int)$r['pv_count']  > 0));

        $this->view->setLayout($this->roleLayout());
        $this->view->render('Payables/index', [
            'page_title' => 'Payables · unified queue',
            'needs_pv'   => $needsPv,
            'has_pv'     => $hasPv,
            'types'      => Lpos::TYPES(),
        ]);
    }
}
