<?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\Services\MedicalRecordService;

class MedicalApprovalController extends Controller
{
    public function index(Request $request): Response
    {
        $this->authorize('player.approve_medical');

        $db = App::getInstance()->db();
        $filter = trim((string) $request->get('filter', 'pending'));

        $whereClause = match ($filter) {
            'approved' => "pmr.approval_status = 'approved'",
            'rejected' => "pmr.approval_status = 'rejected'",
            default    => "pmr.approval_status = 'pending'",
        };

        $records = $db->select(
            "SELECT pmr.*, p.full_name_ar AS player_name, p.registration_serial,
                    p.player_type, p.photo_path
             FROM player_medical_records pmr
             LEFT JOIN players p ON p.id = pmr.player_id
             WHERE {$whereClause}
             ORDER BY pmr.created_at DESC
             LIMIT 100"
        );

        return $this->view('PlayerAffairs.Views.medical_approvals', [
            'records' => $records,
            'filter'  => $filter,
        ]);
    }

    public function approve(Request $request, string $id): Response
    {
        $this->authorize('player.approve_medical');

        $employee = App::getInstance()->currentEmployee();
        $approvedBy = $employee ? (int) $employee->id : 0;
        $medicalLevel = (int) $request->post('medical_level', 1);
        if ($medicalLevel < 1 || $medicalLevel > 3) {
            $medicalLevel = 1;
        }

        try {
            MedicalRecordService::approveRecord((int) $id, $approvedBy, $medicalLevel);
        } catch (\RuntimeException $e) {
            return $this->redirect('/medical-approvals')->withError($e->getMessage());
        }

        return $this->redirect('/medical-approvals')->withSuccess('تم اعتماد السجل الطبي بنجاح');
    }

    public function reject(Request $request, string $id): Response
    {
        $this->authorize('player.approve_medical');

        $reason = trim((string) $request->post('rejection_reason', ''));
        if (empty($reason)) {
            return $this->redirect('/medical-approvals')->withError('يجب إدخال سبب الرفض');
        }

        $employee = App::getInstance()->currentEmployee();
        $rejectedBy = $employee ? (int) $employee->id : 0;

        try {
            MedicalRecordService::rejectRecord((int) $id, $rejectedBy, $reason);
        } catch (\RuntimeException $e) {
            return $this->redirect('/medical-approvals')->withError($e->getMessage());
        }

        return $this->redirect('/medical-approvals')->withSuccess('تم رفض السجل الطبي');
    }
}
