<?php
// --- LOGIC BLOCK: All processing happens before any HTML output ---
require_once '../includes/db.php';

// Check for admin login session at the very beginning
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: ../login.php");
    exit;
}

$message = '';
// --- HANDLE FORM SUBMISSIONS (ADD, EDIT, DELETE) ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // --- DELETE REVIEW ---
    if (isset($_POST['delete_review'])) {
        $id = intval($_POST['id']);
        $stmt = $conn->prepare("DELETE FROM reviews WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        // Set session flash message for display after redirect
        $_SESSION['flash_message'] = '<div class="alert alert-success">Review deleted successfully.</div>';
        header("Location: manage-reviews.php"); 
        exit;
    }

    // --- ADD or EDIT REVIEW ---
    if (isset($_POST['save_review'])) {
        $id = intval($_POST['id'] ?? 0);
        $customer_name = trim($_POST['customer_name']);
        $review_text = trim($_POST['review_text']);
        $rating = intval($_POST['rating']);
        $item_id = intval($_POST['item_id']);
        $is_visible = isset($_POST['is_visible']) ? 1 : 0;
        $is_verified = isset($_POST['is_verified']) ? 1 : 0;
        $display_name_publicly = isset($_POST['display_name_publicly']) ? 1 : 0;

        if ($id > 0) { // Update
            $stmt = $conn->prepare("UPDATE reviews SET customer_name=?, review_text=?, rating=?, is_visible=?, is_verified=?, item_id=?, display_name_publicly=? WHERE id=?");
            $stmt->bind_param("ssiiiiii", $customer_name, $review_text, $rating, $is_visible, $is_verified, $item_id, $display_name_publicly, $id);
            $_SESSION['flash_message'] = '<div class="alert alert-success">Review updated successfully.</div>';
        } else { // Insert
            $stmt = $conn->prepare("INSERT INTO reviews (customer_name, review_text, rating, is_visible, is_verified, item_id, item_type, display_name_publicly) VALUES (?, ?, ?, ?, ?, ?, 'tour', ?)");
            $stmt->bind_param("ssiiiii", $customer_name, $review_text, $rating, $is_visible, $is_verified, $item_id, $display_name_publicly);
            $_SESSION['flash_message'] = '<div class="alert alert-success">New review added successfully.</div>';
        }
        $stmt->execute();
        header("Location: manage-reviews.php"); 
        exit;
    }
}

// Check for a flash message from a redirect
if(isset($_SESSION['flash_message'])) {
    $message = $_SESSION['flash_message'];
    unset($_SESSION['flash_message']);
}

// Fetch a single review for editing if an ID is in the URL
$edit_review = null;
if (isset($_GET['edit'])) {
    $id = intval($_GET['edit']);
    $stmt = $conn->prepare("SELECT * FROM reviews WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $edit_review = $stmt->get_result()->fetch_assoc();
}

// --- PRESENTATION BLOCK: Now we include the header and display the page ---
include 'admin-header.php';
?>

<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">Manage Customer Reviews</h1>
</div>
<?php echo $message; ?>

<div class="card shadow-sm mb-4">
    <div class="card-header fw-bold"><?php echo $edit_review ? 'Edit Review' : 'Add New Review'; ?></div>
    <div class="card-body">
        <form method="POST" action="manage-reviews.php">
            <input type="hidden" name="id" value="<?php echo $edit_review['id'] ?? 0; ?>">
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label">Review For (Tour)</label>
                    <select name="item_id" class="form-select" required>
                        <option value="">-- Select a Tour --</option>
                        <?php 
                        $tours_result = $conn->query("SELECT id, title FROM tours ORDER BY title");
                        while($tour = $tours_result->fetch_assoc()): ?>
                        <option value="<?php echo $tour['id']; ?>" <?php if(isset($edit_review['item_id']) && $edit_review['item_id'] == $tour['id']) echo 'selected'; ?>>
                            <?php echo htmlspecialchars($tour['title']); ?>
                        </option>
                        <?php endwhile; ?>
                    </select>
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">Customer Name</label>
                    <input type="text" class="form-control" name="customer_name" value="<?php echo htmlspecialchars($edit_review['customer_name'] ?? ''); ?>" required>
                </div>
            </div>
            <div class="mb-3">
                <label class="form-label">Review Text</label>
                <textarea class="form-control" name="review_text" rows="4" required><?php echo htmlspecialchars($edit_review['review_text'] ?? ''); ?></textarea>
            </div>
            <div class="mb-3">
                <label class="form-label">Rating (1-5)</label>
                <select name="rating" class="form-select" required>
                    <option value="5" <?php if(isset($edit_review['rating']) && $edit_review['rating'] == 5) echo 'selected'; ?>>5 Stars (Excellent)</option>
                    <option value="4" <?php if(isset($edit_review['rating']) && $edit_review['rating'] == 4) echo 'selected'; ?>>4 Stars (Great)</option>
                    <option value="3" <?php if(isset($edit_review['rating']) && $edit_review['rating'] == 3) echo 'selected'; ?>>3 Stars (Good)</option>
                    <option value="2" <?php if(isset($edit_review['rating']) && $edit_review['rating'] == 2) echo 'selected'; ?>>2 Stars (Fair)</option>
                    <option value="1" <?php if(isset($edit_review['rating']) && $edit_review['rating'] == 1) echo 'selected'; ?>>1 Star (Poor)</option>
                </select>
            </div>
            <div class="d-flex flex-wrap gap-4 mb-3">
                <div class="form-check form-switch">
                    <input type="checkbox" class="form-check-input" id="is_visible" name="is_visible" value="1" <?php echo (isset($edit_review['is_visible']) && $edit_review['is_visible']) || !$edit_review ? 'checked' : ''; ?>>
                    <label class="form-check-label" for="is_visible">Visible on website</label>
                </div>
                <div class="form-check form-switch">
                    <input type="checkbox" class="form-check-input" id="is_verified" name="is_verified" value="1" <?php echo (isset($edit_review['is_verified']) && $edit_review['is_verified']) ? 'checked' : ''; ?>>
                    <label class="form-check-label" for="is_verified">Verified Purchase</label>
                </div>
                <div class="form-check form-switch">
                    <input type="checkbox" class="form-check-input" id="display_name_publicly" name="display_name_publicly" value="1" <?php echo (isset($edit_review['display_name_publicly']) && $edit_review['display_name_publicly']) || !$edit_review ? 'checked' : ''; ?>>
                    <label class="form-check-label" for="display_name_publicly">Display Name Publicly</label>
                </div>
            </div>
            
            <button type="submit" name="save_review" class="btn btn-primary"><?php echo $edit_review ? 'Update Review' : 'Add Review'; ?></button>
            <?php if ($edit_review): ?><a href="manage-reviews.php" class="btn btn-secondary">Cancel</a><?php endif; ?>
        </form>
    </div>
</div>

<div class="card shadow-sm mt-4">
    <div class="card-header fw-bold">Existing Reviews</div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-striped table-hover align-middle">
                <thead class="table-dark"><tr><th>Customer</th><th>Review For</th><th>Rating</th><th>Status</th><th>Actions</th></tr></thead>
                <tbody>
                <?php
                $result = $conn->query("SELECT r.*, t.title as tour_title FROM reviews r LEFT JOIN tours t ON r.item_id = t.id AND r.item_type='tour' ORDER BY r.id DESC");
                while($row = $result->fetch_assoc()):
                ?>
                <tr>
                    <td><?php echo htmlspecialchars($row['customer_name']); ?><?php if(!$row['display_name_publicly']) echo ' <span class="badge bg-secondary">Anonymous</span>'; ?></td>
                    <td><?php echo htmlspecialchars($row['tour_title'] ?? 'N/A'); ?></td>
                    <td><?php echo str_repeat('⭐', $row['rating']); ?></td>
                    <td>
                        <?php echo $row['is_visible'] ? '<span class="badge bg-success">Visible</span>' : '<span class="badge bg-secondary">Hidden</span>'; ?>
                        <?php echo $row['is_verified'] ? '<span class="badge bg-primary">Verified</span>' : '<span class="badge bg-light text-dark">Not Verified</span>'; ?>
                    </td>
                    <td>
                        <a href="?edit=<?php echo $row['id']; ?>" class="btn btn-sm btn-outline-primary">Edit</a>
                        <form method="POST" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this review?');">
                            <input type="hidden" name="id" value="<?php echo $row['id']; ?>">
                            <button type="submit" name="delete_review" class="btn btn-sm btn-outline-danger">Delete</button>
                        </form>
                    </td>
                </tr>
                <?php endwhile; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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