<?php
// --- LOGIC BLOCK: All PHP processing and security checks ---
require_once 'dashboard-logic.php';
require_once '../includes/helpers.php'; 

// --- SECURITY & VALIDATION ---
$item_id = intval($_GET['item_id'] ?? 0);
$item_type = filter_var($_GET['item_type'] ?? 'tour', FILTER_SANITIZE_STRING);
$booking_id = intval($_GET['booking_id'] ?? 0);

if ($item_id <= 0 || $booking_id <= 0 || !in_array($item_type, ['tour', 'hotel'])) {
    // Redirect if URL parameters are invalid
    header("Location: index.php");
    exit();
}

// 1. Check if this booking actually belongs to the logged-in user and is marked as 'Completed'.
// This is the primary security check.
$booking_check_sql = "";
if ($item_type == 'tour') {
    $booking_check_sql = "SELECT id FROM bookings WHERE id = ? AND user_id = ? AND status = 'Completed'";
} elseif ($item_type == 'hotel') {
    $booking_check_sql = "SELECT id FROM hotel_bookings WHERE id = ? AND user_id = ? AND status = 'Completed'";
}

if (!empty($booking_check_sql)) {
    $stmt_check = $conn->prepare($booking_check_sql);
    $stmt_check->bind_param("ii", $booking_id, $user_id);
    $stmt_check->execute();
    $check_result = $stmt_check->get_result();
    if ($check_result->num_rows === 0) {
        // If no match, the booking is not theirs or not completed. Redirect them.
        header("Location: my-" . $item_type . "-bookings.php?error=invalid_review_attempt");
        exit();
    }
}

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

// --- ALL CHECKS PASSED, PROCEED WITH PAGE LOGIC ---

// Fetch item name for display
$item_name = 'Item';
if ($item_type == 'tour') {
    $item_name = $conn->query("SELECT title FROM tours WHERE id = $item_id")->fetch_assoc()['title'] ?? 'Tour';
} elseif ($item_type == 'hotel') {
    $item_name = $conn->query("SELECT name FROM hotels WHERE id = $item_id")->fetch_assoc()['name'] ?? 'Hotel';
}

$message = '';
// Handle Review Form Submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit_review'])) {
    $rating = intval($_POST['rating']);
    $review_text = trim(strip_tags($_POST['review_text']));
    $display_name_publicly = isset($_POST['display_name_publicly']) ? 1 : 0;

    if (!empty($review_text)) {
        // Find the partner who owns this item to trigger a rating update
        $partner_id = null;
        if ($item_type == 'tour') {
            $partner_id_res = $conn->query("SELECT partner_id FROM tours WHERE id = $item_id")->fetch_assoc();
        } elseif ($item_type == 'hotel') {
            $partner_id_res = $conn->query("SELECT partner_id FROM hotels WHERE id = $item_id")->fetch_assoc();
        }
        if ($partner_id_res && !empty($partner_id_res['partner_id'])) {
            $partner_id = $partner_id_res['partner_id'];
        }

        // Insert the review
        $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 (?, ?, ?, ?, ?, ?, ?, 1, 1, ?)");
        $stmt_insert->bind_param("iisssii", $user_id, $item_id, $item_type, $booking_id, $user['full_name'], $review_text, $rating, $display_name_publicly);
        
        if ($stmt_insert->execute()) {
            if ($partner_id) { update_partner_rating($conn, $partner_id); }
            header("Location: my-" . $item_type . "-bookings.php?review=success");
            exit();
        } else {
            $message = '<div class="alert alert-danger">Error submitting review. Please try again.</div>';
        }
    }
}

// --- PRESENTATION BLOCK ---
?>
<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($item_name); ?></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 publicly with this review.</label></div>
                    <button type="submit" name="submit_review" class="btn btn-primary">Submit Review</button>
                    <a href="my-<?php echo $item_type; ?>-bookings.php" class="btn btn-secondary">Cancel</a>
                </form>
            </div>
        </div>
    </div>
</div>
<?php include 'footer.php'; ?>
