<?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 (PELANGGAN FOLDER) ===");
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());

// Check if request is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $response = ['success' => false, 'message' => 'Method not allowed'];
    if ($is_ajax) {
        echo json_encode($response);
    } else {
        echo "Method not allowed";
    }
    exit;
}

// Check if user is logged in
if (!isset($_SESSION['id_pelanggan']) && !isset($_POST['user_id'])) {
    error_log("No session found and no user_id in POST");
    $response = ['success' => false, 'message' => 'User not logged in'];
    if ($is_ajax) {
        echo json_encode($response);
    } else {
        header('Location: ../login.php');
    }
    exit;
}

// Get user ID from session or POST data
$user_id = isset($_SESSION['id_pelanggan']) ? $_SESSION['id_pelanggan'] : $_POST['user_id'];
error_log("User ID: " . $user_id);

// Debug: Log all POST data
error_log("POST data: " . print_r($_POST, true));

// Debug: Test database connection
if (!$conn) {
    error_log("Database connection failed: " . mysqli_connect_error());
    $response = ['success' => false, 'message' => 'Database connection failed'];
    if ($is_ajax) {
        echo json_encode($response);
    } else {
        $_SESSION['error_message'] = 'Database connection failed';
        header('Location: riwayat.php');
    }
    exit;
}

error_log("Database connection successful");

// Test if table exists
$table_check = mysqli_query($conn, "SHOW TABLES LIKE 'ulasan_produk'");
if (mysqli_num_rows($table_check) == 0) {
    error_log("Table 'ulasan_produk' does not exist");
    $response = ['success' => false, 'message' => 'Tabel ulasan_produk tidak ditemukan'];
    if ($is_ajax) {
        echo json_encode($response);
    } else {
        $_SESSION['error_message'] = 'Tabel ulasan_produk tidak ditemukan';
        header('Location: riwayat.php');
    }
    exit;
}

error_log("Table 'ulasan_produk' exists");

// Start transaction
mysqli_autocommit($conn, false);

try {
    $success_count = 0;
    $error_messages = [];

    // Get product IDs from POST data - handle array format
    $product_ids = [];

    if (isset($_POST['produk_id']) && is_array($_POST['produk_id'])) {
        $product_ids = $_POST['produk_id'];
    }

    error_log("Product IDs found: " . implode(', ', $product_ids));

    if (empty($product_ids)) {
        throw new Exception("No product IDs found in form data");
    }

    foreach ($product_ids as $product_id) {
        // Handle array format: rating[product_id] and isi_ulasan[product_id]
        $rating = null;
        $ulasan = null;

        if (isset($_POST['rating'][$product_id])) {
            $rating = intval($_POST['rating'][$product_id]);
        }

        if (isset($_POST['isi_ulasan'][$product_id])) {
            $ulasan = trim($_POST['isi_ulasan'][$product_id]);
        }

        error_log("Product $product_id: rating=$rating, ulasan=" . substr($ulasan, 0, 50) . "...");

        if ($rating === null || $ulasan === null) {
            error_log("Missing data for product $product_id");
            $error_messages[] = "Data tidak lengkap untuk produk ID $product_id";
            continue;
        }

        if ($rating < 1 || $rating > 5 || empty($ulasan)) {
            error_log("Invalid data for product $product_id: rating=$rating, ulasan empty=" . empty($ulasan));
            $error_messages[] = "Data tidak valid untuk produk ID $product_id";
            continue;
        }

        // Check if user has already reviewed this product
        $check_stmt = mysqli_prepare($conn, "SELECT COUNT(*) FROM ulasan_produk WHERE id_produk = ? AND id_pelanggan = ?");
        if (!$check_stmt) {
            error_log("Failed to prepare check statement: " . mysqli_error($conn));
            $error_messages[] = "Database error untuk produk ID $product_id";
            continue;
        }

        mysqli_stmt_bind_param($check_stmt, "ii", $product_id, $user_id);
        mysqli_stmt_execute($check_stmt);
        mysqli_stmt_bind_result($check_stmt, $count);
        mysqli_stmt_fetch($check_stmt);
        mysqli_stmt_close($check_stmt);

        if ($count > 0) {
            error_log("User $user_id already reviewed product $product_id");
            $error_messages[] = "Anda sudah memberikan ulasan untuk produk ID $product_id";
            continue;
        }

        // Insert the review - menggunakan column name yang benar dan set status pending
        $insert_stmt = mysqli_prepare($conn, "INSERT INTO ulasan_produk (id_produk, id_pelanggan, rating, isi_ulasan, tanggal_ulasan, status) VALUES (?, ?, ?, ?, NOW(), 'pending')");
        if (!$insert_stmt) {
            error_log("Failed to prepare insert statement: " . mysqli_error($conn));
            $error_messages[] = "Database error untuk produk ID $product_id";
            continue;
        }

        mysqli_stmt_bind_param($insert_stmt, "iiis", $product_id, $user_id, $rating, $ulasan);

        if (mysqli_stmt_execute($insert_stmt)) {
            $affected_rows = mysqli_stmt_affected_rows($insert_stmt);
            $success_count++;
            error_log("Review inserted successfully for product $product_id. Affected rows: $affected_rows");
        } else {
            $stmt_error = mysqli_stmt_error($insert_stmt);
            $conn_error = mysqli_error($conn);
            error_log("Failed to insert review for product $product_id. Statement error: $stmt_error. Connection error: $conn_error");
            $error_messages[] = "Gagal menyimpan ulasan untuk produk ID $product_id: $stmt_error";
        }
        mysqli_stmt_close($insert_stmt);
    }

    if ($success_count > 0) {
        mysqli_commit($conn);
        $message = "Berhasil menyimpan $success_count ulasan";
        if (!empty($error_messages)) {
            $message .= ". Ada beberapa error: " . implode(', ', $error_messages);
        }

        $response = ['success' => true, 'message' => $message, 'count' => $success_count];
        error_log("SUCCESS: " . $message);
    } else {
        mysqli_rollback($conn);
        $message = "Tidak ada ulasan yang berhasil disimpan";
        if (!empty($error_messages)) {
            $message .= ". Error: " . implode(', ', $error_messages);
        }

        $response = ['success' => false, 'message' => $message];
        error_log("FAILURE: " . $message);
    }
} catch (Exception $e) {
    mysqli_rollback($conn);
    $error_message = "Database error: " . $e->getMessage();
    error_log("EXCEPTION: " . $error_message);
    $response = ['success' => false, 'message' => $error_message];
}

// Restore autocommit
mysqli_autocommit($conn, true);

error_log("=== BULK REVIEW DEBUG END ===");

// Return response
if ($is_ajax) {
    echo json_encode($response);
} else {
    if ($response['success']) {
        $_SESSION['success_message'] = $response['message'];
    } else {
        $_SESSION['error_message'] = $response['message'];
    }
    header('Location: riwayat.php');
    exit;
}
?>
?>