<?php
require_once __DIR__ . '/config/db.php';
session_start();

header('Content-Type: application/json');

if (!isset($_SESSION['user_id']) || ($_SESSION['role']??'tourist') !== 'tourist') {
    echo json_encode(['ok'=>false,'error'=>'يجب تسجيل الدخول كسائح لإرسال طلب']);
    exit;
}

$pid     = (int)($_POST['provider_id'] ?? 0);
$message = trim($_POST['message']      ?? '');
$uid     = (int)$_SESSION['user_id'];

if ($pid <= 0 || $message === '') {
    echo json_encode(['ok'=>false,'error'=>'بيانات غير صحيحة']);
    exit;
}

try {
    $db = db();
    $p = $db->prepare("SELECT id FROM providers WHERE id=? AND status='approved' LIMIT 1");
    $p->execute([$pid]);
    if (!$p->fetch()) {
        echo json_encode(['ok'=>false,'error'=>'مقدم الخدمة غير موجود']);
        exit;
    }
    $stmt = $db->prepare("INSERT INTO service_requests (tourist_id, provider_id, message) VALUES (?,?,?)");
    $stmt->execute([$uid, $pid, $message]);
    echo json_encode(['ok'=>true]);
} catch (Exception $e) {
    echo json_encode(['ok'=>false,'error'=>'خطأ في قاعدة البيانات']);
}
