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

class AcademyController extends Controller
{
    /**
     * List academies with search, filter by discipline, pagination.
     */
    public function index(Request $request): Response
    {
        $db = App::getInstance()->db();

        $search = trim((string) $request->get('q', ''));
        $disciplineId = trim((string) $request->get('discipline_id', ''));
        $page = max(1, (int) $request->get('page', 1));
        $perPage = 25;

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

        if ($search !== '') {
            $where[] = '(a.name_ar LIKE ? OR a.name_en LIKE ? OR a.code LIKE ?)';
            $params[] = "%{$search}%";
            $params[] = "%{$search}%";
            $params[] = "%{$search}%";
        }

        if ($disciplineId !== '') {
            $where[] = 'a.discipline_id = ?';
            $params[] = (int) $disciplineId;
        }

        $whereSql = implode(' AND ', $where);

        // Count total
        $countSql = "SELECT COUNT(*) as total FROM sa_academies a WHERE {$whereSql}";
        $total = (int) $db->selectOne($countSql, $params)['total'];

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

        // Fetch academies with discipline name
        $sql = "SELECT a.*, d.name_ar as discipline_name
                FROM sa_academies a
                LEFT JOIN sa_disciplines d ON d.id = a.discipline_id
                WHERE {$whereSql}
                ORDER BY a.created_at DESC
                LIMIT {$perPage} OFFSET {$offset}";
        $academies = $db->select($sql, $params);

        // Count contracts per academy
        foreach ($academies as &$academy) {
            $contractCount = $db->selectOne(
                "SELECT COUNT(*) as cnt FROM sa_academy_contracts WHERE academy_id = ?",
                [(int) $academy['id']]
            );
            $academy['contract_count'] = (int) ($contractCount['cnt'] ?? 0);
        }
        unset($academy);

        // Get disciplines for filter
        $disciplines = $db->select("SELECT id, name_ar FROM sa_disciplines WHERE is_active = 1 ORDER BY name_ar", []);

        return $this->view('SportsActivity.Views.academies.index', [
            'academies'   => $academies,
            'pagination'  => $pagination,
            'filters'     => [
                'q'             => $search,
                'discipline_id' => $disciplineId,
            ],
            'disciplines' => $disciplines,
        ]);
    }

    /**
     * Show the create academy form.
     */
    public function create(Request $request): Response
    {
        $db = App::getInstance()->db();
        $disciplines = $db->select("SELECT id, name_ar FROM sa_disciplines WHERE is_active = 1 ORDER BY name_ar", []);

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

    /**
     * Validate and store a new academy.
     */
    public function store(Request $request): Response
    {
        $db = App::getInstance()->db();
        $session = App::getInstance()->session();

        $code = trim((string) $request->post('code', ''));
        $nameAr = trim((string) $request->post('name_ar', ''));
        $nameEn = trim((string) $request->post('name_en', ''));
        $disciplineId = (int) $request->post('discipline_id', 0);
        $academyType = trim((string) $request->post('academy_type', ''));
        $contactPerson = trim((string) $request->post('contact_person', ''));
        $contactPhone = trim((string) $request->post('contact_phone', ''));
        $contactEmail = trim((string) $request->post('contact_email', ''));
        $descriptionAr = trim((string) $request->post('description_ar', ''));

        // Validation
        $errors = [];
        if ($code === '') {
            $errors[] = 'كود الأكاديمية مطلوب';
        }
        if ($nameAr === '') {
            $errors[] = 'الاسم بالعربي مطلوب';
        }
        if ($disciplineId <= 0) {
            $errors[] = 'اللعبة / النشاط الرياضي مطلوب';
        }

        $validTypes = ['internal', 'external'];
        if ($academyType !== '' && !in_array($academyType, $validTypes, true)) {
            $errors[] = 'نوع الأكاديمية غير صالح';
        }

        // Check unique code
        if ($code !== '') {
            $existing = $db->selectOne("SELECT id FROM sa_academies WHERE code = ?", [$code]);
            if ($existing) {
                $errors[] = 'كود الأكاديمية مستخدم بالفعل';
            }
        }

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

        $data = [
            'code'            => strtoupper($code),
            'name_ar'         => $nameAr,
            'name_en'         => $nameEn ?: null,
            'discipline_id'   => $disciplineId,
            'academy_type'    => $academyType ?: 'internal',
            'contact_person'  => $contactPerson ?: null,
            'contact_phone'   => $contactPhone ?: null,
            'contact_email'   => $contactEmail ?: null,
            'description_ar'  => $descriptionAr ?: null,
            'is_active'       => 1,
            'created_at'      => now(),
            'updated_at'      => now(),
        ];

        $db->insert('sa_academies', $data);
        $academyId = (int) $db->selectOne("SELECT LAST_INSERT_ID() as id")['id'];

        return $this->redirect('/sa/academies/' . $academyId)->withSuccess('تم إضافة الأكاديمية بنجاح');
    }

    /**
     * Show academy detail with contracts list.
     */
    public function show(Request $request, string $id): Response
    {
        $db = App::getInstance()->db();

        $academy = $db->selectOne("SELECT a.*, d.name_ar as discipline_name
            FROM sa_academies a
            LEFT JOIN sa_disciplines d ON d.id = a.discipline_id
            WHERE a.id = ?", [(int) $id]);

        if (!$academy) {
            return $this->redirect('/sa/academies')->withError('الأكاديمية غير موجودة');
        }

        $contracts = $db->select(
            "SELECT * FROM sa_academy_contracts WHERE academy_id = ? ORDER BY created_at DESC",
            [(int) $id]
        );

        return $this->view('SportsActivity.Views.academies.show', [
            'academy'   => $academy,
            'contracts' => $contracts,
        ]);
    }

    /**
     * Show edit form for an academy.
     */
    public function edit(Request $request, string $id): Response
    {
        $db = App::getInstance()->db();

        $academy = $db->selectOne("SELECT * FROM sa_academies WHERE id = ?", [(int) $id]);
        if (!$academy) {
            return $this->redirect('/sa/academies')->withError('الأكاديمية غير موجودة');
        }

        $disciplines = $db->select("SELECT id, name_ar FROM sa_disciplines WHERE is_active = 1 ORDER BY name_ar", []);

        return $this->view('SportsActivity.Views.academies.edit', [
            'academy'     => $academy,
            'disciplines' => $disciplines,
        ]);
    }

    /**
     * Validate and update an academy.
     */
    public function update(Request $request, string $id): Response
    {
        $db = App::getInstance()->db();
        $session = App::getInstance()->session();

        $academy = $db->selectOne("SELECT * FROM sa_academies WHERE id = ?", [(int) $id]);
        if (!$academy) {
            return $this->redirect('/sa/academies')->withError('الأكاديمية غير موجودة');
        }

        $code = trim((string) $request->post('code', ''));
        $nameAr = trim((string) $request->post('name_ar', ''));
        $nameEn = trim((string) $request->post('name_en', ''));
        $disciplineId = (int) $request->post('discipline_id', 0);
        $academyType = trim((string) $request->post('academy_type', ''));
        $contactPerson = trim((string) $request->post('contact_person', ''));
        $contactPhone = trim((string) $request->post('contact_phone', ''));
        $contactEmail = trim((string) $request->post('contact_email', ''));
        $descriptionAr = trim((string) $request->post('description_ar', ''));

        // Validation
        $errors = [];
        if ($code === '') {
            $errors[] = 'كود الأكاديمية مطلوب';
        }
        if ($nameAr === '') {
            $errors[] = 'الاسم بالعربي مطلوب';
        }
        if ($disciplineId <= 0) {
            $errors[] = 'اللعبة / النشاط الرياضي مطلوب';
        }

        // Check unique code (exclude current)
        if ($code !== '') {
            $existing = $db->selectOne("SELECT id FROM sa_academies WHERE code = ? AND id != ?", [$code, (int) $id]);
            if ($existing) {
                $errors[] = 'كود الأكاديمية مستخدم بالفعل';
            }
        }

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

        $data = [
            'code'            => strtoupper($code),
            'name_ar'         => $nameAr,
            'name_en'         => $nameEn ?: null,
            'discipline_id'   => $disciplineId,
            'academy_type'    => $academyType ?: 'internal',
            'contact_person'  => $contactPerson ?: null,
            'contact_phone'   => $contactPhone ?: null,
            'contact_email'   => $contactEmail ?: null,
            'description_ar'  => $descriptionAr ?: null,
            'updated_at'      => now(),
        ];

        $db->update('sa_academies', $data, 'id = ?', [(int) $id]);

        return $this->redirect('/sa/academies/' . $id)->withSuccess('تم تحديث الأكاديمية بنجاح');
    }
}
