<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Controllers\Swimming;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;

class SwimmingCoachController extends Controller
{
    public function index(Request $request): Response
    {
        $db = App::getInstance()->db();
        $search = trim((string) $request->get('search', ''));
        $filter = trim((string) $request->get('filter', ''));

        $sql = "SELECT c.*, cd.specialization_level,
                       (SELECT COUNT(*) FROM sa_group_coaches gc
                        INNER JOIN sa_groups g ON g.id = gc.group_id AND g.status = 'active'
                        WHERE gc.coach_id = c.id) as active_groups
                FROM sa_coaches c
                INNER JOIN sa_coach_disciplines cd ON cd.coach_id = c.id
                INNER JOIN sa_disciplines d ON d.id = cd.discipline_id
                WHERE d.code = 'SWIMMING' AND c.is_active = 1 AND c.is_archived = 0";

        $params = [];

        if ($search !== '') {
            $sql .= " AND (c.full_name_ar LIKE ? OR c.phone LIKE ? OR c.code LIKE ?)";
            $params[] = "%{$search}%";
            $params[] = "%{$search}%";
            $params[] = "%{$search}%";
        }

        if ($filter !== '' && in_array($filter, ['freelance', 'staff', 'contract'])) {
            $sql .= " AND c.employment_type = ?";
            $params[] = $filter;
        }

        $sql .= " ORDER BY c.full_name_ar ASC";

        $coaches = $db->select($sql, $params);

        return $this->view('SportsActivity.Views.swimming.coaches.index', [
            'coaches' => $coaches,
            'search'  => $search,
            'filter'  => $filter,
        ]);
    }

    public function create(Request $request): Response
    {
        return $this->view('SportsActivity.Views.swimming.coaches.form', [
            'coach' => null,
        ]);
    }

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

        $fullNameAr = trim((string) $request->post('full_name_ar', ''));
        $fullNameEn = trim((string) $request->post('full_name_en', ''));
        $nationalId = trim((string) $request->post('national_id', ''));
        $phone = trim((string) $request->post('phone', ''));
        $employmentType = trim((string) $request->post('employment_type', 'freelance'));

        if ($fullNameAr === '') {
            return $this->redirect('/sa/swimming/coaches/create')->withError('الاسم بالعربي مطلوب');
        }

        if ($nationalId !== '') {
            $existing = $db->selectOne(
                "SELECT id FROM sa_coaches WHERE national_id = ? AND is_archived = 0",
                [$nationalId]
            );
            if ($existing) {
                return $this->redirect('/sa/swimming/coaches/create')
                    ->withError('يوجد مدرب بنفس الرقم القومي — كود: ' . ($existing['code'] ?? $existing['id']));
            }
        }

        $code = self::generateCode($db);

        $coachId = $db->insert('sa_coaches', [
            'code'            => $code,
            'full_name_ar'    => $fullNameAr,
            'full_name_en'    => $fullNameEn ?: null,
            'national_id'     => $nationalId ?: null,
            'phone'           => $phone ?: null,
            'coach_type'      => 'independent',
            'employment_type' => $employmentType,
            'is_active'       => 1,
            'created_at'      => date('Y-m-d H:i:s'),
            'updated_at'      => date('Y-m-d H:i:s'),
            'created_by'      => $employee ? (int) $employee->id : null,
        ]);

        $swimmingDiscipline = $db->selectOne(
            "SELECT id FROM sa_disciplines WHERE code = 'SWIMMING' AND is_archived = 0"
        );
        if ($swimmingDiscipline) {
            $db->insert('sa_coach_disciplines', [
                'coach_id'             => $coachId,
                'discipline_id'        => (int) $swimmingDiscipline['id'],
                'specialization_level' => 'primary',
                'created_at'           => date('Y-m-d H:i:s'),
            ]);
        }

        return $this->redirect('/sa/swimming/coaches')->withSuccess('تم إضافة مدرب السباحة "' . $fullNameAr . '" بنجاح');
    }

    public function show(Request $request, string $id): Response
    {
        $db = App::getInstance()->db();

        $coach = $db->selectOne(
            "SELECT c.* FROM sa_coaches c WHERE c.id = ? AND c.is_archived = 0",
            [(int) $id]
        );
        if (!$coach) {
            return $this->redirect('/sa/swimming/coaches')->withError('المدرب غير موجود');
        }

        $laneBookings = $db->select(
            "SELECT zb.*, f.name_ar as facility_name
             FROM sa_pool_zone_bookings zb
             LEFT JOIN sa_facilities f ON f.id = zb.facility_id
             WHERE zb.coach_id = ?
             ORDER BY zb.booking_date DESC, zb.start_time DESC
             LIMIT 20",
            [(int) $id]
        );

        $groups = $db->select(
            "SELECT g.name_ar, g.code, gc.role
             FROM sa_group_coaches gc
             INNER JOIN sa_groups g ON g.id = gc.group_id AND g.status = 'active'
             WHERE gc.coach_id = ?",
            [(int) $id]
        );

        return $this->view('SportsActivity.Views.swimming.coaches.show', [
            'coach'        => $coach,
            'laneBookings' => $laneBookings,
            'groups'       => $groups,
        ]);
    }

    public function edit(Request $request, string $id): Response
    {
        $db = App::getInstance()->db();

        $coach = $db->selectOne(
            "SELECT * FROM sa_coaches WHERE id = ? AND is_archived = 0",
            [(int) $id]
        );
        if (!$coach) {
            return $this->redirect('/sa/swimming/coaches')->withError('المدرب غير موجود');
        }

        return $this->view('SportsActivity.Views.swimming.coaches.form', [
            'coach' => $coach,
        ]);
    }

    public function update(Request $request, string $id): Response
    {
        $db = App::getInstance()->db();

        $coach = $db->selectOne("SELECT * FROM sa_coaches WHERE id = ? AND is_archived = 0", [(int) $id]);
        if (!$coach) {
            return $this->redirect('/sa/swimming/coaches')->withError('المدرب غير موجود');
        }

        $fullNameAr = trim((string) $request->post('full_name_ar', ''));
        $fullNameEn = trim((string) $request->post('full_name_en', ''));
        $phone = trim((string) $request->post('phone', ''));
        $employmentType = trim((string) $request->post('employment_type', 'freelance'));

        if ($fullNameAr === '') {
            return $this->redirect('/sa/swimming/coaches/' . $id . '/edit')->withError('الاسم بالعربي مطلوب');
        }

        $db->update('sa_coaches', [
            'full_name_ar'    => $fullNameAr,
            'full_name_en'    => $fullNameEn ?: null,
            'phone'           => $phone ?: null,
            'employment_type' => $employmentType,
            'updated_at'      => date('Y-m-d H:i:s'),
        ], 'id = ?', [(int) $id]);

        return $this->redirect('/sa/swimming/coaches')->withSuccess('تم تحديث بيانات المدرب بنجاح');
    }

    private static function generateCode($db): string
    {
        $row = $db->selectOne(
            "SELECT MAX(CAST(SUBSTRING(code, 12) AS UNSIGNED)) as max_num FROM sa_coaches WHERE code LIKE 'SWIM-COACH-%'"
        );
        $next = ((int) ($row['max_num'] ?? 0)) + 1;
        return 'SWIM-COACH-' . str_pad((string) $next, 3, '0', STR_PAD_LEFT);
    }
}
