<?php
class TruckDocs extends Model
{
    private function s($v): string { return trim((string)$v); }

    /** All docs for a truck, joined to doc type for display. */
    public function forTruck(int $truckId): array
    {
        $db = new DB();
        return $db->mySelect(
            "SELECT d.c0d, d.doc_type_id, dt.display_name AS doc_type_name, dt.has_expiry, dt.warn_days,
                    d.doc_no, d.issuer, d.issued_on, d.expires_on,
                    d.cost_amount, d.cost_currency,
                    d.file_url, d.file_name, d.file_size, d.notes,
                    d.created_on, d.edited_on
               FROM truck_docs d
          LEFT JOIN truck_doc_types dt ON dt.c0d = d.doc_type_id
              WHERE d.truck_id = :id AND d.deleted = 0
           ORDER BY dt.sort_order ASC, d.issued_on DESC",
            [':id' => $truckId]
        ) ?: [];
    }

    public function byId(int $id): array
    {
        $db = new DB();
        $rs = $db->mySelect(
            "SELECT d.*, dt.display_name AS doc_type_name
               FROM truck_docs d
          LEFT JOIN truck_doc_types dt ON dt.c0d = d.doc_type_id
              WHERE d.c0d = :id AND d.deleted = 0
              LIMIT 1",
            [':id' => $id]
        );
        return $rs[0] ?? [];
    }

    public function create(array $d, int $uid): array
    {
        $truckId  = (int)($d['truck_id']    ?? 0);
        $typeId   = (int)($d['doc_type_id'] ?? 0);
        if (!$truckId || !$typeId) {
            return ['ok' => false, 'msg' => 'Truck and document type are required.', 'id' => 0];
        }

        $db = new DB();
        $r  = $db->insertUpdate(
            "INSERT INTO truck_docs
                (tenant_id, truck_id, doc_type_id, doc_no, issuer, issued_on, expires_on,
                 cost_amount, cost_currency, file_url, file_name, file_size, notes,
                 created_by, created_on)
             VALUES
                (:tenant, :truck, :type, :doc_no, :issuer, :issued, :expires,
                 :amt, :cur, :url, :fname, :fsize, :notes,
                 :uid, NOW())",
            [
                ':tenant'  => defined('DEFAULT_TENANT_ID') ? DEFAULT_TENANT_ID : 1,
                ':truck'   => $truckId,
                ':type'    => $typeId,
                ':doc_no'  => $this->s($d['doc_no'] ?? ''),
                ':issuer'  => $this->s($d['issuer'] ?? ''),
                ':issued'  => !empty($d['issued_on'])  ? $this->s($d['issued_on'])  : null,
                ':expires' => !empty($d['expires_on']) ? $this->s($d['expires_on']) : null,
                ':amt'     => isset($d['cost_amount']) && $d['cost_amount'] !== '' ? (float)str_replace(',', '', $d['cost_amount']) : null,
                ':cur'     => $this->s(($d['cost_currency'] ?? '') ?: (defined('DEFAULT_CURRENCY') ? DEFAULT_CURRENCY : 'TZS')),
                ':url'     => $this->s($d['file_url']  ?? ''),
                ':fname'   => $this->s($d['file_name'] ?? ''),
                ':fsize'   => isset($d['file_size']) ? (int)$d['file_size'] : null,
                ':notes'   => $this->s($d['notes'] ?? ''),
                ':uid'     => $uid,
            ]
        );
        return ['ok' => $r['success'] > 0, 'msg' => $r['success'] > 0 ? 'Document uploaded.' : 'Upload failed.', 'id' => (int)$r['last_id']];
    }

    public function softDelete(int $id, int $uid): array
    {
        $db = new DB();
        $db->insertUpdate(
            "UPDATE truck_docs SET deleted = 1, edited_by = :uid, edited_on = NOW() WHERE c0d = :id",
            [':uid' => $uid, ':id' => $id]
        );
        return ['ok' => true];
    }
}
