<?php

class Trailer extends BaseModel
{
    public function all(?string $search=null): array
    {
        $sql='SELECT trailers.*,trucks.unit_number truck_number,carriers.company_name carrier_name FROM trailers LEFT JOIN trucks ON trucks.id=trailers.truck_id LEFT JOIN carriers ON carriers.id=trailers.carrier_id';
        $params=[];
        if($search){$sql.=' WHERE trailers.trailer_number LIKE ? OR trailers.plate_number LIKE ? OR trailers.type LIKE ? OR trailers.reefer_unit_number LIKE ? OR trucks.unit_number LIKE ? OR carriers.company_name LIKE ?';$term="%{$search}%";$params=[$term,$term,$term,$term,$term,$term];}
        $sql.=' ORDER BY trailers.id DESC';$stmt=$this->db->prepare($sql);$stmt->execute($params);return $stmt->fetchAll();
    }

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

    public function create(array $data): void
    {
        $stmt=$this->db->prepare('INSERT INTO trailers (trailer_number,type,plate_number,registration_expiry,inspection_expiry,carrier_id,ownership_type,length_ft,max_payload_lbs,door_type,food_grade,air_ride,liftgate,hazmat_ready,reefer_capable,reefer_make,reefer_model,reefer_unit_number,reefer_year,temperature_unit,min_temperature,max_temperature,current_setpoint,current_temperature,reefer_mode,reefer_hours,reefer_fuel_level,last_temperature_at,last_washout_date,reefer_service_due,telematics_id,equipment_features,status,truck_id,notes) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)');
        $stmt->execute($this->payload($data));
    }

    public function update(int $id,array $data): void
    {
        $stmt=$this->db->prepare('UPDATE trailers SET trailer_number=?,type=?,plate_number=?,registration_expiry=?,inspection_expiry=?,carrier_id=?,ownership_type=?,length_ft=?,max_payload_lbs=?,door_type=?,food_grade=?,air_ride=?,liftgate=?,hazmat_ready=?,reefer_capable=?,reefer_make=?,reefer_model=?,reefer_unit_number=?,reefer_year=?,temperature_unit=?,min_temperature=?,max_temperature=?,current_setpoint=?,current_temperature=?,reefer_mode=?,reefer_hours=?,reefer_fuel_level=?,last_temperature_at=?,last_washout_date=?,reefer_service_due=?,telematics_id=?,equipment_features=?,status=?,truck_id=?,notes=? WHERE id=?');
        $params=$this->payload($data);$params[]=$id;$stmt->execute($params);
    }

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

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

    private function payload(array $data): array
    {
        $features=[];
        foreach(['straps','load_bars','pallet_jack','tarps','chains','side_kit','conestoga','vented'] as $feature){if(!empty($data['feature_'.$feature]))$features[]=$feature;}
        $reefer=!empty($data['reefer_capable']) || stripos((string)($data['type']??''),'reefer')!==false;
        return [
            trim((string)($data['trailer_number']??'')),trim((string)($data['type']??''))?:null,trim((string)($data['plate_number']??''))?:null,
            !empty($data['registration_expiry'])?$data['registration_expiry']:null,!empty($data['inspection_expiry'])?$data['inspection_expiry']:null,
            !empty($data['carrier_id'])?(int)$data['carrier_id']:null,
            in_array(($data['ownership_type']??''),['carrier_owned','company_owned','leased','rental','customer_owned'],true)?$data['ownership_type']:'carrier_owned',
            ($data['length_ft']??'')!==''?(float)$data['length_ft']:null,($data['max_payload_lbs']??'')!==''?(int)$data['max_payload_lbs']:null,
            trim((string)($data['door_type']??''))?:null,!empty($data['food_grade'])?1:0,!empty($data['air_ride'])?1:0,!empty($data['liftgate'])?1:0,!empty($data['hazmat_ready'])?1:0,
            $reefer?1:0,trim((string)($data['reefer_make']??''))?:null,trim((string)($data['reefer_model']??''))?:null,trim((string)($data['reefer_unit_number']??''))?:null,
            ($data['reefer_year']??'')!==''?(int)$data['reefer_year']:null,in_array(($data['temperature_unit']??''),['F','C'],true)?$data['temperature_unit']:'F',
            ($data['min_temperature']??'')!==''?(float)$data['min_temperature']:null,($data['max_temperature']??'')!==''?(float)$data['max_temperature']:null,
            ($data['current_setpoint']??'')!==''?(float)$data['current_setpoint']:null,($data['current_temperature']??'')!==''?(float)$data['current_temperature']:null,
            in_array(($data['reefer_mode']??''),['continuous','cycle_sentry','off'],true)?$data['reefer_mode']:null,
            ($data['reefer_hours']??'')!==''?(float)$data['reefer_hours']:null,($data['reefer_fuel_level']??'')!==''?(float)$data['reefer_fuel_level']:null,
            !empty($data['last_temperature_at'])?str_replace('T',' ',$data['last_temperature_at']):null,!empty($data['last_washout_date'])?$data['last_washout_date']:null,
            !empty($data['reefer_service_due'])?$data['reefer_service_due']:null,trim((string)($data['telematics_id']??''))?:null,
            $features?json_encode($features):null,
            in_array(($data['status']??''),['available','assigned','maintenance','inactive'],true)?$data['status']:'available',
            !empty($data['truck_id'])?(int)$data['truck_id']:null,trim((string)($data['notes']??''))?:null,
        ];
    }
}
