<?php
include 'header.php'; // Includes user session, DB connection, and user data ($user, $user_id)

// --- VALIDATION ---
if (!isset($_GET['tour_id']) || !isset($_GET['booking_id'])) {
    header("Location: my-tour-bookings.php");
    exit();
}
$tour_id = intval($_GET['tour_id']);
$booking_id = intval($_GET['booking_id']);

// Security Check 1: Verify this booking belongs to the logged-in user and is 'Completed'
$stmt_check = $conn->prepare("SELECT id FROM bookings WHERE id = ? AND user_id = ? AND status = 'Completed'");
$stmt_check->bind_param("ii", $booking_id, $user_id);
$stmt_check->execute();
$check_result = $stmt_check->get_result();
if ($check_result->num_rows === 0) {
    header("Location: my-tour-bookings.php?error=invalid_review_attempt");
    exit();
}

// Security Check 2: See if a review for this specific booking already exists
$stmt_exists = $conn->prepare("SELECT id FROM reviews WHERE booking_id = ?");
$stmt_exists->bind_param("i", $booking_id);
$stmt_exists->execute();
if ($stmt_exists->get_result()->num_rows > 0) {
    header("Location: my-tour-bookings.php?error=already_reviewed");
    exit();
}

// Fetch tour name for display
$tour_name = $conn->query("SELECT title FROM tours WHERE id = $tour_id")->fetch_assoc()['title'];

$message = '';
// --- HANDLE FORM SUBMISSION ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $rating = intval($_POST['rating']);
    $review_text = trim($_POST['review_text']);
    // Check if the privacy checkbox was submitted. If it's not set, it means the user wants to be anonymous.
    $display_name_publicly = isset($_POST['display_name_publicly']) ? 1 : 0;

    // Insert the review, including the user's ID and their display name preference
    $stmt_insert = $conn->prepare("INSERT INTO reviews (user_id, item_id, item_type, booking_id, customer_name, review_text, rating, is_visible, is_verified, display_name_publicly) VALUES (?, ?, 'tour', ?, ?, ?, ?, 1, 1, ?)");
    $stmt_insert->bind_param("iisssii", $user_id, $tour_id, $booking_id, $user['full_name'], $review_text, $rating, $display_name_publicly);
    
    if ($stmt_insert->execute()) {
        header("Location: my-tour-bookings.php?review=success");
        exit();
    } else {
        $message = '<div class="alert alert-danger">There was an error submitting your review. Please try again.</div>';
    }
}
?>
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">Leave a Review</h1>
</div>

<div class="row justify-content-center">
    <div class="col-lg-8">
        <div class="card shadow-sm">
            <div class="card-header">
                Reviewing: <strong><?php echo htmlspecialchars($tour_name ?? 'Tour'); ?></strong>
            </div>
            <div class="card-body">
                <?php echo $message; ?>
                <form method="POST">
                    <div class="mb-3">
                        <label class="form-label">Your Rating</label>
                        <select name="rating" class="form-select" required>
                            <option value="5">⭐⭐⭐⭐⭐ (Excellent)</option>
                            <option value="4">⭐⭐⭐⭐ (Great)</option>
                            <option value="3">⭐⭐⭐ (Good)</option>
                            <option value="2">⭐⭐ (Fair)</option>
                            <option value="1">⭐ (Poor)</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Your Review</label>
                        <textarea name="review_text" class="form-control" rows="6" placeholder="Share your experience..." required></textarea>
                    </div>
                    
                    <div class="mb-3 form-check">
                        <input type="checkbox" class="form-check-input" id="displayNameCheck" name="display_name_publicly" value="1" checked>
                        <label class="form-check-label" for="displayNameCheck">Show my name (<?php echo htmlspecialchars($user['full_name']); ?>) publicly with this review.</label>
                    </div>

                    <button type="submit" class="btn btn-primary">Submit Review</button>
                    <a href="my-tour-bookings.php" class="btn btn-secondary">Cancel</a>
                </form>
            </div>
        </div>
    </div>
</div>

<?php include 'footer.php'; ?>
