<?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\Core\Pagination;
use App\Modules\SportsActivity\Models\Waitlist;
use App\Modules\SportsActivity\Models\Group;

class WaitlistController extends Controller
{
    /**
     * List all waitlist entries with filters.
     */
    public function index(Request $request): Response
    {
        $db = App::getInstance()->db();

        $filters = [
            'group_id' => trim((string) $request->get('group_id', '')),
            'status'   => trim((string) $request->get('status', '')),
        ];

        $page = max(1, (int) $request->get('page', 1));
        $perPage = 25;

        $where = [];
        $params = [];

        if ($filters['group_id'] !== '') {
            $where[] = "w.group_id = ?";
            $params[] = (int) $filters['group_id'];
        }

        if ($filters['status'] !== '') {
            $where[] = "w.status = ?";
            $params[] = $filters['status'];
        }

        $whereClause = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';

        $total = (int) ($db->selectOne(
            "SELECT COUNT(*) as cnt FROM sa_waitlist w {$whereClause}",
            $params
        )['cnt'] ?? 0);

        $pagination = Pagination::paginate($total, $perPage, $page);
        $offset = ($page - 1) * $perPage;

        $entries = $db->select(
            "SELECT w.*, p.full_name_ar as player_name, p.registration_serial as player_code,
                    g.name_ar as group_name
             FROM sa_waitlist w
             LEFT JOIN sa_players p ON p.id = w.player_id
             LEFT JOIN sa_groups g ON g.id = w.group_id
             {$whereClause}
             ORDER BY w.position ASC, w.created_at ASC
             LIMIT {$perPage} OFFSET {$offset}",
            $params
        );

        $groups = Group::getActive();

        return $this->view('SportsActivity.Views.waitlist.index', [
            'entries'       => $entries,
            'pagination'    => $pagination,
            'filters'       => $filters,
            'groups'        => $groups,
            'statusOptions' => Waitlist::getStatusOptions(),
        ]);
    }

    /**
     * Offer a spot to a waitlisted player.
     */
    public function offer(Request $request, string $id): Response
    {
        $db = App::getInstance()->db();

        $entry = $db->selectOne(
            "SELECT * FROM sa_waitlist WHERE id = ?",
            [(int) $id]
        );

        if (!$entry) {
            return $this->redirect('/sa/waitlist')->withError('السجل غير موجود');
        }

        if ($entry['status'] !== 'waiting') {
            return $this->redirect('/sa/waitlist')->withError('لا يمكن تقديم عرض لهذا السجل بحالته الحالية');
        }

        $now = date('Y-m-d H:i:s');
        $expiresAt = date('Y-m-d H:i:s', strtotime('+48 hours'));

        $db->update('sa_waitlist', [
            'status'     => 'offered',
            'offered_at' => $now,
            'expires_at' => $expiresAt,
            'updated_at' => $now,
        ], 'id = ?', [(int) $id]);

        return $this->redirect('/sa/waitlist')->withSuccess('تم تقديم العرض بنجاح - ينتهي خلال 48 ساعة');
    }

    /**
     * Cancel a waitlist entry.
     */
    public function cancel(Request $request, string $id): Response
    {
        $db = App::getInstance()->db();

        $entry = $db->selectOne(
            "SELECT * FROM sa_waitlist WHERE id = ?",
            [(int) $id]
        );

        if (!$entry) {
            return $this->redirect('/sa/waitlist')->withError('السجل غير موجود');
        }

        $db->update('sa_waitlist', [
            'status'     => 'cancelled',
            'updated_at' => date('Y-m-d H:i:s'),
        ], 'id = ?', [(int) $id]);

        return $this->redirect('/sa/waitlist')->withSuccess('تم إلغاء السجل من قائمة الانتظار');
    }
}
