<?php
declare(strict_types=1);

namespace App\Modules\PlayerAffairs\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\PlayerAffairs\Models\PlayerFitnessTest;
use App\Modules\PlayerAffairs\Models\Player;
use App\Modules\PlayerAffairs\Services\FitnessService;

class FitnessController extends Controller
{
    /**
     * List fitness tests with filters and pagination.
     */
    public function index(Request $request): Response
    {
        $this->authorize('player.manage_fitness');

        $filters = [
            'q'             => trim((string) $request->get('q', '')),
            'player_id'     => $request->get('player_id', '') !== '' ? (int) $request->get('player_id') : null,
            'discipline_id' => $request->get('discipline_id', '') !== '' ? (int) $request->get('discipline_id') : null,
            'test_type'     => trim((string) $request->get('test_type', '')),
            'fitness_level' => trim((string) $request->get('fitness_level', '')),
            'date_from'     => trim((string) $request->get('date_from', '')),
            'date_to'       => trim((string) $request->get('date_to', '')),
        ];

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

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

        return $this->view('PlayerAffairs.Views.fitness_tests', [
            'tests'          => $result['data'],
            'pagination'     => $result['pagination'],
            'filters'        => $filters,
            'testTypes'      => PlayerFitnessTest::getTestTypes(),
            'fitnessLevels'  => PlayerFitnessTest::getFitnessLevels(),
            'disciplines'    => $disciplines,
        ]);
    }

    /**
     * Show fitness test creation form.
     */
    public function create(Request $request): Response
    {
        $this->authorize('player.manage_fitness');

        $db = App::getInstance()->db();
        $disciplines = $db->select(
            "SELECT id, name_ar FROM sport_disciplines WHERE is_active = 1 AND is_archived = 0 ORDER BY name_ar ASC"
        );
        $coaches = $db->select(
            "SELECT id, full_name_ar FROM coaches WHERE is_active = 1 AND is_archived = 0 ORDER BY full_name_ar ASC"
        );
        $players = Player::allActive();

        // Pre-select player if player_id in query string
        $selectedPlayerId = $request->get('player_id', '') !== '' ? (int) $request->get('player_id') : null;

        return $this->view('PlayerAffairs.Views.fitness_create', [
            'players'          => $players,
            'disciplines'      => $disciplines,
            'coaches'          => $coaches,
            'testTypes'        => PlayerFitnessTest::getTestTypes(),
            'fitnessLevels'    => PlayerFitnessTest::getFitnessLevels(),
            'selectedPlayerId' => $selectedPlayerId,
        ]);
    }

    /**
     * Store a new fitness test.
     */
    public function store(Request $request): Response
    {
        $this->authorize('player.manage_fitness');

        $data = [
            'player_id'              => (int) $request->post('player_id', 0),
            'discipline_id'          => $request->post('discipline_id', '') !== '' ? (int) $request->post('discipline_id') : null,
            'test_date'              => trim((string) $request->post('test_date', '')),
            'test_type'              => trim((string) $request->post('test_type', '')),
            'tester_name'            => trim((string) $request->post('tester_name', '')) ?: null,
            'coach_id'               => $request->post('coach_id', '') !== '' ? (int) $request->post('coach_id') : null,
            'overall_fitness_score'  => $request->post('overall_fitness_score', '') !== '' ? (float) $request->post('overall_fitness_score') : null,
            'weight_kg'              => $request->post('weight_kg', '') !== '' ? (float) $request->post('weight_kg') : null,
            'height_cm'              => $request->post('height_cm', '') !== '' ? (float) $request->post('height_cm') : null,
            'resting_heart_rate'     => $request->post('resting_heart_rate', '') !== '' ? (int) $request->post('resting_heart_rate') : null,
            'blood_pressure'         => trim((string) $request->post('blood_pressure', '')) ?: null,
            'recommendations_ar'     => trim((string) $request->post('recommendations_ar', '')) ?: null,
            'cleared_for_activity'   => $request->post('cleared_for_activity', '') !== '' ? (int) $request->post('cleared_for_activity') : null,
            'next_test_date'         => trim((string) $request->post('next_test_date', '')) ?: null,
        ];

        // Collect dynamic results fields
        $resultKeys = $request->post('result_keys', []);
        $resultValues = $request->post('result_values', []);
        if (is_array($resultKeys) && is_array($resultValues)) {
            $results = [];
            foreach ($resultKeys as $i => $key) {
                $key = trim((string) $key);
                $value = trim((string) ($resultValues[$i] ?? ''));
                if ($key !== '') {
                    $results[$key] = $value;
                }
            }
            if (!empty($results)) {
                $data['results'] = $results;
            }
        }

        // Validation
        $errors = [];
        if ($data['player_id'] <= 0) $errors[] = 'يجب اختيار اللاعب';
        if (empty($data['test_date'])) $errors[] = 'يجب تحديد تاريخ الاختبار';
        if (empty($data['test_type'])) $errors[] = 'يجب تحديد نوع الاختبار';

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

        try {
            $test = FitnessService::recordTest($data);
            return $this->redirect('/fitness-tests/' . $test->id)->withSuccess('تم تسجيل اختبار اللياقة بنجاح');
        } catch (\Throwable $e) {
            return $this->redirect('/fitness-tests/create')->withError('حدث خطأ: ' . $e->getMessage());
        }
    }

    /**
     * Show fitness test details.
     */
    public function show(Request $request, int $id): Response
    {
        $this->authorize('player.manage_fitness');

        $test = PlayerFitnessTest::findOrFail($id);

        $db = App::getInstance()->db();
        $player = $db->selectOne("SELECT * FROM players WHERE id = ?", [(int) $test->player_id]);
        $discipline = null;
        if ($test->discipline_id) {
            $discipline = $db->selectOne("SELECT * FROM sport_disciplines WHERE id = ?", [(int) $test->discipline_id]);
        }
        $coach = null;
        if ($test->coach_id) {
            $coach = $db->selectOne("SELECT * FROM coaches WHERE id = ?", [(int) $test->coach_id]);
        }

        // Get progression data for chart
        $progression = FitnessService::getProgressionData((int) $test->player_id);

        // Get player fitness summary
        $summary = FitnessService::getPlayerSummary((int) $test->player_id);

        return $this->view('PlayerAffairs.Views.fitness_show', [
            'test'        => $test,
            'player'      => $player,
            'discipline'  => $discipline,
            'coach'       => $coach,
            'progression' => $progression,
            'summary'     => $summary,
            'testTypes'   => PlayerFitnessTest::getTestTypes(),
            'fitnessLevels' => PlayerFitnessTest::getFitnessLevels(),
        ]);
    }
}
