<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\SportsActivity\Services\BookingPassService;

class BookingPassController extends Controller
{
    public function passes(Request $request, string $bookingId): Response
    {
        $db = App::getInstance()->db();

        $booking = $db->selectOne(
            "SELECT b.*, fu.name_ar as unit_name, f.name_ar as facility_name
             FROM sa_bookings b
             INNER JOIN sa_facility_units fu ON fu.id = b.facility_unit_id
             INNER JOIN sa_facilities f ON f.id = fu.facility_id
             WHERE b.id = ?",
            [(int) $bookingId]
        );

        if (!$booking) {
            return $this->redirect('/sa/bookings')->withError('الحجز غير موجود');
        }

        $passes = BookingPassService::getBookingPasses((int) $bookingId);

        return $this->view('SportsActivity.Views.bookings.passes', [
            'booking' => $booking,
            'passes'  => $passes,
        ]);
    }

    public function usePass(Request $request): Response
    {
        $passNumber = trim((string) $request->post('pass_number', ''));
        $usedByName = trim((string) $request->post('used_by_name', ''));
        $employeeId = (int) (App::getInstance()->session()->get('employee_id') ?? 0);

        if ($passNumber === '') {
            return $this->json(['success' => false, 'error' => 'أدخل رقم الباس']);
        }

        $result = BookingPassService::usePass($passNumber, $usedByName ?: null, $employeeId);
        return $this->json($result);
    }

    public function validatePass(Request $request): Response
    {
        $passNumber = trim((string) $request->get('pass_number', ''));
        if ($passNumber === '') {
            return $this->json(['valid' => false, 'error' => 'أدخل رقم الباس']);
        }

        $result = BookingPassService::validatePass($passNumber);
        return $this->json($result);
    }
}
