<?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 everything
error_log("=== BULK REVIEW DEBUG START ===");
error_log("Request Method: " . $_SERVER['REQUEST_METHOD']);
error_log("Is AJAX: " . ($is_ajax ? 'YES' : 'NO'));
error_log("Session ID: " . session_id());
error_log("Session Status: " . session_status());
error_log("POST data: " . print_r($_POST, true));
error_log("Session data: " . print_r($_SESSION, true));
error_log("Cookies: " . print_r($_COOKIE, true));
error_log("Headers: " . print_r(getallheaders(), true));

if (!isset($_SESSION['user_id'])) {
    // Try to get user_id from POST data as fallback
    $user_id = $_POST['user_id'] ?? null;

    if ($user_id) {
        // Verify this user_id exists and is valid
        $stmt_check = $conn->prepare("SELECT id FROM pengguna WHERE id = ?");
        $stmt_check->bind_param("i", $user_id);
        $stmt_check->execute();
        $user_check = $stmt_check->get_result()->fetch_assoc();

        if ($user_check) {
            error_log("Using user_id from form data: " . $user_id);
            // Set it in session for this request
            $_SESSION['user_id'] = $user_id;
        } else {
            error_log("ERROR: Invalid user_id in form data: " . $user_id);
            if ($is_ajax) {
                echo json_encode(['success' => false, 'message' => 'Invalid user ID']);
                exit;
            }
            header('Location: ../login.php');
            exit;
        }
    } else {
        error_log("ERROR: user_id not found in session or form data");
        if ($is_ajax) {
            echo json_encode(['success' => false, 'message' => 'User not logged in. Please refresh and try again.']);
            exit;
        }
        header('Location: ../login.php');
        exit;
    }
} else {
    error_log("SUCCESS: user_id found in session: " . $_SESSION['user_id']);
}

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

    // Debug: Log received values
    error_log("Bulk review - user_id: $user_id, transaksi_id: $transaksi_id");
    error_log("Product IDs: " . print_r($produk_ids, true));
    error_log("Ratings: " . print_r($ratings, true));
    error_log("Reviews: " . print_r($isi_ulasans, true));

    // Validasi
    if (!$transaksi_id || empty($produk_ids) || empty($ratings) || empty($isi_ulasans)) {
        $error = 'Data tidak lengkap.';
        if ($is_ajax) {
            echo json_encode(['success' => false, 'message' => $error]);
            exit;
        }
        $_SESSION['error'] = $error;
        header('Location: ../pelanggan/riwayat.php');
        exit;
    }

    // Verify transaction belongs to user and is completed
    $stmt_verify = $conn->prepare("SELECT * FROM transaksi WHERE id = ? AND pengguna_id = ? AND status = 'selesai'");
    $stmt_verify->bind_param("ii", $transaksi_id, $user_id);
    $stmt_verify->execute();
    $transaksi = $stmt_verify->get_result()->fetch_assoc();

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

    $success_count = 0;
    $errors = [];

    // Process each product review
    foreach ($produk_ids as $produk_id) {
        $produk_id = (int)$produk_id;
        $rating = isset($ratings[$produk_id]) ? (int)$ratings[$produk_id] : 0;
        $isi_ulasan = isset($isi_ulasans[$produk_id]) ? trim($isi_ulasans[$produk_id]) : '';

        error_log("Processing product $produk_id: rating=$rating, review='$isi_ulasan'");

        // Validate individual product data
        if ($rating < 1 || $rating > 5 || empty($isi_ulasan)) {
            $errors[] = "Data tidak valid untuk produk ID $produk_id";
            continue;
        }

        if (strlen($isi_ulasan) > 500) {
            $errors[] = "Ulasan terlalu panjang untuk produk ID $produk_id (maksimal 500 karakter)";
            continue;
        }

        // Check for duplicate 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) {
            $errors[] = "Produk ID $produk_id sudah pernah diulas untuk transaksi ini";
            continue;
        }

        // Verify product exists in this transaction
        $stmt_product = $conn->prepare("SELECT COUNT(*) as count FROM transaksi_detail WHERE transaksi_id = ? AND produk_id = ?");
        $stmt_product->bind_param("ii", $transaksi_id, $produk_id);
        $stmt_product->execute();
        $product_check = $stmt_product->get_result()->fetch_assoc();

        if ($product_check['count'] == 0) {
            $errors[] = "Produk ID $produk_id tidak ditemukan dalam transaksi ini";
            continue;
        }

        // Insert review
        error_log("About to insert review for product $produk_id");
        $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 for product ' . $produk_id . ': ' . $conn->error;
            error_log("Database prepare error: " . $error_msg);
            $errors[] = $error_msg;
            continue;
        }

        $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 for product $produk_id. Affected rows: " . $affected_rows);
            $success_count++;
        } else {
            $error_msg = 'Execute failed for product ' . $produk_id . ': ' . $stmt->error;
            error_log("Database execute error: " . $error_msg);
            $errors[] = $error_msg;
        }
    }

    // Prepare response
    if ($success_count > 0) {
        $message = "Berhasil menyimpan $success_count ulasan.";
        if (!empty($errors)) {
            $message .= " Namun ada beberapa error: " . implode(', ', $errors);
        }

        if ($is_ajax) {
            echo json_encode([
                'success' => true,
                'message' => $message,
                'success_count' => $success_count,
                'errors' => $errors
            ]);
        } else {
            $_SESSION['success'] = $message;
            header('Location: ../pelanggan/riwayat.php');
        }
    } else {
        $error = 'Tidak ada ulasan yang berhasil disimpan. Error: ' . implode(', ', $errors);
        if ($is_ajax) {
            echo json_encode(['success' => false, 'message' => $error]);
        } else {
            $_SESSION['error'] = $error;
            header('Location: ../pelanggan/riwayat.php');
        }
    }
} else {
    $error = 'Invalid request method.';
    if ($is_ajax) {
        echo json_encode(['success' => false, 'message' => $error]);
    } else {
        $_SESSION['error'] = $error;
        header('Location: ../pelanggan/riwayat.php');
    }
}
