<?php
// app/Models/InviteCode.php

class InviteCode {

    /** توليد كود عشوائي فريد 8 أحرف */
    public static function generate(int $ownerId, ?int $vehicleId = null): string {
        do {
            $code = strtoupper(substr(bin2hex(random_bytes(5)), 0, 8));
        } while (self::findByCode($code));

        $expires = date('Y-m-d H:i:s', strtotime('+7 days'));
        db()->prepare(
            'INSERT INTO invite_codes(code, owner_id, vehicle_id, expires_at) VALUES(?,?,?,?)'
        )->execute([$code, $ownerId, $vehicleId, $expires]);

        return $code;
    }

    /** البحث عن كود */
    public static function findByCode(string $code): ?array {
        $s = db()->prepare(
            'SELECT ic.*, u.name as owner_name, v.plate_number, v.brand, v.model
             FROM invite_codes ic
             JOIN users u ON u.id = ic.owner_id
             LEFT JOIN vehicles v ON v.id = ic.vehicle_id
             WHERE ic.code = ?'
        );
        $s->execute([strtoupper($code)]);
        return $s->fetch() ?: null;
    }

    /** أكواد المالك */
    public static function byOwner(int $ownerId): array {
        $s = db()->prepare(
            'SELECT ic.*, v.plate_number, v.brand, v.model, u.name as used_by_name
             FROM invite_codes ic
             LEFT JOIN vehicles v ON v.id = ic.vehicle_id
             LEFT JOIN users u ON u.id = ic.used_by
             WHERE ic.owner_id = ?
             ORDER BY ic.created_at DESC'
        );
        $s->execute([$ownerId]);
        return $s->fetchAll();
    }

    /** استخدام الكود من قِبل السائق */
    public static function redeem(string $code, int $driverId): array {
        $invite = self::findByCode($code);

        if (!$invite) {
            return ['success' => false, 'msg' => 'الكود غير صحيح'];
        }
        if ($invite['used_by']) {
            return ['success' => false, 'msg' => 'هذا الكود مستخدم مسبقاً'];
        }
        if ($invite['expires_at'] && strtotime($invite['expires_at']) < time()) {
            return ['success' => false, 'msg' => 'انتهت صلاحية هذا الكود'];
        }
        if ($invite['owner_id'] == $driverId) {
            return ['success' => false, 'msg' => 'لا يمكنك استخدام كودك الخاص'];
        }

        // ربط السائق بالمالك عبر السيارة إن وُجدت
        db()->prepare(
            'UPDATE invite_codes SET used_by=?, used_at=NOW() WHERE code=?'
        )->execute([$driverId, strtoupper($code)]);

        if ($invite['vehicle_id']) {
            // ربط السائق بالسيارة المحددة
            try {
                db()->prepare(
                    'INSERT IGNORE INTO vehicle_drivers(vehicle_id, driver_id) VALUES(?,?)'
                )->execute([$invite['vehicle_id'], $driverId]);
            } catch (PDOException $e) {}
        } else {
            // ربط السائق بكل سيارات المالك
            $vehicles = db()->prepare('SELECT id FROM vehicles WHERE owner_id=?');
            $vehicles->execute([$invite['owner_id']]);
            foreach ($vehicles->fetchAll() as $v) {
                try {
                    db()->prepare(
                        'INSERT IGNORE INTO vehicle_drivers(vehicle_id, driver_id) VALUES(?,?)'
                    )->execute([$v['id'], $driverId]);
                } catch (PDOException $e) {}
            }
        }

        return ['success' => true, 'invite' => $invite];
    }

    /** حذف كود */
    public static function delete(int $id, int $ownerId): void {
        db()->prepare('DELETE FROM invite_codes WHERE id=? AND owner_id=?')->execute([$id, $ownerId]);
    }

    /** إحصاء أكواد المالك الفعّالة */
    public static function activeCount(int $ownerId): int {
        $s = db()->prepare(
            "SELECT COUNT(*) FROM invite_codes WHERE owner_id=? AND used_by IS NULL AND (expires_at IS NULL OR expires_at > NOW())"
        );
        $s->execute([$ownerId]);
        return (int)$s->fetchColumn();
    }
}
