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

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo 'Unauthorized';
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $order_id = isset($_POST['order_id']) ? intval($_POST['order_id']) : 0;
    $rating = isset($_POST['rating']) ? intval($_POST['rating']) : 0;
    $review = isset($_POST['review']) ? trim($_POST['review']) : '';
    $user_id = $_SESSION['user_id'];

    if ($order_id <= 0 || $rating < 1 || $rating > 5) {
        echo 'Data tidak valid.';
        exit;
    }

    require_once '../config/db_config.php';
    $conn = $db_conn;

    // Cek apakah order milik user dan sudah selesai
    $cekOrder = $conn->prepare('SELECT * FROM orders WHERE order_id = ? AND user_id = ? AND status = ?');
    $cekOrder->execute([$order_id, $user_id, 'selesai']);
    if ($cekOrder->rowCount() === 0) {
        echo 'Order tidak valid atau belum selesai.';
        exit;
    }

    // Cek apakah sudah pernah rating
    $cekRating = $conn->prepare('SELECT * FROM order_ratings WHERE order_id = ? AND user_id = ?');
    $cekRating->execute([$order_id, $user_id]);
    if ($cekRating->rowCount() > 0) {
        echo 'Anda sudah memberi rating untuk pesanan ini.';
        exit;
    }

    // Simpan rating
    $stmt = $conn->prepare('INSERT INTO order_ratings (order_id, user_id, rating, review) VALUES (?, ?, ?, ?)');
    if ($stmt->execute([$order_id, $user_id, $rating, $review])) {
        echo 'Rating berhasil disimpan.';
    } else {
        echo 'Gagal menyimpan rating.';
    }
} else {
    echo 'Metode tidak diizinkan.';
} 