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

if (!isset($_SESSION['user_id']) || !isset($_GET['transaksi_id'])) {
    exit('Unauthorized');
}

$user_id = $_SESSION['user_id'];
$transaksi_id = (int)$_GET['transaksi_id'];

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

if (!$transaksi) {
    exit('Transaction not found or not completed');
}

// Get unique products from this transaction (group by product_id to avoid duplicates)
$products_query = "
    SELECT td.produk_id, p.nama, p.gambar, 
           GROUP_CONCAT(DISTINCT up.ukuran ORDER BY up.ukuran ASC) as ukuran_list,
           SUM(td.jumlah) as total_qty,
           ul.id as review_id, ul.rating, ul.isi_ulasan
    FROM transaksi_detail td
    JOIN produk p ON td.produk_id = p.id
    JOIN ukuran_produk up ON td.ukuran_id = up.id
    LEFT JOIN ulasan_produk ul ON ul.produk_id = td.produk_id 
                                  AND ul.transaksi_id = td.transaksi_id 
                                  AND ul.pengguna_id = ?
    WHERE td.transaksi_id = ?
    GROUP BY td.produk_id, p.nama, p.gambar, ul.id, ul.rating, ul.isi_ulasan
";
$stmt = $conn->prepare($products_query);
$stmt->bind_param("ii", $user_id, $transaksi_id);
$stmt->execute();
$products = $stmt->get_result();

$products_array = [];
$has_unreviewed = false;
while ($product = $products->fetch_assoc()) {
    $products_array[] = $product;
    if (!$product['review_id']) {
        $has_unreviewed = true;
    }
}
?>

<style>
    .product-card {
        border: 1px solid #ddd;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 15px;
        background: #f8f9fa;
    }

    .product-info {
        display: flex;
        align-items: center;
        margin-bottom: 1rem;
    }

    .product-image {
        width: 60px;
        height: 60px;
        object-fit: cover;
        border-radius: 6px;
        margin-right: 1rem;
    }

    .star-rating {
        display: flex;
        gap: 5px;
        margin-bottom: 10px;
    }

    .star-rating input {
        display: none;
    }

    .star-rating label {
        font-size: 1.5rem;
        color: #ddd;
        cursor: pointer;
        transition: color 0.2s;
    }

    .star-rating input:checked~label,
    .star-rating label:hover,
    .star-rating label:hover~label {
        color: #ffc107;
    }

    .star-rating input:checked~label {
        color: #ffc107;
    }

    .review-submitted {
        background: #d4edda;
        border-color: #c3e6cb;
        color: #155724;
    }

    .review-form-container {
        background: white;
        border-radius: 8px;
        padding: 20px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }
</style>

<div class="review-container">
    <h6 class="mb-3">
        <i class="fas fa-star text-warning"></i>
        Ulasan untuk Transaksi #TRX-<?= date('Ymd', strtotime($transaksi['dibuat_pada'])) ?>-<?= str_pad($transaksi['id'], 4, '0', STR_PAD_LEFT) ?>
    </h6>

    <!-- Display Products -->
    <div class="mb-3">
        <?php foreach ($products_array as $product): ?>
            <div class="product-card <?= $product['review_id'] ? 'review-submitted' : '' ?>">
                <div class="product-info">
                    <img src="../upload/<?= htmlspecialchars($product['gambar']) ?>"
                        alt="<?= htmlspecialchars($product['nama']) ?>"
                        class="product-image">
                    <div>
                        <h6 class="mb-1"><?= htmlspecialchars($product['nama']) ?></h6>
                        <small class="text-muted">
                            Ukuran: <?= htmlspecialchars($product['ukuran_list']) ?> |
                            Total: <?= $product['total_qty'] ?> pcs
                        </small>

                        <?php if ($product['review_id']): ?>
                            <div class="mt-2">
                                <span class="badge bg-success">✓ Sudah diulas</span>
                                <div class="mt-1">
                                    <strong>Rating:</strong>
                                    <?php for ($i = 1; $i <= 5; $i++): ?>
                                        <span class="<?= $i <= $product['rating'] ? 'text-warning' : 'text-muted' ?>">★</span>
                                    <?php endfor; ?>
                                </div>
                                <div class="mt-1">
                                    <strong>Ulasan:</strong> "<?= htmlspecialchars($product['isi_ulasan']) ?>"
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>

    <?php if ($has_unreviewed): ?>
        <!-- Review Form for Unreviewed Products -->
        <div class="review-form-container">
            <h6 class="mb-3"><i class="fas fa-edit"></i> Berikan Ulasan</h6>
            <form id="transactionReviewForm">
                <input type="hidden" name="transaksi_id" value="<?= $transaksi_id ?>">
                <input type="hidden" name="user_id" value="<?= $user_id ?>">

                <?php foreach ($products_array as $index => $product): ?>
                    <?php if (!$product['review_id']): ?>
                        <div class="product-review-section mb-4 border-bottom pb-3">
                            <input type="hidden" name="produk_id[]" value="<?= $product['produk_id'] ?>">

                            <div class="product-info mb-3">
                                <img src="../upload/<?= htmlspecialchars($product['gambar']) ?>"
                                    alt="<?= htmlspecialchars($product['nama']) ?>"
                                    class="product-image">
                                <div>
                                    <h6 class="mb-1"><?= htmlspecialchars($product['nama']) ?></h6>
                                    <small class="text-muted">
                                        Ukuran: <?= htmlspecialchars($product['ukuran_list']) ?> |
                                        Total: <?= $product['total_qty'] ?> pcs
                                    </small>
                                </div>
                            </div>

                            <div class="mb-3">
                                <label class="form-label"><strong>Rating untuk <?= htmlspecialchars($product['nama']) ?></strong></label>
                                <div class="star-rating">
                                    <?php for ($i = 5; $i >= 1; $i--): ?>
                                        <input type="radio"
                                            id="star<?= $i ?>_<?= $product['produk_id'] ?>"
                                            name="rating[<?= $product['produk_id'] ?>]"
                                            value="<?= $i ?>"
                                            required />
                                        <label for="star<?= $i ?>_<?= $product['produk_id'] ?>"
                                            title="<?= $i ?> bintang">★</label>
                                    <?php endfor; ?>
                                </div>
                            </div>

                            <div class="mb-3">
                                <label class="form-label"><strong>Ulasan untuk <?= htmlspecialchars($product['nama']) ?></strong></label>
                                <textarea class="form-control"
                                    name="isi_ulasan[<?= $product['produk_id'] ?>]"
                                    rows="3"
                                    maxlength="500"
                                    required
                                    placeholder="Bagikan pengalaman Anda dengan produk ini..."></textarea>
                                <div class="form-text">Maksimal 500 karakter.</div>
                            </div>
                        </div>
                    <?php endif; ?>
                <?php endforeach; ?>

                <div class="text-end">
                    <button type="button" class="btn btn-secondary me-2" data-bs-dismiss="modal">
                        <i class="fas fa-times"></i> Batal
                    </button>
                    <button type="button" class="btn btn-primary" id="submitReviewBtn" onclick="submitBulkReview()">
                        <i class="fas fa-paper-plane"></i> Kirim Semua Ulasan
                    </button>
                </div>
            </form>
        </div>
    <?php else: ?>
        <div class="alert alert-info">
            <i class="fas fa-check-circle"></i>
            Semua produk dalam transaksi ini sudah memiliki ulasan. Terima kasih!
        </div>
    <?php endif; ?>
</div>

<script>
    function submitBulkReview() {
        console.log('submitBulkReview function called');

        const form = document.getElementById('transactionReviewForm');
        if (!form) {
            console.error('Form not found');
            alert('Form tidak ditemukan. Silakan refresh halaman.');
            return;
        }

        console.log('Form found, processing submission');

        // Validate required fields
        const ratings = form.querySelectorAll('input[type="radio"]:checked');
        const textareas = form.querySelectorAll('textarea[required]');
        let isValid = true;

        // Check if all required ratings are selected
        const ratingGroups = form.querySelectorAll('input[type="radio"][required]');
        const uniqueGroups = new Set();
        ratingGroups.forEach(input => uniqueGroups.add(input.name));

        if (ratings.length < uniqueGroups.size) {
            alert('Harap berikan rating untuk semua produk.');
            return;
        }

        // Check if all textareas are filled
        textareas.forEach(textarea => {
            if (!textarea.value.trim()) {
                isValid = false;
            }
        });

        if (!isValid) {
            alert('Harap isi semua field ulasan.');
            return;
        }

        const submitBtn = document.getElementById('submitReviewBtn');
        const originalText = submitBtn.innerHTML;

        // Show loading state
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Mengirim...';
        submitBtn.disabled = true;

        // Create FormData
        const formData = new FormData(form);

        // Debug: Log form data
        console.log('Form data being sent:');
        for (let pair of formData.entries()) {
            console.log(pair[0] + ': ' + pair[1]);
        }

        // Send to processing script
        fetch('../proses/proses_tambah_ulasan_bulk.php', {
                method: 'POST',
                credentials: 'include',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: formData
            })
            .then(response => {
                console.log('Response status:', response.status);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                console.log('Response data:', data);

                // Reset button
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;

                if (data.success) {
                    alert('Semua ulasan berhasil dikirim! Terima kasih atas feedback Anda.');

                    // Close modal
                    const modal = bootstrap.Modal.getInstance(document.querySelector('#reviewModal'));
                    if (modal) {
                        modal.hide();
                    }

                    // Refresh the page to update review status
                    setTimeout(() => {
                        window.location.reload();
                    }, 1000);

                } else {
                    alert('Error: ' + (data.message || 'Gagal mengirim ulasan. Silakan coba lagi.'));
                }
            })
            .catch(error => {
                console.error('Fetch error:', error);

                // Reset button
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;

                alert('Terjadi kesalahan saat mengirim ulasan: ' + error.message);
            });
    }
</script>