<?php
declare(strict_types=1);

namespace App\Modules\PlayerApi\Controllers\Api;

use App\Core\ApiController;
use App\Core\App;
use App\Core\Request;
use App\Core\Response;
use App\Core\Exceptions\ValidationException;

final class MedicalController extends ApiController
{
    public function __construct(Request $request)
    {
        parent::__construct();
        $this->request = $request;
    }

    public function records(Request $request): Response
    {
        $player = App::getInstance()->currentPlayer();
        $db = App::getInstance()->db();

        $records = $db->select(
            "SELECT id, record_type, certificate_type, exam_date, expiry_date,
                    doctor_name, clinic_name, result, restrictions,
                    approval_status, rejection_reason, document_id, created_at
             FROM player_medical_records
             WHERE player_id = ?
             ORDER BY exam_date DESC",
            [$player->id]
        );

        return $this->successResponse($records);
    }

    public function submit(Request $request): Response
    {
        try {
            $data = $this->validatedJson([
                'record_type' => 'required|string|in:fitness_cert,medical_exam,blood_test,cardiac_screen,other',
                'certificate_type' => 'nullable|string|in:recreational,academy,international',
                'exam_date' => 'required|string',
                'expiry_date' => 'required|string',
                'doctor_name' => 'nullable|string|max:200',
                'clinic_name' => 'nullable|string|max:200',
                'cert_number' => 'nullable|string|max:100',
                'restrictions' => 'nullable|string|max:500',
            ]);
        } catch (ValidationException $e) {
            return $this->errorResponse('بيانات غير صالحة', 422, $e->errors());
        }

        $player = App::getInstance()->currentPlayer();
        $db = App::getInstance()->db();

        $db->insert('player_medical_records', [
            'player_id' => $player->id,
            'record_type' => $data['record_type'],
            'certificate_type' => $data['certificate_type'] ?? null,
            'exam_date' => $data['exam_date'],
            'expiry_date' => $data['expiry_date'],
            'doctor_name' => $data['doctor_name'] ?? null,
            'clinic_name' => $data['clinic_name'] ?? null,
            'cert_number' => $data['cert_number'] ?? null,
            'restrictions' => $data['restrictions'] ?? null,
            'result' => 'pending',
            'approval_status' => 'pending',
        ]);

        $recordId = (int) $db->selectOne("SELECT LAST_INSERT_ID() as id")['id'];

        $db->update('players', [
            'medical_status' => 'pending',
            'medical_expiry_date' => $data['expiry_date'],
        ], 'id = ?', [$player->id]);

        return $this->successResponse([
            'id' => $recordId,
            'message' => 'تم تقديم السجل الطبي وسيتم مراجعته',
        ], 201);
    }

    public function upload(Request $request, string $id): Response
    {
        $player = App::getInstance()->currentPlayer();
        $db = App::getInstance()->db();

        $record = $db->selectOne(
            "SELECT id FROM player_medical_records WHERE id = ? AND player_id = ?",
            [(int) $id, $player->id]
        );

        if (!$record) {
            return $this->errorResponse('السجل الطبي غير موجود', 404);
        }

        if (!isset($_FILES['document']) || $_FILES['document']['error'] !== UPLOAD_ERR_OK) {
            return $this->errorResponse('يرجى رفع ملف صالح', 422);
        }

        $file = $_FILES['document'];
        $allowedTypes = ['image/jpeg', 'image/png', 'image/webp', 'application/pdf'];

        if (!in_array($file['type'], $allowedTypes, true)) {
            return $this->errorResponse('نوع الملف غير مسموح. المسموح: JPG, PNG, WebP, PDF', 422);
        }

        $maxSize = 10 * 1024 * 1024; // 10MB
        if ($file['size'] > $maxSize) {
            return $this->errorResponse('حجم الملف أكبر من 10 ميجا', 422);
        }

        $ext = match ($file['type']) {
            'image/jpeg' => 'jpg',
            'image/png' => 'png',
            'image/webp' => 'webp',
            'application/pdf' => 'pdf',
            default => 'bin',
        };

        $filename = 'medical_' . $player->id . '_' . $id . '_' . time() . '.' . $ext;
        $uploadDir = App::getInstance()->storagePath() . '/uploads/medical';

        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        $destination = $uploadDir . '/' . $filename;
        move_uploaded_file($file['tmp_name'], $destination);

        $db->insert('documents', [
            'entity_type' => 'player_medical',
            'entity_id' => (int) $id,
            'file_name' => $filename,
            'file_path' => 'uploads/medical/' . $filename,
            'file_type' => $file['type'],
            'file_size' => $file['size'],
            'uploaded_by_type' => 'player',
            'uploaded_by_id' => $player->id,
        ]);

        $documentId = (int) $db->selectOne("SELECT LAST_INSERT_ID() as id")['id'];

        $db->update('player_medical_records', [
            'document_id' => $documentId,
        ], 'id = ?', [(int) $id]);

        return $this->successResponse([
            'document_id' => $documentId,
            'file_name' => $filename,
            'message' => 'تم رفع المستند بنجاح',
        ], 201);
    }
}
