<?php
// app/Models/Document.php
class Document {
    public static function byVehicle(int $vehicleId): array {
        $s = db()->prepare('SELECT * FROM documents WHERE vehicle_id=? ORDER BY type');
        $s->execute([$vehicleId]); return $s->fetchAll();
    }
    public static function byUser(int $userId, ?string $type = null): array {
        $sql = 'SELECT * FROM documents WHERE user_id=? AND vehicle_id IS NULL';
        $params = [$userId];
        if($type){ $sql .= ' AND type=?'; $params[]=$type; }
        $s = db()->prepare($sql); $s->execute($params); return $s->fetchAll();
    }
    public static function upsert(array $d): void {
        $sql = 'INSERT INTO documents(user_id,vehicle_id,type,file_path,expiry_date,status)
                VALUES(?,?,?,?,?,?)
                ON DUPLICATE KEY UPDATE file_path=VALUES(file_path),expiry_date=VALUES(expiry_date),status=VALUES(status),uploaded_at=NOW()';
        db()->prepare($sql)->execute([$d['user_id'],$d['vehicle_id']??null,$d['type'],$d['file_path'],$d['expiry_date'],docStatus($d['expiry_date'])]);
    }
    public static function delete(int $id, int $userId): void {
        db()->prepare('DELETE FROM documents WHERE id=? AND user_id=?')->execute([$id,$userId]);
    }
    public static function refreshStatuses(): void {
        $w = function_exists('expiryWarnDays') ? expiryWarnDays() : 30;
        db()->exec("UPDATE documents SET status='expired'  WHERE expiry_date < CURDATE()");
        $s = db()->prepare("UPDATE documents SET status='expiring' WHERE expiry_date >= CURDATE() AND expiry_date <= DATE_ADD(CURDATE(),INTERVAL ? DAY)");
        $s->execute([$w]);
        $s2 = db()->prepare("UPDATE documents SET status='valid' WHERE expiry_date > DATE_ADD(CURDATE(),INTERVAL ? DAY)");
        $s2->execute([$w]);
    }
    /** All personal documents (vehicle_id IS NULL) for a user */
    public static function personalByUser(int $userId): array {
        $s = db()->prepare('SELECT * FROM documents WHERE user_id=? AND vehicle_id IS NULL ORDER BY type');
        $s->execute([$userId]); return $s->fetchAll();
    }
    public static function countValidByOwner(int $ownerId): int {
        $s = db()->prepare("SELECT COUNT(*) FROM documents d JOIN vehicles v ON v.id=d.vehicle_id WHERE v.owner_id=? AND d.status='valid'");
        $s->execute([$ownerId]); return (int)$s->fetchColumn();
    }
    public static function countExpiredByOwner(int $ownerId): int {
        $s = db()->prepare("SELECT COUNT(*) FROM documents d JOIN vehicles v ON v.id=d.vehicle_id WHERE v.owner_id=? AND d.status='expired'");
        $s->execute([$ownerId]); return (int)$s->fetchColumn();
    }
    public static function countExpiringByOwner(int $ownerId): int {
        $s = db()->prepare("SELECT COUNT(*) FROM documents d JOIN vehicles v ON v.id=d.vehicle_id WHERE v.owner_id=? AND d.status='expiring'");
        $s->execute([$ownerId]); return (int)$s->fetchColumn();
    }
    /** Documents expiring soon or expired, for an owner (with vehicle info) */
    public static function alertsByOwner(int $ownerId): array {
        $s = db()->prepare("SELECT d.*, v.plate_number, v.brand, v.model
                            FROM documents d JOIN vehicles v ON v.id=d.vehicle_id
                            WHERE v.owner_id=? AND d.status IN ('expiring','expired')
                            ORDER BY d.expiry_date ASC");
        $s->execute([$ownerId]); return $s->fetchAll();
    }
    /** Expire every document attached to a vehicle (used on ownership transfer) */
    public static function expireAllForVehicle(int $vehicleId): int {
        $s = db()->prepare("UPDATE documents SET expiry_date = DATE_SUB(CURDATE(),INTERVAL 1 DAY), status='expired' WHERE vehicle_id=?");
        $s->execute([$vehicleId]); return $s->rowCount();
    }
}
