<?php
declare(strict_types=1);

namespace App\Modules\ActivitySubscriptions\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\Disciplines\Models\SportDiscipline;

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

        $db = App::getInstance()->db();
        $disciplines = SportDiscipline::allActive();

        $levels = $db->select(
            "SELECT al.*, a.name_ar AS academy_name, a.discipline_id
             FROM academy_levels al
             JOIN academies a ON a.id = al.academy_id
             WHERE a.is_active = 1
             ORDER BY a.discipline_id, al.level_order ASC"
        );

        $groupTypes = [
            'private'     => ['label' => 'خاص (1 لاعب)', 'max' => 1],
            'small_group' => ['label' => 'مجموعة صغيرة (2-4)', 'max' => 4],
            'group'       => ['label' => 'مجموعة (5-12)', 'max' => 12],
            'team'        => ['label' => 'فريق (13+)', 'max' => 25],
        ];

        $pricing = $db->select(
            "SELECT ap.*, sd.name_ar AS discipline_name
             FROM activity_pricing ap
             LEFT JOIN sport_disciplines sd ON sd.id = ap.reference_id AND ap.pricing_type = 'discipline'
             WHERE ap.is_active = 1 AND ap.pricing_type = 'discipline'
             AND (ap.effective_to IS NULL OR ap.effective_to >= CURDATE())
             AND ap.effective_from <= CURDATE()
             ORDER BY ap.reference_id, ap.group_type"
        );

        $pricingMatrix = [];
        foreach ($pricing as $p) {
            $key = $p['reference_id'] . '_' . ($p['group_type'] ?? 'group');
            $pricingMatrix[$key] = $p;
        }

        return $this->view('ActivitySubscriptions.Views.enroll_wizard', [
            'disciplines'   => $disciplines,
            'levels'        => $levels,
            'groupTypes'    => $groupTypes,
            'pricingMatrix' => $pricingMatrix,
        ]);
    }

    public function getAvailability(Request $request): Response
    {
        $db = App::getInstance()->db();
        $disciplineId = (int) ($request->get('discipline_id', '0'));
        $groupType = $request->get('group_type', 'group');

        if (!$disciplineId) {
            return $this->json(['success' => false]);
        }

        $groups = $db->select(
            "SELECT tg.*, c.full_name_ar AS coach_name, f.name_ar AS facility_name
             FROM training_groups tg
             LEFT JOIN coaches c ON c.id = tg.coach_id
             LEFT JOIN facilities f ON f.id = tg.facility_id
             JOIN academies a ON a.id = tg.academy_id
             WHERE a.discipline_id = ? AND tg.group_type = ?
             AND tg.is_active = 1 AND tg.is_full = 0
             ORDER BY (tg.max_capacity - tg.current_count) DESC",
            [$disciplineId, $groupType]
        );

        return $this->json(['success' => true, 'groups' => $groups]);
    }

    public function getLevels(Request $request): Response
    {
        $db = App::getInstance()->db();
        $disciplineId = (int) ($request->get('discipline_id', '0'));

        if (!$disciplineId) {
            return $this->json(['success' => false]);
        }

        $levels = $db->select(
            "SELECT al.id, al.name_ar, al.level_order
             FROM academy_levels al
             JOIN academies a ON a.id = al.academy_id
             WHERE a.discipline_id = ? AND a.is_active = 1
             GROUP BY al.name_ar
             ORDER BY al.level_order ASC",
            [$disciplineId]
        );

        return $this->json(['success' => true, 'levels' => $levels]);
    }

    public function getPrice(Request $request): Response
    {
        $disciplineId = (int) ($request->get('discipline_id', '0'));
        $groupType = $request->get('group_type', 'group');
        $isMember = ($request->get('is_member', '1')) === '1';

        $db = App::getInstance()->db();
        $pricing = $db->selectOne(
            "SELECT * FROM activity_pricing
             WHERE pricing_type = 'discipline' AND reference_id = ?
             AND (group_type = ? OR group_type IS NULL)
             AND is_active = 1
             AND effective_from <= CURDATE()
             AND (effective_to IS NULL OR effective_to >= CURDATE())
             ORDER BY group_type DESC
             LIMIT 1",
            [$disciplineId, $groupType]
        );

        if (!$pricing) {
            return $this->json(['success' => true, 'price' => 0, 'note' => 'لم يتم تحديد سعر بعد']);
        }

        $price = $isMember ? (float) $pricing['member_rate'] : (float) $pricing['nonmember_rate'];
        return $this->json(['success' => true, 'price' => $price]);
    }

    public function enroll(Request $request): Response
    {
        $this->authorize('academy.enroll');
        $db = App::getInstance()->db();

        $playerId = (int) ($request->post('player_id') ?? 0);
        $disciplineId = (int) ($request->post('discipline_id') ?? 0);
        $levelId = (int) ($request->post('level_id') ?? 0);
        $groupType = $request->post('group_type') ?? 'group';

        if (!$playerId || !$disciplineId) {
            return $this->redirect('/activity-subscriptions/enroll')->withError('يجب تحديد اللاعب والنشاط');
        }

        $player = $db->selectOne("SELECT * FROM players WHERE id = ?", [$playerId]);
        if (!$player) {
            return $this->redirect('/activity-subscriptions/enroll')->withError('اللاعب غير موجود');
        }

        $group = $db->selectOne(
            "SELECT tg.*
             FROM training_groups tg
             JOIN academies a ON a.id = tg.academy_id
             WHERE a.discipline_id = ? AND tg.group_type = ?
             AND tg.is_active = 1 AND tg.is_full = 0
             " . ($levelId ? "AND tg.level_id = ?" : "") . "
             ORDER BY (tg.max_capacity - tg.current_count) DESC
             LIMIT 1",
            $levelId ? [$disciplineId, $groupType, $levelId] : [$disciplineId, $groupType]
        );

        if (!$group) {
            return $this->redirect('/activity-subscriptions/enroll')->withError(
                'لا توجد مجموعات متاحة لهذا النشاط والمستوى. يتم إضافة اللاعب لقائمة الانتظار.'
            );
        }

        $academyId = (int) $group['academy_id'];
        $groupLevelId = (int) $group['level_id'];

        $employee = App::getInstance()->currentEmployee();

        $enrollment = \App\Modules\PlayerAffairs\Models\AcademyEnrollment::create([
            'player_id'      => $playerId,
            'academy_id'     => $academyId,
            'level_id'       => $groupLevelId,
            'schedule_id'    => null,
            'season'         => date('Y') . '-' . (date('Y') + 1),
            'enrolled_at'    => date('Y-m-d H:i:s'),
            'enrollment_day' => (int) date('j'),
            'status'         => 'active',
            'created_by'     => $employee ? (int) $employee->id : null,
        ]);

        $db->insert('group_memberships', [
            'group_id'      => (int) $group['id'],
            'enrollment_id' => (int) $enrollment->id,
            'player_id'     => $playerId,
            'status'        => 'active',
            'joined_at'     => date('Y-m-d H:i:s'),
        ]);

        $db->update('training_groups', [
            'current_count' => (int) $group['current_count'] + 1,
            'is_full'       => ((int) $group['current_count'] + 1) >= (int) $group['max_capacity'] ? 1 : 0,
        ], 'id = ?', [(int) $group['id']]);

        return $this->redirect('/players/' . $playerId)
            ->withSuccess('تم تسجيل اللاعب بنجاح في ' . ($group['name_ar'] ?? 'المجموعة'));
    }
}
