<?php
// app/Models/TowLog.php
class TowLog {

    public static function create(array $d): int {
        $s = db()->prepare(
            'INSERT INTO tow_logs(officer_id,vehicle_id,plate_number,reason,tow_location,notes)
             VALUES(?,?,?,?,?,?)'
        );
        $s->execute([
            $d['officer_id'], $d['vehicle_id'], $d['plate_number'],
            $d['reason'], $d['tow_location'] ?? null, $d['notes'] ?? null
        ]);
        return (int)db()->lastInsertId();
    }

    public static function find(int $id): ?array {
        $s = db()->prepare(
            'SELECT t.*, u.name AS officer_name, v.brand, v.model
             FROM tow_logs t
             JOIN users u    ON u.id = t.officer_id
             JOIN vehicles v ON v.id = t.vehicle_id
             WHERE t.id = ?'
        );
        $s->execute([$id]);
        return $s->fetch() ?: null;
    }

    public static function byVehicle(int $vehicleId): array {
        $s = db()->prepare(
            'SELECT t.*, u.name AS officer_name
             FROM tow_logs t
             JOIN users u ON u.id = t.officer_id
             WHERE t.vehicle_id = ?
             ORDER BY t.towed_at DESC'
        );
        $s->execute([$vehicleId]);
        return $s->fetchAll();
    }

    public static function byOfficer(int $officerId, int $limit = 50): array {
        $s = db()->prepare(
            'SELECT t.*, v.brand, v.model
             FROM tow_logs t
             JOIN vehicles v ON v.id = t.vehicle_id
             WHERE t.officer_id = ?
             ORDER BY t.towed_at DESC
             LIMIT ' . (int)$limit
        );
        $s->execute([$officerId]);
        return $s->fetchAll();
    }

    /** هل السيارة محجوزة حالياً؟ */
    public static function activeByVehicle(int $vehicleId): ?array {
        $s = db()->prepare(
            "SELECT * FROM tow_logs WHERE vehicle_id=? AND status='active' ORDER BY towed_at DESC LIMIT 1"
        );
        $s->execute([$vehicleId]);
        return $s->fetch() ?: null;
    }

    public static function release(int $id): void {
        db()->prepare(
            "UPDATE tow_logs SET status='released', released_at=NOW() WHERE id=?"
        )->execute([$id]);
    }
}
