<?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);
$rating  = (int)($_POST['rating']      ?? 0);
$comment = trim($_POST['comment']      ?? '');
$uid     = (int)$_SESSION['user_id'];

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

try {
    $db = db();
    // Check provider exists and approved
    $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;
    }
    // Insert or update
    $stmt = $db->prepare("
        INSERT INTO provider_ratings (provider_id, user_id, rating, comment)
        VALUES (?,?,?,?)
        ON DUPLICATE KEY UPDATE rating=VALUES(rating), comment=VALUES(comment), created_at=NOW()
    ");
    $stmt->execute([$pid, $uid, $rating, $comment ?: null]);
    echo json_encode(['ok'=>true]);
} catch (Exception $e) {
    echo json_encode(['ok'=>false,'error'=>'خطأ في قاعدة البيانات']);
}
