<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Controllers\Swimming;

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

class PoolReservationController extends Controller
{
    public function list(Request $request): Response
    {
        $this->authorize('sa.pool_reservation.view');
        $db = App::getInstance()->db();

        $search = trim((string) $request->get('search', ''));
        $status = trim((string) $request->get('status', ''));
        $page   = max(1, (int) $request->get('page', 1));
        $limit  = 20;
        $offset = ($page - 1) * $limit;

        $where = "1=1";
        $params = [];

        if ($search !== '') {
            $where .= " AND (r.booker_name LIKE ? OR r.reservation_number LIKE ?)";
            $params[] = '%' . $search . '%';
            $params[] = '%' . $search . '%';
        }
        if ($status !== '' && in_array($status, ['active', 'completed', 'cancelled', 'expired'], true)) {
            $where .= " AND r.status = ?";
            $params[] = $status;
        }

        $countRow = $db->selectOne(
            "SELECT COUNT(*) as total FROM sa_pool_reservations r WHERE {$where}",
            $params
        );
        $total = (int) ($countRow['total'] ?? 0);

        $reservations = $db->select(
            "SELECT r.*, g.name_ar as group_name
             FROM sa_pool_reservations r
             LEFT JOIN sa_groups g ON g.id = r.group_id
             WHERE {$where}
             ORDER BY r.created_at DESC
             LIMIT {$limit} OFFSET {$offset}",
            $params
        );

        return $this->view('SportsActivity.Views.swimming.pool-reservations.index', [
            'reservations' => $reservations,
            'total'        => $total,
            'page'         => $page,
            'totalPages'   => (int) ceil($total / $limit),
            'search'       => $search,
            'status'       => $status,
        ]);
    }

    public function wizard(Request $request): Response
    {
        $this->authorize('sa.pool_reservation.create');
        $db = App::getInstance()->db();

        $recentReservations = $db->select(
            "SELECT r.id, r.reservation_number, r.booker_name, r.reservation_type,
                    r.sessions_total, r.sessions_used, r.total_amount, r.status, r.payment_status,
                    r.created_at
             FROM sa_pool_reservations r
             ORDER BY r.created_at DESC LIMIT 10"
        );

        return $this->view('SportsActivity.Views.swimming.pool-reservations.wizard', [
            'recentReservations' => $recentReservations,
        ]);
    }

    public function show(Request $request, string $id): Response
    {
        $this->authorize('sa.pool_reservation.view');
        $db = App::getInstance()->db();

        $reservation = $db->selectOne(
            "SELECT r.*, g.name_ar as group_name, g.code as group_code
             FROM sa_pool_reservations r
             LEFT JOIN sa_groups g ON g.id = r.group_id
             WHERE r.id = ?",
            [(int) $id]
        );
        if (!$reservation) {
            throw new \RuntimeException('الحجز غير موجود', 404);
        }

        $bookings = $db->select(
            "SELECT b.id, b.booking_date, b.start_time, b.end_time, b.status,
                    fu.name_ar as unit_name
             FROM sa_bookings b
             LEFT JOIN sa_facility_units fu ON fu.id = b.facility_unit_id
             WHERE b.group_id = ?
             ORDER BY b.booking_date DESC, b.start_time DESC
             LIMIT 50",
            [(int) $reservation['group_id']]
        );

        return $this->view('SportsActivity.Views.swimming.pool-reservations.show', [
            'reservation' => $reservation,
            'bookings'    => $bookings,
        ]);
    }

    public function pricing(Request $request): Response
    {
        $this->authorize('sa.pool_reservation.create');
        $options = PoolReservationService::getPricingOptions();
        return $this->json(['success' => true, 'data' => $options]);
    }

    public function capacityCheck(Request $request): Response
    {
        $this->authorize('sa.pool_reservation.create');

        $reservationType  = (string) $request->post('reservation_type', '');
        $participantCount = (int) $request->post('participant_count', 1);

        $result = PoolReservationService::checkCapacity($reservationType, $participantCount);
        return $this->json(['success' => true, 'data' => $result]);
    }

    public function store(Request $request): Response
    {
        $this->authorize('sa.pool_reservation.create');

        $data = [
            'booker_name'         => $request->post('booker_name', ''),
            'booker_phone'        => $request->post('booker_phone', ''),
            'booker_type'         => $request->post('booker_type', 'freelance_coach'),
            'participant_count'   => $request->post('participant_count', 1),
            'reservation_type'    => $request->post('reservation_type', ''),
            'pricing_id'          => $request->post('pricing_id', 0),
            'sessions_total'      => $request->post('sessions_total', 0),
            'unit_price'          => $request->post('unit_price', 0),
            'notes'               => $request->post('notes', ''),
            'overflow_type'       => $request->post('overflow_type'),
            'overflow_cards_count' => $request->post('overflow_cards_count', 0),
            'overflow_amount'     => $request->post('overflow_amount', 0),
        ];

        $result = PoolReservationService::create($data);

        if (!$result['success']) {
            return $this->json($result, 422);
        }

        return $this->json($result);
    }

    public function recordSession(Request $request, string $id): Response
    {
        $this->authorize('sa.pool_reservation.manage');
        $result = PoolReservationService::recordSessionUsage((int) $id);

        if (!$result['success']) {
            return $this->json($result, 422);
        }

        return $this->redirect('/sa/swimming/pool-reservations/' . $id)
            ->withSuccess('تم تسجيل حصة — المتبقي: ' . $result['sessions_remaining']);
    }

    public function cancel(Request $request, string $id): Response
    {
        $this->authorize('sa.pool_reservation.manage');
        $reason = trim((string) $request->post('reason', ''));
        $result = PoolReservationService::cancel((int) $id, $reason);

        if (!$result['success']) {
            return $this->redirect('/sa/swimming/pool-reservations/' . $id)
                ->withError($result['error']);
        }

        return $this->redirect('/sa/swimming/pool-reservations')
            ->withSuccess('تم إلغاء الحجز بنجاح');
    }
}
