<?php
// app/Models/Transfer.php
// سجل عمليات نقل ملكية المركبات

class Transfer {
    public static function record(int $vehicleId, ?int $fromOwner, int $toOwner, ?int $byUser, string $plate): int {
        $s = db()->prepare(
            'INSERT INTO ownership_transfers (vehicle_id, plate_number, from_owner_id, to_owner_id, performed_by)
             VALUES (?,?,?,?,?)'
        );
        $s->execute([$vehicleId, $plate, $fromOwner, $toOwner, $byUser]);
        return (int)db()->lastInsertId();
    }

    public static function recent(int $limit = 50): array {
        $limit = max(1, min($limit, 200));
        $s = db()->prepare(
            'SELECT tr.*, f.name AS from_name, rcv.name AS to_name, p.name AS by_name
             FROM ownership_transfers tr
             LEFT JOIN users f  ON f.id  = tr.from_owner_id
             LEFT JOIN users rcv ON rcv.id = tr.to_owner_id
             LEFT JOIN users p  ON p.id  = tr.performed_by
             ORDER BY tr.created_at DESC LIMIT '.$limit
        );
        $s->execute();
        return $s->fetchAll();
    }

    public static function forVehicle(int $vehicleId): array {
        $s = db()->prepare(
            'SELECT tr.*, f.name AS from_name, rcv.name AS to_name
             FROM ownership_transfers tr
             LEFT JOIN users f  ON f.id  = tr.from_owner_id
             LEFT JOIN users rcv ON rcv.id = tr.to_owner_id
             WHERE tr.vehicle_id=? ORDER BY tr.created_at DESC'
        );
        $s->execute([$vehicleId]);
        return $s->fetchAll();
    }
}
