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

    public function listPaginated(int $page, int $perPage, array $filters = []): array
    {
        $where  = ['d.deleted = 0', 'd.tenant_id = :tenant'];
        $params = [':tenant' => defined('DEFAULT_TENANT_ID') ? DEFAULT_TENANT_ID : 1];

        if (!empty($filters['q'])) {
            $where[] = '(d.full_name LIKE :q OR d.employee_no LIKE :q OR d.id_no LIKE :q OR d.phone_1 LIKE :q OR d.licence_no LIKE :q)';
            $params[':q'] = '%' . $filters['q'] . '%';
        }
        if (!empty($filters['status'])) {
            $where[] = 'd.status = :status';
            $params[':status'] = $this->s($filters['status']);
        }
        if (!empty($filters['licence_expiring_days'])) {
            $where[] = 'd.licence_expires IS NOT NULL AND d.licence_expires <= DATE_ADD(CURDATE(), INTERVAL :days DAY)';
            $params[':days'] = (int)$filters['licence_expiring_days'];
        }

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

        $countRs = $db->mySelect("SELECT COUNT(*) AS n FROM drivers d 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 d.c0d, d.employee_no, d.full_name, d.phone_1, d.licence_no, d.licence_class,
                    d.licence_expires, d.hire_date, d.status, d.photo_url
               FROM drivers d
              WHERE $whereSql
           ORDER BY d.full_name ASC
              LIMIT $perPage OFFSET $offset",
            $params
        ) ?: [];

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

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

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

        $db = new DB();
        $r  = $db->insertUpdate(
            "INSERT INTO drivers
                (tenant_id, employee_no, full_name, id_no, phone_1, phone_2, email,
                 dob, gender, address, city, country, next_of_kin_name, next_of_kin_phone,
                 licence_no, licence_class, licence_expires, hire_date, status, branch_id,
                 photo_url, blood_group, notes, created_by, created_on)
             VALUES
                (:tenant, :emp, :name, :idno, :p1, :p2, :em,
                 :dob, :gen, :addr, :city, :ctry, :nokn, :nokp,
                 :lic, :licc, :lice, :hire, :status, :branch,
                 :photo, :bg, :notes, :uid, NOW())",
            [
                ':tenant' => defined('DEFAULT_TENANT_ID') ? DEFAULT_TENANT_ID : 1,
                ':emp'    => $this->s($d['employee_no'] ?? ''),
                ':name'   => $name,
                ':idno'   => $this->s($d['id_no']   ?? ''),
                ':p1'     => $this->s($d['phone_1'] ?? ''),
                ':p2'     => $this->s($d['phone_2'] ?? ''),
                ':em'     => $this->s($d['email']   ?? ''),
                ':dob'    => !empty($d['dob']) ? $this->s($d['dob']) : null,
                ':gen'    => $this->s($d['gender']  ?? ''),
                ':addr'   => $this->s($d['address'] ?? ''),
                ':city'   => $this->s($d['city']    ?? ''),
                ':ctry'   => $this->s(($d['country'] ?? '') ?: 'TANZANIA'),
                ':nokn'   => $this->s($d['next_of_kin_name']  ?? ''),
                ':nokp'   => $this->s($d['next_of_kin_phone'] ?? ''),
                ':lic'    => $this->s($d['licence_no']    ?? ''),
                ':licc'   => $this->s($d['licence_class'] ?? ''),
                ':lice'   => !empty($d['licence_expires']) ? $this->s($d['licence_expires']) : null,
                ':hire'   => !empty($d['hire_date'])       ? $this->s($d['hire_date'])       : null,
                ':status' => $this->s(($d['status'] ?? '') ?: 'available'),
                ':branch' => !empty($d['branch_id']) ? (int)$d['branch_id'] : null,
                ':photo'  => $this->s($d['photo_url'] ?? '') ?: null,
                ':bg'     => strtoupper($this->s($d['blood_group'] ?? '')) ?: null,
                ':notes'  => $this->s($d['notes'] ?? ''),
                ':uid'    => $uid,
            ]
        );
        return ['ok' => $r['success'] > 0, 'msg' => $r['success'] > 0 ? 'Driver added.' : 'Save failed.', 'id' => (int)$r['last_id']];
    }

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

        $db = new DB();
        $db->insertUpdate(
            "UPDATE drivers SET
                employee_no = :emp, full_name = :name, id_no = :idno,
                phone_1 = :p1, phone_2 = :p2, email = :em,
                dob = :dob, gender = :gen, address = :addr, city = :city, country = :ctry,
                next_of_kin_name = :nokn, next_of_kin_phone = :nokp,
                licence_no = :lic, licence_class = :licc, licence_expires = :lice,
                hire_date = :hire, status = :status, branch_id = :branch,
                blood_group = :bg, notes = :notes,
                edited_by = :uid, edited_on = NOW()
              WHERE c0d = :id AND deleted = 0",
            [
                ':emp'  => $this->s($d['employee_no'] ?? ''),
                ':name' => $name,
                ':idno' => $this->s($d['id_no']   ?? ''),
                ':p1'   => $this->s($d['phone_1'] ?? ''),
                ':p2'   => $this->s($d['phone_2'] ?? ''),
                ':em'   => $this->s($d['email']   ?? ''),
                ':dob'  => !empty($d['dob']) ? $this->s($d['dob']) : null,
                ':gen'  => $this->s($d['gender']  ?? ''),
                ':addr' => $this->s($d['address'] ?? ''),
                ':city' => $this->s($d['city']    ?? ''),
                ':ctry' => $this->s(($d['country'] ?? '') ?: 'TANZANIA'),
                ':nokn' => $this->s($d['next_of_kin_name']  ?? ''),
                ':nokp' => $this->s($d['next_of_kin_phone'] ?? ''),
                ':lic'  => $this->s($d['licence_no']    ?? ''),
                ':licc' => $this->s($d['licence_class'] ?? ''),
                ':lice' => !empty($d['licence_expires']) ? $this->s($d['licence_expires']) : null,
                ':hire' => !empty($d['hire_date'])       ? $this->s($d['hire_date'])       : null,
                ':status'=> $this->s(($d['status'] ?? '') ?: 'available'),
                ':branch'=> !empty($d['branch_id']) ? (int)$d['branch_id'] : null,
                ':bg'    => strtoupper($this->s($d['blood_group'] ?? '')) ?: null,
                ':notes' => $this->s($d['notes'] ?? ''),
                ':uid'   => $uid,
                ':id'    => $id,
            ]
        );
        return ['ok' => true, 'msg' => 'Driver updated.', 'id' => $id];
    }

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