<?php
declare(strict_types=1);

namespace App\Modules\MedicalBoard\Controllers;

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

class MedicalBoardController extends Controller
{
    public function index(Request $request): Response
    {
        $this->authorize('medical.board.view');
        $db = App::getInstance()->db();

        $status = $request->get('status', 'pending');
        $where = '1=1';
        $params = [];

        if ($status) {
            $where .= ' AND pmr.approval_status = ?';
            $params[] = $status;
        }

        $records = $db->select(
            "SELECT pmr.*, p.full_name_ar as player_name, p.card_status,
                    p.phone as player_phone, d.file_path as document_path
             FROM player_medical_records pmr
             JOIN players p ON p.id = pmr.player_id
             LEFT JOIN documents d ON d.id = pmr.document_id
             WHERE {$where}
             ORDER BY pmr.created_at DESC
             LIMIT 100",
            $params
        );

        return $this->view('MedicalBoard.Views.index', [
            'records' => $records,
            'currentStatus' => $status,
        ]);
    }

    public function approve(Request $request, string $id): Response
    {
        $this->authorize('medical.board.approve');
        $db = App::getInstance()->db();

        $record = $db->selectOne("SELECT * FROM player_medical_records WHERE id = ?", [(int) $id]);
        if (!$record) return $this->redirect('/medical-board')->withError('السجل غير موجود');

        $expiryDate = trim($request->post('expiry_date', ''));
        if (!$expiryDate) {
            return $this->redirect('/medical-board')->withError('تاريخ انتهاء الصلاحية مطلوب');
        }

        $employee = App::getInstance()->currentEmployee();

        $db->update('player_medical_records', [
            'approval_status' => 'approved',
            'result' => 'fit',
            'expiry_date' => $expiryDate,
            'approved_by' => $employee ? (int) $employee->id : null,
            'approved_at' => date('Y-m-d H:i:s'),
        ], 'id = ?', [(int) $id]);

        $db->update('players', [
            'medical_status' => 'fit',
            'medical_expiry_date' => $expiryDate,
        ], 'id = ?', [(int) $record['player_id']]);

        return $this->redirect('/medical-board')->withSuccess('تم اعتماد الشهادة الطبية');
    }

    public function reject(Request $request, string $id): Response
    {
        $this->authorize('medical.board.approve');
        $db = App::getInstance()->db();

        $record = $db->selectOne("SELECT * FROM player_medical_records WHERE id = ?", [(int) $id]);
        if (!$record) return $this->redirect('/medical-board')->withError('السجل غير موجود');

        $reason = trim($request->post('rejection_reason', ''));
        $employee = App::getInstance()->currentEmployee();

        $db->update('player_medical_records', [
            'approval_status' => 'rejected',
            'result' => 'unfit',
            'rejection_reason' => $reason ?: 'مرفوض',
            'approved_by' => $employee ? (int) $employee->id : null,
            'approved_at' => date('Y-m-d H:i:s'),
        ], 'id = ?', [(int) $id]);

        $db->update('players', [
            'medical_status' => 'unfit',
        ], 'id = ?', [(int) $record['player_id']]);

        return $this->redirect('/medical-board')->withSuccess('تم رفض الشهادة الطبية');
    }
}
