<?php
/**
 * Suppliers — thin CRUD wrapper on the existing `vendors` table
 * (rsflow legacy). Kept lean because the AP module needs only
 * lookup + basic edit; the master data lives in `vendors`.
 */
class Suppliers extends Model
{
    private function s($v): string { return trim((string)$v); }

    public function listPaginated(int $page, int $perPage, array $filters = []): array
    {
        $where  = ['deleted = 0'];
        $params = [];

        if (!empty($filters['q'])) {
            $where[] = '(vendor_name LIKE :q OR vendor_no LIKE :q OR vendor_tin LIKE :q OR vendor_phone_1 LIKE :q)';
            $params[':q'] = '%' . $filters['q'] . '%';
        }
        if (!empty($filters['category'])) { $where[] = 'vendor_category = :c'; $params[':c'] = $this->s($filters['category']); }
        if (!empty($filters['status']))   { $where[] = 'status = :s';          $params[':s'] = $this->s($filters['status']); }

        $whereSql = implode(' AND ', $where);
        $db = new DB();

        $countRs = $db->mySelect("SELECT COUNT(*) AS n FROM vendors WHERE $whereSql", $params);
        $total = (int)($countRs[0]['n'] ?? 0);

        $page    = max(1, $page);
        $perPage = max(1, min(200, $perPage));
        $offset  = ($page - 1) * $perPage;

        $rows = $db->mySelect(
            "SELECT c0d, vendor_no, vendor_name, vendor_tin, vendor_vrn,
                    vendor_phone_1, vendor_email, vendor_category, vendor_city, status
               FROM vendors
              WHERE $whereSql
           ORDER BY vendor_name
              LIMIT $perPage OFFSET $offset",
            $params
        ) ?: [];

        return ['rows' => $rows, 'total' => $total];
    }

    public function byId(int $id): array
    {
        $db = new DB();
        $rs = $db->mySelect("SELECT * FROM vendors WHERE c0d = :id AND deleted = 0 LIMIT 1", [':id' => $id]);
        return $rs[0] ?? [];
    }

    public function allActive(): array
    {
        $db = new DB();
        return $db->mySelect(
            "SELECT c0d, vendor_no, vendor_name, vendor_tin FROM vendors
              WHERE deleted = 0 AND status = 'ACTIVE'
           ORDER BY vendor_name",
            []
        ) ?: [];
    }

    public function create(array $d, int $uid): array
    {
        $name = $this->s($d['vendor_name'] ?? '');
        if ($name === '') return ['ok' => false, 'msg' => 'Supplier name is required.', 'id' => 0];

        $db = new DB();
        $r  = $db->insertUpdate(
            "INSERT INTO vendors
                (vendor_no, vendor_name, vendor_phone_1, vendor_phone_2, vendor_email,
                 vendor_address, vendor_city, vendor_country, vendor_po_box,
                 vendor_tin, vendor_vrn, vendor_category, vendor_poc, vendor_poc_phone,
                 vendor_poc_email, bank_name, bank_account_no, bank_swift, status, created_by)
             VALUES
                (:vn, :n, :p1, :p2, :em, :addr, :city, :ctry, :box,
                 :tin, :vrn, :cat, :poc, :pocp, :poce, :bnk, :bacc, :swift, 'ACTIVE', :uid)",
            [
                ':vn'   => $this->s($d['vendor_no'] ?? '') ?: $this->nextVendorNo(),
                ':n'    => $name,
                ':p1'   => $this->s($d['vendor_phone_1'] ?? ''),
                ':p2'   => $this->s($d['vendor_phone_2'] ?? ''),
                ':em'   => $this->s($d['vendor_email']   ?? ''),
                ':addr' => $this->s($d['vendor_address'] ?? ''),
                ':city' => $this->s($d['vendor_city']    ?? ''),
                ':ctry' => $this->s(($d['vendor_country'] ?? '') ?: 'TANZANIA'),
                ':box'  => $this->s($d['vendor_po_box']  ?? ''),
                ':tin'  => $this->s($d['vendor_tin']     ?? ''),
                ':vrn'  => $this->s($d['vendor_vrn']     ?? ''),
                ':cat'  => $this->s($d['vendor_category']?? ''),
                ':poc'  => $this->s($d['vendor_poc']     ?? ''),
                ':pocp' => $this->s($d['vendor_poc_phone'] ?? ''),
                ':poce' => $this->s($d['vendor_poc_email'] ?? ''),
                ':bnk'  => $this->s($d['bank_name']      ?? ''),
                ':bacc' => $this->s($d['bank_account_no']?? ''),
                ':swift'=> $this->s($d['bank_swift']     ?? ''),
                ':uid'  => $uid,
            ]
        );
        return ['ok' => $r['success'] > 0, 'msg' => 'Supplier added.', 'id' => (int)$r['last_id']];
    }

    public function update(int $id, array $d, int $uid): array
    {
        if (!$this->byId($id)) return ['ok' => false, 'msg' => 'Supplier not found.', 'id' => 0];
        $name = $this->s($d['vendor_name'] ?? '');
        if ($name === '') return ['ok' => false, 'msg' => 'Supplier name is required.', 'id' => 0];

        $db = new DB();
        $db->insertUpdate(
            "UPDATE vendors SET
                vendor_name = :n, vendor_phone_1 = :p1, vendor_phone_2 = :p2, vendor_email = :em,
                vendor_address = :addr, vendor_city = :city, vendor_country = :ctry, vendor_po_box = :box,
                vendor_tin = :tin, vendor_vrn = :vrn, vendor_category = :cat,
                vendor_poc = :poc, vendor_poc_phone = :pocp, vendor_poc_email = :poce,
                bank_name = :bnk, bank_account_no = :bacc, bank_swift = :swift,
                status = :st, edited_by = :uid, edited_on = NOW()
              WHERE c0d = :id",
            [
                ':n'    => $name,
                ':p1'   => $this->s($d['vendor_phone_1'] ?? ''),
                ':p2'   => $this->s($d['vendor_phone_2'] ?? ''),
                ':em'   => $this->s($d['vendor_email']   ?? ''),
                ':addr' => $this->s($d['vendor_address'] ?? ''),
                ':city' => $this->s($d['vendor_city']    ?? ''),
                ':ctry' => $this->s(($d['vendor_country'] ?? '') ?: 'TANZANIA'),
                ':box'  => $this->s($d['vendor_po_box']  ?? ''),
                ':tin'  => $this->s($d['vendor_tin']     ?? ''),
                ':vrn'  => $this->s($d['vendor_vrn']     ?? ''),
                ':cat'  => $this->s($d['vendor_category']?? ''),
                ':poc'  => $this->s($d['vendor_poc']     ?? ''),
                ':pocp' => $this->s($d['vendor_poc_phone'] ?? ''),
                ':poce' => $this->s($d['vendor_poc_email'] ?? ''),
                ':bnk'  => $this->s($d['bank_name']      ?? ''),
                ':bacc' => $this->s($d['bank_account_no']?? ''),
                ':swift'=> $this->s($d['bank_swift']     ?? ''),
                ':st'   => $this->s(($d['status'] ?? '') ?: 'ACTIVE'),
                ':uid'  => $uid,
                ':id'   => $id,
            ]
        );
        return ['ok' => true, 'msg' => 'Supplier updated.', 'id' => $id];
    }

    private function nextVendorNo(): string
    {
        $db = new DB();
        $rs = $db->mySelect("SELECT vendor_no FROM vendors WHERE vendor_no LIKE 'V-%' ORDER BY c0d DESC LIMIT 1", []);
        $n = 1;
        if (!empty($rs) && preg_match('/V-(\d+)/', $rs[0]['vendor_no'], $m)) $n = (int)$m[1] + 1;
        return sprintf('V-%04d', $n);
    }
}
