<?php
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__ . '/../engine/Logger.php'; // COVERAGE
$ctx = Kernel::handle(['auth' => true]);
$u   = $ctx['user'];
$b      = json_decode(file_get_contents('php://input'), true) ?? [];
$action = $b['action'] ?? 'apply';

if ($action === 'apply') {
    $name    = mb_substr(trim($b['name'] ?? ''), 0, 200);
    $license = mb_substr(trim($b['license_no'] ?? ''), 0, 100);
    $address = mb_substr(trim($b['address'] ?? ''), 0, 300);
    $phone   = mb_substr(trim($b['phone'] ?? ''), 0, 30);
    $state   = mb_substr(trim($b['state'] ?? $u['state'] ?? ''), 0, 100);
    $city    = mb_substr(trim($b['city']  ?? $u['city']  ?? ''), 0, 100);
    $hours   = mb_substr(trim($b['hours'] ?? ''), 0, 200);

    if (!$name || !$license || !$phone) Kernel::fail('missing_fields', '', 400);

    db()->prepare('INSERT INTO pharmacies (user_id,name,license_no,address,phone,whatsapp,state,city,neighborhood_id,hours) VALUES (?,?,?,?,?,?,?,?,?,?)')
        ->execute([$u['id'], $name, $license, $address, $phone, $b['whatsapp'] ?? $phone, $state, $city, $u['neighborhood_id'] ?: null, $hours]);

    $pid = (int)db()->lastInsertId();
    // تلقائياً يُضاف كخدمة في دليل الحي
    db()->prepare('INSERT INTO neighborhood_services (provider_user_id,pharmacy_id,neighborhood_id,state,city,category,name,address,phone) VALUES (?,?,?,?,?,?,?,?,?)')
        ->execute([$u['id'], $pid, $u['neighborhood_id'] ?: null, $state, $city, 'health', "صيدلية: $name", $address, $phone]);

    save_notification($u['id'], 'pharmacy_applied', '✅ تم استلام طلبك', "طلب تسجيل صيدليتك «$name» قيد المراجعة. سيُفعَّل خلال 48 ساعة.");
    json_response(['success' => true, 'pharmacy_id' => $pid, 'message' => 'تم تقديم طلب الصيدلية. سيراجعه فريق سودانا خلال 48 ساعة.']);
}

// قائمة الصيدليات للزوار
if ($action === 'list') {
    $state = $_GET['state'] ?? '';
    $city  = $_GET['city']  ?? '';
    $st    = db()->prepare("SELECT id,name,address,phone,whatsapp,hours,delivery,state,city,rating_avg FROM pharmacies WHERE status='active'" . ($state?" AND state=?":'') . ($city?" AND city=?":'') . " ORDER BY name LIMIT 100");
    $params = array_filter([$state ?: null, $city ?: null]);
    $st->execute(array_values($params));
    json_response(['success' => true, 'pharmacies' => $st->fetchAll()]);
}

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