<?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\Discipline;

class DisciplineController extends Controller
{
    /**
     * List all disciplines with search filter and pagination.
     */
    public function index(Request $request): Response
    {
        $filters = [
            'q'        => trim((string) $request->get('q', '')),
            'category' => trim((string) $request->get('category', '')),
        ];

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

        $query = Discipline::query();

        if ($filters['q'] !== '') {
            $query->where('name_ar', 'LIKE', '%' . $filters['q'] . '%');
        }

        if ($filters['category'] !== '') {
            $query->where('category', '=', $filters['category']);
        }

        // Count total
        $countQuery = Discipline::query();
        if ($filters['q'] !== '') {
            $countQuery->where('name_ar', 'LIKE', '%' . $filters['q'] . '%');
        }
        if ($filters['category'] !== '') {
            $countQuery->where('category', '=', $filters['category']);
        }
        $total = count($countQuery->get());

        $pagination = Pagination::paginate($total, $perPage, $page);

        $disciplines = $query
            ->orderBy('sort_order', 'ASC')
            ->orderBy('name_ar', 'ASC')
            ->limit($perPage)
            ->offset(($page - 1) * $perPage)
            ->get();

        return $this->view('SportsActivity.Views.disciplines.index', [
            'disciplines' => $disciplines,
            'pagination'  => $pagination,
            'filters'     => $filters,
            'categories'  => Discipline::getCategoryOptions(),
        ]);
    }

    public function activityBrowser(Request $request): Response
    {
        $db = App::getInstance()->db();

        $disciplines = $db->select(
            "SELECT d.id, d.code, d.name_ar, d.icon, d.category,
                    (SELECT COUNT(*) FROM sa_programs p WHERE p.discipline_id = d.id AND p.is_archived = 0) as program_count
             FROM sa_disciplines d
             WHERE d.is_active = 1 AND d.is_archived = 0
             ORDER BY d.sort_order ASC, d.name_ar ASC",
            []
        );

        return $this->view('SportsActivity.Views.activities.browser', [
            'disciplines' => $disciplines,
        ]);
    }

    /**
     * Show the create discipline form.
     */
    public function create(Request $request): Response
    {
        return $this->view('SportsActivity.Views.disciplines.create', [
            'categories' => Discipline::getCategoryOptions(),
        ]);
    }

    /**
     * Validate and store a new discipline.
     */
    public function store(Request $request): Response
    {
        $code = strtoupper(trim((string) $request->post('code', '')));
        $nameAr = trim((string) $request->post('name_ar', ''));
        $nameEn = trim((string) $request->post('name_en', ''));
        $category = trim((string) $request->post('category', ''));
        $icon = trim((string) $request->post('icon', 'activity'));
        $descriptionAr = trim((string) $request->post('description_ar', ''));
        $sortOrder = (int) $request->post('sort_order', 0);

        // Validation
        $errors = [];
        if ($code === '') {
            $errors[] = 'كود النشاط مطلوب';
        }
        if ($nameAr === '' || mb_strlen($nameAr) < 2) {
            $errors[] = 'الاسم بالعربي مطلوب (حرفان على الأقل)';
        }

        // Check unique code
        if ($code !== '') {
            $existing = Discipline::query()
                ->where('code', '=', $code)
                ->first();
            if ($existing) {
                $errors[] = 'كود النشاط مستخدم بالفعل — جرب كود مختلف';
            }
        }

        // Validate category if provided
        if ($category !== '' && !array_key_exists($category, Discipline::getCategoryOptions())) {
            $errors[] = 'فئة النشاط غير صالحة';
        }

        if (!empty($errors)) {
            $session = App::getInstance()->session();
            $session->flash('_alerts', array_map(fn($e) => ['type' => 'error', 'message' => $e], $errors));
            $session->flash('_old_input', $request->all());
            return $this->redirect('/sa/disciplines/create');
        }

        $sportType = trim((string) $request->post('sport_type', 'training'));
        if (!in_array($sportType, ['training', 'recreational'], true)) {
            $sportType = 'training';
        }

        $discipline = Discipline::create([
            'code'           => $code,
            'name_ar'        => $nameAr,
            'name_en'        => $nameEn ?: null,
            'category'       => $category ?: null,
            'sport_type'     => $sportType,
            'icon'           => $icon ?: null,
            'description_ar' => $descriptionAr ?: null,
            'sort_order'     => $sortOrder,
            'is_active'      => 1,
        ]);

        return $this->redirect('/sa/disciplines/' . $discipline->id)->withSuccess('تم إضافة النشاط الرياضي بنجاح');
    }

    /**
     * Show discipline detail page.
     */
    public function show(Request $request, string $id): Response
    {
        $discipline = Discipline::find((int) $id);
        if (!$discipline) {
            return $this->redirect('/sa/disciplines')->withError('النشاط الرياضي غير موجود');
        }

        return $this->view('SportsActivity.Views.disciplines.show', [
            'discipline' => $discipline,
            'categories' => Discipline::getCategoryOptions(),
        ]);
    }

    /**
     * Show edit form for a discipline.
     */
    public function edit(Request $request, string $id): Response
    {
        $discipline = Discipline::find((int) $id);
        if (!$discipline) {
            return $this->redirect('/sa/disciplines')->withError('النشاط الرياضي غير موجود');
        }

        return $this->view('SportsActivity.Views.disciplines.edit', [
            'discipline' => $discipline,
            'categories' => Discipline::getCategoryOptions(),
        ]);
    }

    /**
     * Validate and update an existing discipline.
     */
    public function update(Request $request, string $id): Response
    {
        $discipline = Discipline::find((int) $id);
        if (!$discipline) {
            return $this->redirect('/sa/disciplines')->withError('النشاط الرياضي غير موجود');
        }

        $code = strtoupper(trim((string) $request->post('code', '')));
        $nameAr = trim((string) $request->post('name_ar', ''));
        $nameEn = trim((string) $request->post('name_en', ''));
        $category = trim((string) $request->post('category', ''));
        $icon = trim((string) $request->post('icon', 'activity'));
        $descriptionAr = trim((string) $request->post('description_ar', ''));
        $sortOrder = (int) $request->post('sort_order', 0);

        // Validation
        $errors = [];
        if ($code === '') {
            $errors[] = 'كود النشاط مطلوب';
        }
        if ($nameAr === '' || mb_strlen($nameAr) < 2) {
            $errors[] = 'الاسم بالعربي مطلوب (حرفان على الأقل)';
        }

        // Check unique code (exclude current)
        if ($code !== '') {
            $db = App::getInstance()->db();
            $existing = $db->selectOne(
                "SELECT id FROM sa_disciplines WHERE code = ? AND id != ?",
                [$code, (int) $id]
            );
            if ($existing) {
                $errors[] = 'كود النشاط مستخدم بالفعل — جرب كود مختلف';
            }
        }

        // Validate category if provided
        if ($category !== '' && !array_key_exists($category, Discipline::getCategoryOptions())) {
            $errors[] = 'فئة النشاط غير صالحة';
        }

        if (!empty($errors)) {
            $session = App::getInstance()->session();
            $session->flash('_alerts', array_map(fn($e) => ['type' => 'error', 'message' => $e], $errors));
            $session->flash('_old_input', $request->all());
            return $this->redirect('/sa/disciplines/' . $id . '/edit');
        }

        $sportType = trim((string) $request->post('sport_type', 'training'));
        if (!in_array($sportType, ['training', 'recreational'], true)) {
            $sportType = 'training';
        }

        $discipline->update([
            'code'           => $code,
            'name_ar'        => $nameAr,
            'name_en'        => $nameEn ?: null,
            'category'       => $category ?: null,
            'sport_type'     => $sportType,
            'icon'           => $icon ?: null,
            'description_ar' => $descriptionAr ?: null,
            'sort_order'     => $sortOrder,
        ]);

        return $this->redirect('/sa/disciplines/' . $id)->withSuccess('تم تحديث النشاط الرياضي بنجاح');
    }

    /**
     * Toggle the is_active status of a discipline.
     */
    public function toggle(Request $request, string $id): Response
    {
        $discipline = Discipline::find((int) $id);
        if (!$discipline) {
            return $this->redirect('/sa/disciplines')->withError('النشاط الرياضي غير موجود');
        }

        $newStatus = $discipline->is_active ? 0 : 1;
        $discipline->update(['is_active' => $newStatus]);

        $message = $newStatus ? 'تم تفعيل النشاط الرياضي' : 'تم إيقاف النشاط الرياضي';
        return $this->redirect('/sa/disciplines/' . $id)->withSuccess($message);
    }
}
