<?php
declare(strict_types=1);

namespace App\Modules\Sessions\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\Sessions\Models\TrainingSession;
use App\Modules\Sessions\Services\SessionManagementService;

class SessionController extends Controller
{
    public function index(Request $request): Response
    {
        $this->authorize('session.view');

        $filters = [
            'date_from'    => trim((string) $request->get('date_from', '')),
            'date_to'      => trim((string) $request->get('date_to', '')),
            'group_id'     => trim((string) $request->get('group_id', '')),
            'academy_id'   => trim((string) $request->get('academy_id', '')),
            'coach_id'     => trim((string) $request->get('coach_id', '')),
            'status'       => trim((string) $request->get('status', '')),
            'session_type' => trim((string) $request->get('session_type', '')),
        ];

        $page = max(1, (int) $request->get('page', 1));
        $result = TrainingSession::search($filters, 25, $page);

        $db = App::getInstance()->db();

        $academies = $db->select(
            "SELECT id, name_ar FROM academies WHERE is_active = 1 AND is_archived = 0 ORDER BY name_ar ASC"
        );

        $groups = $db->select(
            "SELECT id, name_ar FROM training_groups WHERE is_active = 1 AND is_archived = 0 ORDER BY name_ar ASC"
        );

        return $this->view('Sessions.Views.index', [
            'sessions'     => $result['data'],
            'pagination'   => $result['pagination'],
            'filters'      => $filters,
            'academies'    => $academies,
            'groups'       => $groups,
            'statuses'     => TrainingSession::getStatuses(),
            'sessionTypes' => TrainingSession::getSessionTypes(),
        ]);
    }

    public function calendar(Request $request): Response
    {
        $this->authorize('session.view');

        $year = (int) $request->get('year', (int) date('Y'));
        $month = (int) $request->get('month', (int) date('m'));
        $academyId = $request->get('academy_id', '') !== '' ? (int) $request->get('academy_id') : null;

        // Clamp month
        if ($month < 1) { $month = 12; $year--; }
        if ($month > 12) { $month = 1; $year++; }

        $sessions = TrainingSession::getForCalendar($year, $month, $academyId);

        $db = App::getInstance()->db();
        $academies = $db->select(
            "SELECT id, name_ar FROM academies WHERE is_active = 1 AND is_archived = 0 ORDER BY name_ar ASC"
        );

        return $this->view('Sessions.Views.calendar', [
            'sessions'   => $sessions,
            'year'       => $year,
            'month'      => $month,
            'academyId'  => $academyId,
            'academies'  => $academies,
        ]);
    }

    public function show(Request $request, string $id): Response
    {
        $this->authorize('session.view');

        $db = App::getInstance()->db();

        $session = $db->selectOne(
            "SELECT ts.*,
                    tg.name_ar AS group_name,
                    a.name_ar AS academy_name,
                    c.full_name_ar AS coach_name,
                    f.name_ar AS facility_name
             FROM training_sessions ts
             LEFT JOIN training_groups tg ON tg.id = ts.group_id
             LEFT JOIN academies a ON a.id = ts.academy_id
             LEFT JOIN coaches c ON c.id = ts.coach_id
             LEFT JOIN facilities f ON f.id = ts.facility_id
             WHERE ts.id = ?",
            [(int) $id]
        );

        if (!$session) {
            return $this->redirect('/sessions')->withError('الحصة غير موجودة');
        }

        // Get attendance records if session is in_progress or completed
        $attendance = [];
        if (in_array($session['status'], ['in_progress', 'completed'], true)) {
            $attendance = $db->select(
                "SELECT sa.*, p.full_name_ar AS player_name, p.phone AS player_phone
                 FROM session_attendance sa
                 LEFT JOIN players p ON p.id = sa.player_id
                 WHERE sa.session_id = ?
                 ORDER BY p.full_name_ar ASC",
                [(int) $id]
            );
        }

        return $this->view('Sessions.Views.show', [
            'session'    => $session,
            'attendance' => $attendance,
            'statuses'   => TrainingSession::getStatuses(),
            'types'      => TrainingSession::getSessionTypes(),
        ]);
    }

    public function cancel(Request $request, string $id): Response
    {
        $this->authorize('session.manage');

        $db = App::getInstance()->db();

        $session = $db->selectOne(
            "SELECT id, status FROM training_sessions WHERE id = ?",
            [(int) $id]
        );

        if (!$session) {
            return $this->redirect('/sessions')->withError('الحصة غير موجودة');
        }

        if ($session['status'] === 'cancelled') {
            return $this->redirect('/sessions/' . $id)->withError('الحصة ملغاة بالفعل');
        }

        if ($session['status'] === 'completed') {
            return $this->redirect('/sessions/' . $id)->withError('لا يمكن إلغاء حصة مكتملة');
        }

        $reason = trim((string) $request->post('cancellation_reason', ''));
        if ($reason === '') {
            $session_obj = App::getInstance()->session();
            $session_obj->flash('_alerts', [['type' => 'error', 'message' => 'يجب إدخال سبب الإلغاء']]);
            return $this->redirect('/sessions/' . $id);
        }

        $cancelledBy = (int) ($_SESSION['employee_id'] ?? 0);
        SessionManagementService::cancelSession((int) $id, $reason, $cancelledBy);

        return $this->redirect('/sessions/' . $id)->withSuccess('تم إلغاء الحصة وإصدار رصيد تعويضي للاعبين');
    }

    public function complete(Request $request, string $id): Response
    {
        $this->authorize('session.manage');

        $db = App::getInstance()->db();

        $session = $db->selectOne(
            "SELECT id, status FROM training_sessions WHERE id = ?",
            [(int) $id]
        );

        if (!$session) {
            return $this->redirect('/sessions')->withError('الحصة غير موجودة');
        }

        if ($session['status'] === 'completed') {
            return $this->redirect('/sessions/' . $id)->withError('الحصة مكتملة بالفعل');
        }

        if ($session['status'] === 'cancelled') {
            return $this->redirect('/sessions/' . $id)->withError('لا يمكن إكمال حصة ملغاة');
        }

        SessionManagementService::completeSession((int) $id);

        return $this->redirect('/sessions/' . $id)->withSuccess('تم تحديث حالة الحصة إلى مكتملة');
    }

    public function generate(Request $request): Response
    {
        $this->authorize('session.manage');

        $weekStart = trim((string) $request->post('week_start', ''));

        if ($weekStart === '') {
            // Default to next Sunday
            $nextSunday = date('Y-m-d', strtotime('next sunday'));
            $weekStart = $nextSunday;
        }

        $count = SessionManagementService::generateWeeklySessions($weekStart);

        if ($count > 0) {
            return $this->redirect('/sessions')->withSuccess("تم إنشاء {$count} حصة تدريبية للأسبوع بدءًا من {$weekStart}");
        }

        return $this->redirect('/sessions')->withError('لم يتم إنشاء أي حصص جديدة. قد تكون الحصص موجودة بالفعل أو لا توجد مجموعات بجدول محدد.');
    }
}
