<?php
session_start();
require '../config.php';

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Set content type for JSON response if it's an AJAX request
$is_ajax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
if ($is_ajax) {
    header('Content-Type: application/json');
}

// Debug: Log the request
if ($is_ajax) {
    error_log("AJAX Review Request - POST data: " . print_r($_POST, true));
}

if (!isset($_SESSION['user_id'])) {
    if ($is_ajax) {
        echo json_encode(['success' => false, 'message' => 'User not logged in']);
        exit;
    }
    header('Location: ../login.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user_id = $_SESSION['user_id'];
    $produk_id = $_POST['produk_id'] ?? null;
    $transaksi_id = $_POST['transaksi_id'] ?? null;
    $rating = $_POST['rating'] ?? null;
    $isi_ulasan = trim($_POST['isi_ulasan'] ?? '');

    // Debug: Log received values
    error_log("Received values - user_id: $user_id, produk_id: $produk_id, transaksi_id: $transaksi_id, rating: $rating, isi_ulasan: '$isi_ulasan'");

    // Validasi
    if (!$produk_id || !$transaksi_id || !$rating || !$isi_ulasan) {
        $error = 'Semua field harus diisi.';
        if ($is_ajax) {
            echo json_encode(['success' => false, 'message' => $error]);
            exit;
        }
        $_SESSION['error'] = $error;
        header('Location: ../detail_produk.php?id=' . $produk_id);
        exit;
    }
    if ($rating < 1 || $rating > 5) {
        $error = 'Rating tidak valid.';
        if ($is_ajax) {
            echo json_encode(['success' => false, 'message' => $error]);
            exit;
        }
        $_SESSION['error'] = $error;
        header('Location: ../detail_produk.php?id=' . $produk_id);
        exit;
    }
    if (strlen($isi_ulasan) > 500) {
        $error = 'Ulasan maksimal 500 karakter.';
        if ($is_ajax) {
            echo json_encode(['success' => false, 'message' => $error]);
            exit;
        }
        $_SESSION['error'] = $error;
        header('Location: ../detail_produk.php?id=' . $produk_id);
        exit;
    }

    // Cegah double review
    $stmt_cek = $conn->prepare("SELECT id FROM ulasan_produk WHERE pengguna_id = ? AND produk_id = ? AND transaksi_id = ?");
    $stmt_cek->bind_param("iii", $user_id, $produk_id, $transaksi_id);
    $stmt_cek->execute();
    $result_cek = $stmt_cek->get_result();
    if ($result_cek->num_rows > 0) {
        $error = 'Anda sudah pernah memberikan ulasan untuk produk ini pada transaksi yang sama. Satu produk hanya dapat diulas sekali per transaksi.';
        if ($is_ajax) {
            echo json_encode(['success' => false, 'message' => $error]);
            exit;
        }
        $_SESSION['error'] = $error;
        header('Location: ../detail_produk.php?id=' . $produk_id);
        exit;
    }

    // Verify user owns this transaction and it's completed
    $stmt_verify = $conn->prepare("SELECT td.produk_id, p.nama, p.gambar, up.ukuran FROM transaksi_detail td JOIN transaksi t ON td.transaksi_id = t.id JOIN produk p ON td.produk_id = p.id JOIN ukuran_produk up ON td.ukuran_id = up.id WHERE t.id = ? AND t.pengguna_id = ? AND t.status = 'selesai' AND td.produk_id = ?");
    $stmt_verify->bind_param("iii", $transaksi_id, $user_id, $produk_id);
    $stmt_verify->execute();
    $product_data = $stmt_verify->get_result()->fetch_assoc();

    if (!$product_data) {
        $error = 'Transaksi tidak valid atau belum selesai.';
        if ($is_ajax) {
            echo json_encode(['success' => false, 'message' => $error]);
            exit;
        }
        $_SESSION['error'] = $error;
        header('Location: ../detail_produk.php?id=' . $produk_id);
        exit;
    }

    // Simpan ulasan
    error_log("About to insert review - user_id: $user_id, produk_id: $produk_id, transaksi_id: $transaksi_id, rating: $rating, isi_ulasan: $isi_ulasan");

    $stmt = $conn->prepare("INSERT INTO ulasan_produk (pengguna_id, produk_id, transaksi_id, rating, isi_ulasan, status) VALUES (?, ?, ?, ?, ?, 'approved')");

    if (!$stmt) {
        $error_msg = 'Prepare failed: ' . $conn->error;
        error_log("Database prepare error: " . $error_msg);
        $error = $error_msg;
        if ($is_ajax) {
            echo json_encode(['success' => false, 'message' => $error]);
            exit;
        }
        $_SESSION['error'] = $error;
        header('Location: ../detail_produk.php?id=' . $produk_id);
        exit;
    }

    $stmt->bind_param("iiiis", $user_id, $produk_id, $transaksi_id, $rating, $isi_ulasan);

    if ($stmt->execute()) {
        $affected_rows = $stmt->affected_rows;
        error_log("Review inserted successfully. Affected rows: " . $affected_rows);

        $success_message = 'Ulasan berhasil dikirim.';
        if ($is_ajax) {
            echo json_encode([
                'success' => true,
                'message' => $success_message,
                'rating' => (int)$rating,
                'ulasan' => $isi_ulasan,
                'product' => $product_data
            ]);
            exit;
        }
        $_SESSION['success'] = $success_message;
    } else {
        $error_msg = 'Execute failed: ' . $stmt->error;
        error_log("Database execute error: " . $error_msg);

        $error = $error_msg;
        if ($is_ajax) {
            echo json_encode(['success' => false, 'message' => $error]);
            exit;
        }
        $_SESSION['error'] = $error;
    }

    if (!$is_ajax) {
        header('Location: ../detail_produk.php?id=' . $produk_id);
        exit;
    }
} else {
    if ($is_ajax) {
        echo json_encode(['success' => false, 'message' => 'Invalid request method']);
        exit;
    }
    header('Location: ../index.php');
    exit;
}
