<?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.*,
                    COALESCE(p.full_name_ar, sp.full_name_ar) as player_name,
                    COALESCE(p.card_status, 'N/A') as card_status,
                    COALESCE(p.phone, sp.phone) as player_phone,
                    d.file_path as document_path,
                    spd.file_path as sa_document_path
             FROM player_medical_records pmr
             LEFT JOIN players p ON p.id = pmr.player_id AND pmr.source = 'membership'
             LEFT JOIN sa_players sp ON sp.id = pmr.sa_player_id AND pmr.source = 'sports_activity'
             LEFT JOIN documents d ON d.id = pmr.document_id
             LEFT JOIN sa_player_documents spd ON spd.id = pmr.sa_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]);

        if (($record['source'] ?? 'membership') === 'sports_activity' && !empty($record['sa_player_id'])) {
            $db->update('sa_players', [
                'medical_status' => 'fit',
                'medical_expiry_date' => $expiryDate,
                'updated_at' => date('Y-m-d H:i:s'),
            ], 'id = ?', [(int) $record['sa_player_id']]);

            if (!empty($record['sa_document_id'])) {
                $db->update('sa_player_documents', [
                    'approval_status' => 'approved',
                    'expiry_date' => $expiryDate,
                    'approved_by' => $employee ? (int) $employee->id : null,
                    'approved_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s'),
                ], 'id = ?', [(int) $record['sa_document_id']]);
            }
        } else {
            $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]);

        if (($record['source'] ?? 'membership') === 'sports_activity' && !empty($record['sa_player_id'])) {
            $db->update('sa_players', [
                'medical_status' => 'unfit',
                'updated_at' => date('Y-m-d H:i:s'),
            ], 'id = ?', [(int) $record['sa_player_id']]);

            if (!empty($record['sa_document_id'])) {
                $db->update('sa_player_documents', [
                    'approval_status' => 'rejected',
                    'updated_at' => date('Y-m-d H:i:s'),
                ], 'id = ?', [(int) $record['sa_document_id']]);
            }
        } else {
            $db->update('players', [
                'medical_status' => 'unfit',
            ], 'id = ?', [(int) $record['player_id']]);
        }

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