<?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\PlayerInjury;
use App\Modules\PlayerAffairs\Models\Player;
use App\Modules\PlayerAffairs\Services\InjuryService;

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

        $filters = [
            'q'             => trim((string) $request->get('q', '')),
            'player_id'     => $request->get('player_id', '') !== '' ? (int) $request->get('player_id') : null,
            'status'        => trim((string) $request->get('status', '')),
            'severity'      => trim((string) $request->get('severity', '')),
            'injury_type'   => trim((string) $request->get('injury_type', '')),
            'discipline_id' => $request->get('discipline_id', '') !== '' ? (int) $request->get('discipline_id') : null,
            '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 = PlayerInjury::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.injuries', [
            'injuries'      => $result['data'],
            'pagination'    => $result['pagination'],
            'filters'       => $filters,
            'statuses'      => PlayerInjury::getStatuses(),
            'severities'    => PlayerInjury::getSeverities(),
            'injuryTypes'   => PlayerInjury::getInjuryTypes(),
            'disciplines'   => $disciplines,
        ]);
    }

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

        $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"
        );

        $players = Player::allActive();

        return $this->view('PlayerAffairs.Views.injury_create', [
            'players'        => $players,
            'disciplines'    => $disciplines,
            'injuryTypes'    => PlayerInjury::getInjuryTypes(),
            'severities'     => PlayerInjury::getSeverities(),
            'bodyParts'      => PlayerInjury::getBodyParts(),
            'occurredDuring' => PlayerInjury::getOccurredDuringOptions(),
        ]);
    }

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

        $data = [
            'player_id'                 => (int) $request->post('player_id', 0),
            'discipline_id'             => $request->post('discipline_id', '') !== '' ? (int) $request->post('discipline_id') : null,
            'injury_type'               => trim((string) $request->post('injury_type', '')),
            'body_part'                 => trim((string) $request->post('body_part', '')),
            'severity'                  => trim((string) $request->post('severity', '')),
            'description_ar'            => trim((string) $request->post('description_ar', '')),
            'occurred_date'             => trim((string) $request->post('occurred_date', '')),
            'occurred_during'           => trim((string) $request->post('occurred_during', '')) ?: null,
            'session_id'                => $request->post('session_id', '') !== '' ? (int) $request->post('session_id') : null,
            'tournament_match_id'       => $request->post('tournament_match_id', '') !== '' ? (int) $request->post('tournament_match_id') : null,
            'diagnosed_by'              => trim((string) $request->post('diagnosed_by', '')) ?: null,
            'diagnosis_ar'              => trim((string) $request->post('diagnosis_ar', '')) ?: null,
            'treatment_ar'              => trim((string) $request->post('treatment_ar', '')) ?: null,
            'estimated_recovery_days'   => $request->post('estimated_recovery_days', '') !== '' ? (int) $request->post('estimated_recovery_days') : null,
            'follow_up_date'            => trim((string) $request->post('follow_up_date', '')) ?: null,
            'notes'                     => trim((string) $request->post('notes', '')) ?: null,
        ];

        // Restricted activities from checkboxes
        $restrictedActivities = $request->post('restricted_activities', []);
        if (is_array($restrictedActivities) && !empty($restrictedActivities)) {
            $data['restricted_activities'] = $restrictedActivities;
        }

        // Validation
        $errors = [];
        if ($data['player_id'] <= 0) $errors[] = 'يجب اختيار اللاعب';
        if (empty($data['injury_type'])) $errors[] = 'يجب تحديد نوع الإصابة';
        if (empty($data['body_part'])) $errors[] = 'يجب تحديد مكان الإصابة';
        if (empty($data['severity'])) $errors[] = 'يجب تحديد شدة الإصابة';
        if (empty($data['occurred_date'])) $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('/injuries/create');
        }

        try {
            $injury = InjuryService::reportInjury($data);
            return $this->redirect('/injuries/' . $injury->id)->withSuccess('تم تسجيل الإصابة بنجاح');
        } catch (\Throwable $e) {
            return $this->redirect('/injuries/create')->withError('حدث خطأ: ' . $e->getMessage());
        }
    }

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

        $injury = PlayerInjury::findOrFail($id);

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

        // Get injury history for this player
        $playerInjuries = PlayerInjury::getForPlayer((int) $injury->player_id);

        // Get stats
        $stats = InjuryService::getPlayerStats((int) $injury->player_id);

        return $this->view('PlayerAffairs.Views.injury_show', [
            'injury'          => $injury,
            'player'          => $player,
            'discipline'      => $discipline,
            'playerInjuries'  => $playerInjuries,
            'stats'           => $stats,
            'statuses'        => PlayerInjury::getStatuses(),
            'severities'      => PlayerInjury::getSeverities(),
            'injuryTypes'     => PlayerInjury::getInjuryTypes(),
            'bodyParts'       => PlayerInjury::getBodyParts(),
        ]);
    }

    /**
     * Update injury status (POST).
     */
    public function updateStatus(Request $request, int $id): Response
    {
        $this->authorize('player.manage_injuries');

        $newStatus = trim((string) $request->post('status', ''));
        $validStatuses = array_keys(PlayerInjury::getStatuses());

        if (!in_array($newStatus, $validStatuses, true)) {
            return $this->redirect('/injuries/' . $id)->withError('حالة غير صالحة');
        }

        $clearanceData = null;
        if ($newStatus === 'recovered') {
            $clearanceData = [
                'recovery_date'          => trim((string) $request->post('recovery_date', '')) ?: date('Y-m-d'),
                'clearance_document_id'  => $request->post('clearance_document_id', '') !== '' ? (int) $request->post('clearance_document_id') : null,
            ];
        }

        try {
            InjuryService::updateStatus($id, $newStatus, $clearanceData);
            return $this->redirect('/injuries/' . $id)->withSuccess('تم تحديث حالة الإصابة');
        } catch (\Throwable $e) {
            return $this->redirect('/injuries/' . $id)->withError('حدث خطأ: ' . $e->getMessage());
        }
    }

    /**
     * Clear player from injury (mark as recovered).
     */
    public function clearPlayer(Request $request, int $id): Response
    {
        $this->authorize('player.manage_injuries');

        $clearanceData = [
            'recovery_date'         => trim((string) $request->post('recovery_date', '')) ?: date('Y-m-d'),
            'clearance_document_id' => $request->post('clearance_document_id', '') !== '' ? (int) $request->post('clearance_document_id') : null,
        ];

        try {
            InjuryService::updateStatus($id, 'recovered', $clearanceData);
            return $this->redirect('/injuries/' . $id)->withSuccess('تم إصدار التصريح الطبي - اللاعب جاهز للعودة');
        } catch (\Throwable $e) {
            return $this->redirect('/injuries/' . $id)->withError('حدث خطأ: ' . $e->getMessage());
        }
    }
}
