<?php
/**
 * POST /api/booking/rate.php
 * WAVE E — Full Kernel Replace
 * Rate a completed booking
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') Kernel::fail('method_not_allowed', '', 405);

$ctx = Kernel::handle(['auth' => true, 'rate' => 'api']);
$u   = $ctx['user'];

$b         = json_decode(file_get_contents('php://input'), true) ?? [];
$bookingId = (int)($b['booking_id'] ?? 0);
$rating    = (int)($b['rating'] ?? 0);
$comment   = mb_substr(trim($b['comment'] ?? ''), 0, 500);
$anon      = (bool)($b['is_anonymous'] ?? false);

if (!$bookingId || $rating < 1 || $rating > 5) {
    Kernel::fail('invalid_input', 'booking_id ورقم تقييم 1-5 مطلوبان', 400);
}

$bk = db()->prepare('SELECT * FROM bookings WHERE id=? AND user_id=? LIMIT 1');
$bk->execute([$bookingId, $u['id']]);
$booking = $bk->fetch();

if (!$booking) Kernel::fail('not_found', 'الحجز غير موجود', 404);
if ($booking['status'] !== 'completed') Kernel::fail('booking_not_done', 'الحجز لم يكتمل بعد', 409);
if ($booking['completed_at'] && strtotime($booking['completed_at']) < time() - 2592000) {
    Kernel::fail('rating_expired', 'انتهت مدة التقييم (30 يوم)', 410);
}

try {
    db()->prepare(
        "INSERT INTO booking_reviews (booking_id, user_id, provider_id, rating, comment, is_anonymous)
         VALUES (?,?,?,?,?,?)
         ON DUPLICATE KEY UPDATE rating=VALUES(rating), comment=VALUES(comment)"
    )->execute([$bookingId, $u['id'], $booking['provider_id'], $rating, $comment, (int)$anon]);

    db()->prepare(
        "UPDATE users SET avg_rating = (
            SELECT AVG(r.rating) FROM booking_reviews r WHERE r.provider_id=?
         ) WHERE id=?"
    )->execute([$booking['provider_id'], $booking['provider_id']]);

    Logger::info('booking_rated', [
        'booking_id'  => $bookingId,
        'provider_id' => (int)$booking['provider_id'],
        'rating'      => $rating,
    ]);

    $provToken = get_user_token($booking['provider_id']);
    if ($provToken) send_push($provToken, "تقييم جديد ⭐×{$rating}", 'شكراً لتقديم خدمة ممتازة!', ['tag' => 'rating']);

    Kernel::respond(['success' => true, 'rating' => $rating, 'message' => 'شكراً لتقييمك — يساعد المجتمع 🙏']);

} catch (Throwable $e) {
    Logger::error('booking_rate_failed', ['booking_id' => $bookingId, 'error' => $e->getMessage()]);
    Kernel::fail('rate_failed', 'فشل حفظ التقييم', 500);
}
