<?php

class Driver extends BaseModel
{
    public function all(?string $search = null): array
    {
        $sql = 'SELECT drivers.*, carriers.company_name AS carrier_name
                FROM drivers LEFT JOIN carriers ON carriers.id=drivers.carrier_id';
        $params = [];
        if ($search) {
            $sql .= ' WHERE drivers.name LIKE ? OR drivers.email LIKE ? OR drivers.phone LIKE ? OR drivers.license_number LIKE ? OR carriers.company_name LIKE ?';
            $term = "%{$search}%";
            $params = [$term,$term,$term,$term,$term];
        }
        $sql .= ' ORDER BY drivers.id DESC';
        $stmt=$this->db->prepare($sql);$stmt->execute($params);return $stmt->fetchAll();
    }

    public function find(int $id): ?array
    {
        $stmt=$this->db->prepare('SELECT drivers.*,carriers.company_name carrier_name FROM drivers LEFT JOIN carriers ON carriers.id=drivers.carrier_id WHERE drivers.id=?');
        $stmt->execute([$id]);return $stmt->fetch()?:null;
    }

    public function create(array $data): void
    {
        $stmt=$this->db->prepare('INSERT INTO drivers (name,email,phone,license_number,license_expiry,medical_card_expiry,carrier_id,employment_type,pay_type,rate,status,address,notes) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)');
        $stmt->execute($this->payload($data));
    }

    public function update(int $id,array $data): void
    {
        $stmt=$this->db->prepare('UPDATE drivers SET name=?,email=?,phone=?,license_number=?,license_expiry=?,medical_card_expiry=?,carrier_id=?,employment_type=?,pay_type=?,rate=?,status=?,address=?,notes=? WHERE id=?');
        $params=$this->payload($data);$params[]=$id;$stmt->execute($params);
    }

    public function delete(int $id): void
    {
        $this->db->prepare('DELETE FROM drivers WHERE id=?')->execute([$id]);
    }

    public function available(?int $carrierId=null): array
    {
        $sql="SELECT drivers.id,drivers.name,drivers.carrier_id,carriers.company_name carrier_name FROM drivers LEFT JOIN carriers ON carriers.id=drivers.carrier_id WHERE drivers.status IN ('available','on_load')";
        $params=[];
        if($carrierId){$sql.=' AND drivers.carrier_id=?';$params[]=$carrierId;}
        $sql.=' ORDER BY carriers.company_name,drivers.name';
        $stmt=$this->db->prepare($sql);$stmt->execute($params);return $stmt->fetchAll();
    }

    private function payload(array $data): array
    {
        return [
            trim((string)($data['name']??'')),
            trim((string)($data['email']??''))?:null,
            trim((string)($data['phone']??''))?:null,
            trim((string)($data['license_number']??''))?:null,
            !empty($data['license_expiry'])?$data['license_expiry']:null,
            !empty($data['medical_card_expiry'])?$data['medical_card_expiry']:null,
            !empty($data['carrier_id'])?(int)$data['carrier_id']:null,
            in_array(($data['employment_type']??''),['carrier_driver','owner_operator','company_driver','leased_driver'],true)?$data['employment_type']:'carrier_driver',
            in_array(($data['pay_type']??''),['percentage','per_mile','fixed'],true)?$data['pay_type']:'percentage',
            (float)($data['rate']??0),
            in_array(($data['status']??''),['available','on_load','inactive'],true)?$data['status']:'available',
            trim((string)($data['address']??''))?:null,
            trim((string)($data['notes']??''))?:null,
        ];
    }
}
