<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Services;

use App\Core\App;
use App\Modules\SportsActivity\SaConstants;

final class BookingPassService
{
    public static function generatePasses(int $bookingId, int $count): array
    {
        $db = App::getInstance()->db();
        $now = date('Y-m-d H:i:s');
        $passes = [];

        $booking = $db->selectOne("SELECT booking_number FROM sa_bookings WHERE id = ?", [$bookingId]);
        $prefix = $booking ? $booking['booking_number'] : ('BK-' . str_pad((string) $bookingId, 5, '0', STR_PAD_LEFT));

        for ($i = 1; $i <= $count; $i++) {
            $passNumber = $prefix . '-P' . str_pad((string) $i, 2, '0', STR_PAD_LEFT);

            $passId = $db->insert('sa_booking_passes', [
                'booking_id'  => $bookingId,
                'pass_number' => $passNumber,
                'status'      => SaConstants::PASS_ISSUED,
                'created_at'  => $now,
                'updated_at'  => $now,
            ]);

            $passes[] = ['id' => $passId, 'pass_number' => $passNumber];
        }

        $db->update('sa_bookings', [
            'passes_total' => $count,
            'updated_at'   => $now,
        ], 'id = ?', [$bookingId]);

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

    public static function usePass(string $passNumber, ?string $usedByName, int $employeeId): array
    {
        $db = App::getInstance()->db();

        $pass = $db->selectOne(
            "SELECT bp.*, b.booking_date, b.start_time, b.end_time, b.status as booking_status
             FROM sa_booking_passes bp
             INNER JOIN sa_bookings b ON b.id = bp.booking_id
             WHERE bp.pass_number = ?",
            [$passNumber]
        );

        if (!$pass) {
            return ['success' => false, 'error' => 'رقم الباس غير موجود'];
        }

        if ($pass['status'] !== SaConstants::PASS_ISSUED) {
            return ['success' => false, 'error' => 'هذا الباس ' . ($pass['status'] === 'used' ? 'مستخدم بالفعل' : 'غير صالح')];
        }

        if ($pass['booking_status'] === 'cancelled') {
            return ['success' => false, 'error' => 'الحجز ملغي'];
        }

        $now = date('Y-m-d H:i:s');

        $db->update('sa_booking_passes', [
            'status'           => SaConstants::PASS_USED,
            'used_at'          => $now,
            'used_by_name'     => $usedByName,
            'gate_employee_id' => $employeeId,
            'updated_at'       => $now,
        ], 'id = ?', [(int) $pass['id']]);

        $db->query(
            "UPDATE sa_bookings SET passes_used = passes_used + 1, updated_at = ? WHERE id = ?",
            [$now, (int) $pass['booking_id']]
        );

        return ['success' => true, 'pass_number' => $passNumber, 'booking_id' => (int) $pass['booking_id']];
    }

    public static function validatePass(string $passNumber): array
    {
        $db = App::getInstance()->db();

        $pass = $db->selectOne(
            "SELECT bp.*, b.booking_date, b.start_time, b.end_time, b.booker_name,
                    b.organization_name, b.status as booking_status
             FROM sa_booking_passes bp
             INNER JOIN sa_bookings b ON b.id = bp.booking_id
             WHERE bp.pass_number = ?",
            [$passNumber]
        );

        if (!$pass) {
            return ['valid' => false, 'error' => 'رقم الباس غير موجود'];
        }

        if ($pass['status'] !== SaConstants::PASS_ISSUED) {
            return ['valid' => false, 'error' => 'الباس ' . $pass['status'], 'pass' => $pass];
        }

        if ($pass['booking_status'] === 'cancelled') {
            return ['valid' => false, 'error' => 'الحجز ملغي', 'pass' => $pass];
        }

        return ['valid' => true, 'pass' => $pass];
    }

    public static function getBookingPasses(int $bookingId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT * FROM sa_booking_passes WHERE booking_id = ? ORDER BY pass_number",
            [$bookingId]
        );
    }

    public static function expireBookingPasses(int $bookingId): int
    {
        $db = App::getInstance()->db();
        $now = date('Y-m-d H:i:s');

        $stmt = $db->query(
            "UPDATE sa_booking_passes SET status = ?, updated_at = ? WHERE booking_id = ? AND status = ?",
            [SaConstants::PASS_EXPIRED, $now, $bookingId, SaConstants::PASS_ISSUED]
        );

        return $stmt->rowCount();
    }
}
