<?php
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__ . '/../engine/Logger.php'; // COVERAGE
$action = $_GET['action'] ?? 'request';
$b      = json_decode(file_get_contents('php://input'), true) ?? [];

// ── تقديم وصفة طبية (يحتاج تسجيل دخول) ─────────────────────
if ($action === 'request') {
    $ctx = Kernel::handle(['auth' => true]);
$u   = $ctx['user'];
    if (!check_rate_limit('presc_' . $u['id'], 3, 3600))
        Kernel::fail('rate_limit', 'الحد الأقصى 3 وصفات/ساعة', 429);

    $image_url = null;
    $ai_extracted = null;
    $medicines_text = mb_substr(trim($b['medicines_text'] ?? ''), 0, 1000);

    // رفع صورة الوصفة + استخراج AI
    if (!empty($b['image_base64'])) {
        $image_url = save_uploaded_image($b['image_base64']);
        if ($image_url) {
            // Gemini Vision يقرأ الوصفة
            try {
                $pure = preg_replace('/^data:image\/\w+;base64,/', '', $b['image_base64']);
                $payload = [
                    'contents' => [[
                        'parts' => [
                            ['text' => 'استخرج أسماء الأدوية من هذه الوصفة الطبية. أجب بـ JSON فقط: {"medicines":["دواء1","دواء2"],"note":"ملاحظة الطبيب إن وُجدت"}'],
                            ['inline_data' => ['mime_type' => 'image/jpeg', 'data' => $pure]],
                        ]
                    ]],
                    'generationConfig' => ['maxOutputTokens' => 300, 'temperature' => 0.1],
                ];
                $url = GEMINI_ENDPOINT . 'gemini-1.5-flash:generateContent?key=' . GEMINI_API_KEY;
                $ch  = curl_init($url);
                curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode($payload),
                    CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30,
                    CURLOPT_HTTPHEADER => ['Content-Type: application/json']]);
                $raw  = curl_exec($ch); curl_close($ch);
                $data = json_decode($raw, true);
                $text = $data['candidates'][0]['content']['parts'][0]['text'] ?? '';
                $clean = preg_replace('/^```json\s*|\s*```$/', '', trim($text));
                $ai_extracted = json_decode($clean, true);
                if (!empty($ai_extracted['medicines']))
                    $medicines_text = implode('، ', $ai_extracted['medicines']);
            } catch (Throwable $ignored) {}
        }
    }

    if (!$medicines_text) Kernel::fail('medicines_required', 'أدخل أسماء الأدوية أو ارفع صورة الوصفة', 400);

    db()->prepare(
        'INSERT INTO prescription_requests (user_id, image_url, ai_extracted, medicines_text, state, city, neighborhood_id)
         VALUES (?, ?, ?, ?, ?, ?, ?)'
    )->execute([$u['id'], $image_url, $ai_extracted ? json_encode($ai_extracted, JSON_UNESCAPED_UNICODE) : null,
        $medicines_text, $u['state'] ?? '', $u['city'] ?? '', $u['neighborhood_id'] ?: null]);

    $req_id = (int)db()->lastInsertId();

    // إشعار الصيدليات القريبة
    $pharma_st = db()->prepare(
        "SELECT p.id, p.name, p.whatsapp, u.fcm_token
         FROM pharmacies p LEFT JOIN users u ON u.id = p.user_id
         WHERE p.status = 'active' AND p.state = ? LIMIT 10"
    );
    $pharma_st->execute([$u['state'] ?? '']);
    $pharmacies = $pharma_st->fetchAll();
    $notified = 0;
    foreach ($pharmacies as $ph) {
        if ($ph['fcm_token']) {
            send_push($ph['fcm_token'], '💊 وصفة طبية جديدة', "مريض يبحث عن: " . mb_substr($medicines_text, 0, 60), ['req_id' => (string)$req_id, 'tag' => 'prescription']);
            $notified++;
        }
    }

    json_response(['success' => true, 'request_id' => $req_id, 'medicines' => $medicines_text,
        'ai_extracted' => $ai_extracted, 'notified_pharmacies' => $notified,
        'message' => "تم إرسال طلبك لـ $notified صيدلية قريبة. ستصلك ردودهم قريباً."]);
}

// ── رد الصيدلية على وصفة ────────────────────────────────────
if ($action === 'respond') {
    $u       = require_auth();
    $req_id  = (int)($b['request_id'] ?? 0);
    $pharma_id = (int)($b['pharmacy_id'] ?? 0);
    $avail   = in_array($b['available'] ?? '', ['full','partial','none']) ? $b['available'] : 'none';
    $note    = mb_substr(trim($b['note'] ?? ''), 0, 300);

    $req = db()->prepare('SELECT * FROM prescription_requests WHERE id = ? AND status = "open" LIMIT 1');
    $req->execute([$req_id]);
    $request = $req->fetch();
    if (!$request) Kernel::fail('not_found', '', 404);

    db()->prepare('INSERT INTO prescription_responses (request_id, pharmacy_id, available, note) VALUES (?,?,?,?)')
        ->execute([$req_id, $pharma_id, $avail, $note]);

    // إشعار المريض
    $fcm = get_user_token($request['user_id']);
    $avail_ar = ['full' => '✅ متوفر كامل', 'partial' => '⚠️ متوفر جزئياً', 'none' => '❌ غير متوفر'];
    if ($fcm) send_push($fcm, '💊 رد صيدلية', $avail_ar[$avail] . ($note ? ": $note" : ''), ['req_id' => (string)$req_id, 'tag' => 'prescription']);
    save_notification($request['user_id'], 'prescription_response', '💊 رد من صيدلية', $avail_ar[$avail] . ($note ? ": $note" : ''));

    json_response(['success' => true]);
}

// ── قائمة طلباتي ─────────────────────────────────────────────
if ($action === 'my_requests') {
    $u = require_auth();
    $st = db()->prepare(
        'SELECT r.*, (SELECT COUNT(*) FROM prescription_responses pr WHERE pr.request_id=r.id) AS response_count
         FROM prescription_requests r WHERE r.user_id = ? ORDER BY r.id DESC LIMIT 20'
    );
    $st->execute([$u['id']]);
    json_response(['success' => true, 'requests' => $st->fetchAll()]);
}

// ── تفاصيل طلب + ردود الصيدليات ────────────────────────────
if ($action === 'responses') {
    $u      = require_auth();
    $req_id = (int)($_GET['id'] ?? 0);
    $st     = db()->prepare(
        'SELECT pr.*, p.name AS pharmacy_name, p.phone, p.address
         FROM prescription_responses pr JOIN pharmacies p ON p.id = pr.pharmacy_id
         WHERE pr.request_id = ? ORDER BY FIELD(pr.available,"full","partial","none")'
    );
    $st->execute([$req_id]);
    json_response(['success' => true, 'responses' => $st->fetchAll()]);
}

Kernel::fail('unknown_action', '', 400);
