<?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'];

// Provider must be verified
if (!$u['provider_verified']) {
    json_response([
        'error'   => 'not_verified',
        'message' => 'يجب التحقق من حسابك كمزود أولاً.',
        'action'  => ['label'=>'قدّم طلب التحقق','url'=>'#providers'],
    ], 403);
}

$b      = json_decode(file_get_contents('php://input'), true) ?? [];
$action = $_GET['action'] ?? ($b['action'] ?? 'list');

// ── LIST ─────────────────────────────────────────────────────
if ($action === 'list') {
    $st = db()->prepare(
        'SELECT ps.*, COUNT(bk.id) AS bookings_count FROM provider_services ps
         LEFT JOIN bookings bk ON bk.service_id=ps.id AND bk.status NOT IN ("cancelled","rejected")
         WHERE ps.provider_id=? GROUP BY ps.id ORDER BY ps.created_at DESC'
    );
    $st->execute([$u['id']]);
    json_response(['success'=>true,'services'=>$st->fetchAll()]);
}

// ── CREATE ────────────────────────────────────────────────────
if ($action === 'create') {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') Kernel::fail('method_not_allowed', '', 405);
    if (!check_rate_limit('svc_create_'.$u['id'], 20, 3600)) Kernel::fail('rate_limit', '', 429);

    $cnt = db()->prepare('SELECT COUNT(*) FROM provider_services WHERE provider_id=? AND is_active=1');
    $cnt->execute([$u['id']]);
    if ((int)$cnt->fetchColumn() >= 10) Kernel::fail('limit', 'الحد الأقصى 10 خدمات نشطة', 403);

    $title    = mb_substr(trim($b['title']       ?? ''), 0, 200);
    $desc     = mb_substr(trim($b['description'] ?? ''), 0, 1000);
    $category = $b['category']      ?? 'other';
    $pType    = in_array($b['pricing_type']??'', ['free','fixed','hourly','negotiable']) ? $b['pricing_type'] : 'negotiable';
    $price    = ($pType==='fixed'||$pType==='hourly') ? (float)($b['price_sdg']??0) : null;
    $location = in_array($b['location_type']??'', ['in_person','online','both']) ? $b['location_type'] : 'in_person';
    $duration = (int)($b['duration_min'] ?? 60);

    if (!$title || mb_strlen($title)<5) Kernel::fail('title_required', 'العنوان 5 أحرف على الأقل', 400);
    if (!$desc  || mb_strlen($desc)<20)  Kernel::fail('desc_required', 'الوصف 20 حرفاً على الأقل', 400);
    if ($pType!=='free' && $pType!=='negotiable' && (!$price || $price<=0))
        Kernel::fail('price_required', 'السعر مطلوب للباقات المدفوعة', 400);

    db()->prepare(
        'INSERT INTO provider_services (provider_id, title, description, category, pricing_type, price_sdg, duration_min, location_type)
         VALUES (?,?,?,?,?,?,?,?)'
    )->execute([$u['id'], $title, $desc, $category, $pType, $price, $duration, $location]);

    $svcId = (int)db()->lastInsertId();
    json_response(['success'=>true,'service_id'=>$svcId,'message'=>'تمت إضافة الخدمة ✅ تظهر الآن للمستخدمين']);
}

// ── UPDATE ────────────────────────────────────────────────────
if ($action === 'update') {
    $svcId = (int)($b['service_id'] ?? 0);
    $check = db()->prepare('SELECT id FROM provider_services WHERE id=? AND provider_id=? LIMIT 1');
    $check->execute([$svcId, $u['id']]);
    if (!$check->fetch()) Kernel::fail('not_found', '', 404);

    $fields = []; $params = [];
    if (isset($b['title']))       { $fields[] = 'title=?';       $params[] = mb_substr($b['title'],0,200); }
    if (isset($b['description'])) { $fields[] = 'description=?'; $params[] = mb_substr($b['description'],0,1000); }
    if (isset($b['price_sdg']))   { $fields[] = 'price_sdg=?';   $params[] = (float)$b['price_sdg']; }
    if (isset($b['is_active']))   { $fields[] = 'is_active=?';   $params[] = (int)$b['is_active']; }
    if (empty($fields)) Kernel::fail('nothing_to_update', '', 400);

    $params[] = $svcId;
    db()->prepare('UPDATE provider_services SET '.implode(',',$fields).' WHERE id=?')->execute($params);
    json_response(['success'=>true,'message'=>'تم تحديث الخدمة']);
}

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