<?php
// app/Models/Vehicle.php
class Vehicle {
    public static function find(int $id): ?array {
        $s = db()->prepare('SELECT v.*,u.name as owner_name,u.phone as owner_phone,u.email as owner_email,d.name as driver_name,d.phone as driver_phone,d.email as driver_email FROM vehicles v LEFT JOIN users u ON u.id=v.owner_id LEFT JOIN users d ON d.id=v.current_driver_id WHERE v.id=?');
        $s->execute([$id]); return $s->fetch() ?: null;
    }
    public static function findByPlate(string $plate): ?array {
        $s = db()->prepare('SELECT v.*,u.name as owner_name,u.phone as owner_phone,u.email as owner_email,d.name as driver_name,d.phone as driver_phone,d.email as driver_email FROM vehicles v LEFT JOIN users u ON u.id=v.owner_id LEFT JOIN users d ON d.id=v.current_driver_id WHERE v.plate_number=?');
        $s->execute([$plate]); return $s->fetch() ?: null;
    }
    public static function byOwner(int $ownerId): array {
        $s = db()->prepare('SELECT v.*,d.name as driver_name FROM vehicles v LEFT JOIN users d ON d.id=v.current_driver_id WHERE v.owner_id=? ORDER BY v.created_at DESC');
        $s->execute([$ownerId]); return $s->fetchAll();
    }
    public static function byDriver(int $driverId): array {
        $s = db()->prepare('SELECT v.*,u.name as owner_name FROM vehicles v JOIN vehicle_drivers vd ON vd.vehicle_id=v.id LEFT JOIN users u ON u.id=v.owner_id WHERE vd.driver_id=? ORDER BY v.brand');
        $s->execute([$driverId]); return $s->fetchAll();
    }
    public static function create(array $d): int {
        $s = db()->prepare('INSERT INTO vehicles(owner_id,plate_number,brand,model,color,year,fuel_type) VALUES(?,?,?,?,?,?,?)');
        $s->execute([$d['owner_id'],$d['plate_number'],$d['brand'],$d['model'],$d['color']??null,$d['year']??null,$d['fuel_type']??'petrol']);
        return (int)db()->lastInsertId();
    }
    public static function update(int $id, array $d): void {
        $sets=[]; $vals=[];
        foreach(['plate_number','brand','model','color','year','fuel_type','current_driver_id'] as $f) {
            if(array_key_exists($f,$d)){ $sets[]="$f=?"; $vals[]=$d[$f]; }
        }
        if(!$sets) return;
        $vals[]=$id;
        db()->prepare('UPDATE vehicles SET '.implode(',',$sets).' WHERE id=?')->execute($vals);
    }
    public static function delete(int $id): void {
        db()->prepare('DELETE FROM vehicles WHERE id=?')->execute([$id]);
    }
    // Drivers
    public static function getDrivers(int $vehicleId): array {
        $s = db()->prepare('SELECT u.id,u.name,u.email,u.phone FROM vehicle_drivers vd JOIN users u ON u.id=vd.driver_id WHERE vd.vehicle_id=? ORDER BY u.name');
        $s->execute([$vehicleId]); return $s->fetchAll();
    }
    public static function addDriver(int $vehicleId, int $driverId): void {
        try {
            db()->prepare('INSERT IGNORE INTO vehicle_drivers(vehicle_id,driver_id) VALUES(?,?)')->execute([$vehicleId,$driverId]);
        } catch(PDOException $e) {}
    }
    public static function removeDriver(int $vehicleId, int $driverId): void {
        db()->prepare('DELETE FROM vehicle_drivers WHERE vehicle_id=? AND driver_id=?')->execute([$vehicleId,$driverId]);
        // Clear current driver if same
        db()->prepare("UPDATE vehicles SET current_driver_id=NULL WHERE id=? AND current_driver_id=?")->execute([$vehicleId,$driverId]);
    }
    public static function countByOwner(int $ownerId): int {
        $s = db()->prepare('SELECT COUNT(*) FROM vehicles WHERE owner_id=?');
        $s->execute([$ownerId]); return (int)$s->fetchColumn();
    }
    /**
     * Transfer ownership to a new owner.
     * Clears the current driver and linked drivers, and expires all the
     * vehicle's documents so the new owner must re-upload valid ones.
     */
    public static function transferOwnership(int $vehicleId, int $newOwnerId): void {
        require_once __DIR__.'/Document.php';
        $pdo = db();
        $pdo->prepare('UPDATE vehicles SET owner_id=?, current_driver_id=NULL WHERE id=?')
            ->execute([$newOwnerId, $vehicleId]);
        $pdo->prepare('DELETE FROM vehicle_drivers WHERE vehicle_id=?')->execute([$vehicleId]);
        Document::expireAllForVehicle($vehicleId);
    }
}
