<?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\PoolTicketService;
use App\Modules\SportsActivity\Services\PoolGridService;

class PoolTicketController extends Controller
{
    public function index(Request $request): Response
    {
        $db = App::getInstance()->db();
        $facilityId = (int) $request->get('facility_id', 0);
        $date = trim((string) $request->get('date', date('Y-m-d')));

        $facilities = $db->select(
            "SELECT * FROM sa_facilities WHERE facility_type = 'pool' AND is_active = 1 AND is_archived = 0"
        );

        $tickets = [];
        if ($facilityId > 0) {
            $tickets = PoolTicketService::getActiveTickets($facilityId, $date);
        }

        return $this->view('SportsActivity.Views.pool-tickets.index', [
            'facilities' => $facilities,
            'tickets'    => $tickets,
            'facilityId' => $facilityId,
            'date'       => $date,
        ]);
    }

    public function issue(Request $request): Response
    {
        $data = [
            'facility_id'       => (int) $request->post('facility_id', 0),
            'booking_date'      => trim((string) $request->post('booking_date', date('Y-m-d'))),
            'start_time'        => trim((string) $request->post('start_time', '')),
            'end_time'          => trim((string) $request->post('end_time', '')),
            'is_member'         => (bool) $request->post('is_member', false),
            'member_id'         => $request->post('member_id') ? (int) $request->post('member_id') : null,
            'player_id'         => $request->post('player_id') ? (int) $request->post('player_id') : null,
            'guest_name'        => trim((string) $request->post('guest_name', '')),
            'guest_national_id' => trim((string) $request->post('guest_national_id', '')),
        ];

        if ($data['facility_id'] <= 0 || $data['start_time'] === '') {
            return $this->json(['success' => false, 'error' => 'بيانات غير مكتملة']);
        }

        $result = PoolTicketService::issueTicket($data);
        return $this->json($result);
    }

    public function cancel(Request $request, string $id): Response
    {
        $reason = trim((string) $request->post('reason', ''));
        $result = PoolTicketService::cancelTicket((int) $id, $reason);
        return $this->json($result);
    }

    public function entry(Request $request, string $id): Response
    {
        $result = PoolTicketService::recordEntry((int) $id);
        return $this->json($result);
    }

    public function exit(Request $request, string $id): Response
    {
        $result = PoolTicketService::recordExit((int) $id);
        return $this->json($result);
    }
}
