<?php
require_once 'config.php';

$message = '';
$messageType = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name        = trim($_POST['name'] ?? '');
    $email       = trim($_POST['email'] ?? '');
    $rating      = intval($_POST['rating'] ?? 0);
    $description = trim($_POST['description'] ?? '');
    $ip          = $_SERVER['REMOTE_ADDR'] ?? null;

    // Validation
    $errors = [];

    if (empty($name) || strlen($name) < 2) {
        $errors[] = "Please enter a valid name (min 2 characters).";
    }

    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Please enter a valid email address.";
    }

    if ($rating < 1 || $rating > 5) {
        $errors[] = "Please select a rating between 1 and 5 stars.";
    }

    if (empty($description) || strlen($description) < 5) {
        $errors[] = "Please write a review (min 5 characters).";
    }

    if (empty($errors)) {
        // Use prepared statement to prevent SQL injection
        $stmt = $conn->prepare("INSERT INTO reviews (name, email, rating, description, ip_address) VALUES (?, ?, ?, ?, ?)");
        $stmt->bind_param("ssiss", $name, $email, $rating, $description, $ip);

        if ($stmt->execute()) {
            $message = "Thank you! Your review has been submitted successfully.";
            $messageType = "success";
        } else {
            $message = "Error: Could not save your review. Please try again.";
            $messageType = "error";
        }
        $stmt->close();
    } else {
        $message = implode("<br>", $errors);
        $messageType = "error";
    }
}

// Fetch latest reviews
$reviews = [];
$result = $conn->query("SELECT name, rating, description, created_at FROM reviews ORDER BY created_at DESC LIMIT 20");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $reviews[] = $row;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Leave a Review</title>
<style>
    * { box-sizing: border-box; margin: 0; padding: 0; }
    body {
        font-family: 'Segoe UI', Tahoma, sans-serif;
        background: linear-gradient(135deg, #667eea, #764ba2);
        min-height: 100vh;
        padding: 30px 15px;
    }
    .container {
        max-width: 700px;
        margin: 0 auto;
    }
    .card {
        background: #fff;
        border-radius: 12px;
        padding: 30px;
        box-shadow: 0 10px 40px rgba(0,0,0,0.2);
        margin-bottom: 25px;
    }
    h1 {
        text-align: center;
        color: #333;
        margin-bottom: 25px;
        font-size: 26px;
    }
    .form-group {
        margin-bottom: 18px;
    }
    label {
        display: block;
        margin-bottom: 6px;
        font-weight: 600;
        color: #444;
        font-size: 14px;
    }
    input[type="text"],
    input[type="email"],
    textarea {
        width: 100%;
        padding: 11px 14px;
        border: 2px solid #e0e0e0;
        border-radius: 8px;
        font-size: 15px;
        transition: border 0.3s;
        font-family: inherit;
    }
    input:focus, textarea:focus {
        border-color: #667eea;
        outline: none;
    }
    textarea {
        resize: vertical;
        min-height: 100px;
    }
    /* Star Rating */
    .star-rating {
        display: flex;
        flex-direction: row-reverse;
        justify-content: flex-end;
        gap: 5px;
    }
    .star-rating input { display: none; }
    .star-rating label {
        font-size: 38px;
        color: #ddd;
        cursor: pointer;
        transition: color 0.2s, transform 0.2s;
        margin: 0;
        line-height: 1;
    }
    .star-rating label:hover,
    .star-rating label:hover ~ label,
    .star-rating input:checked ~ label {
        color: #ffc107;
    }
    .star-rating label:hover { transform: scale(1.1); }
    button {
        width: 100%;
        padding: 14px;
        background: linear-gradient(135deg, #667eea, #764ba2);
        color: #fff;
        border: none;
        border-radius: 8px;
        font-size: 16px;
        font-weight: 600;
        cursor: pointer;
        transition: transform 0.2s, opacity 0.2s;
    }
    button:hover { transform: translateY(-2px); opacity: 0.95; }
    .alert {
        padding: 12px 16px;
        border-radius: 8px;
        margin-bottom: 20px;
        font-size: 14px;
    }
    .alert.success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
    .alert.error   { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
    /* Reviews List */
    .reviews-list h2 {
        color: #fff;
        margin-bottom: 18px;
        text-align: center;
    }
    .review-item {
        background: #fff;
        border-radius: 10px;
        padding: 18px;
        margin-bottom: 14px;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    }
    .review-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;
        flex-wrap: wrap;
        gap: 8px;
    }
    .review-name { font-weight: 700; color: #333; }
    .review-stars { color: #ffc107; font-size: 18px; }
    .review-stars .empty { color: #ddd; }
    .review-date { font-size: 12px; color: #888; }
    .review-desc { color: #555; font-size: 14px; line-height: 1.5; }
    .no-reviews { color: #fff; text-align: center; font-style: italic; }
</style>
</head>
<body>
<div class="container">

    <!-- Review Form -->
    <div class="card">
        <h1>⭐ Leave a Review</h1>

        <?php if ($message): ?>
            <div class="alert <?= $messageType ?>"><?= $message ?></div>
        <?php endif; ?>

        <form method="POST" action="">
            <div class="form-group">
                <label for="name">Your Name *</label>
                <input type="text" id="name" name="name" placeholder="John Doe" required
                       value="<?= htmlspecialchars($_POST['name'] ?? '') ?>">
            </div>

            <div class="form-group">
                <label for="email">Your Email *</label>
                <input type="email" id="email" name="email" placeholder="john@example.com" required
                       value="<?= htmlspecialchars($_POST['email'] ?? '') ?>">
            </div>

            <div class="form-group">
                <label>Your Rating *</label>
                <div class="star-rating">
                    <input type="radio" id="star5" name="rating" value="5" <?= (($_POST['rating'] ?? '') == 5) ? 'checked' : '' ?>>
                    <label for="star5" title="5 stars">★</label>
                    <input type="radio" id="star4" name="rating" value="4" <?= (($_POST['rating'] ?? '') == 4) ? 'checked' : '' ?>>
                    <label for="star4" title="4 stars">★</label>
                    <input type="radio" id="star3" name="rating" value="3" <?= (($_POST['rating'] ?? '') == 3) ? 'checked' : '' ?>>
                    <label for="star3" title="3 stars">★</label>
                    <input type="radio" id="star2" name="rating" value="2" <?= (($_POST['rating'] ?? '') == 2) ? 'checked' : '' ?>>
                    <label for="star2" title="2 stars">★</label>
                    <input type="radio" id="star1" name="rating" value="1" <?= (($_POST['rating'] ?? '') == 1) ? 'checked' : '' ?>>
                    <label for="star1" title="1 star">★</label>
                </div>
            </div>

            <div class="form-group">
                <label for="description">Your Review *</label>
                <textarea id="description" name="description" placeholder="Tell us about your experience..." required><?= htmlspecialchars($_POST['description'] ?? '') ?></textarea>
            </div>

            <button type="submit">Submit Review</button>
        </form>
    </div>

    <!-- Reviews List -->
    <div class="reviews-list">
        <h2>Recent Reviews</h2>

        <?php if (empty($reviews)): ?>
            <p class="no-reviews">No reviews yet. Be the first to leave one!</p>
        <?php else: ?>
            <?php foreach ($reviews as $r): ?>
                <div class="review-item">
                    <div class="review-header">
                        <span class="review-name"><?= htmlspecialchars($r['name']) ?></span>
                        <span class="review-stars">
                            <?php
                            for ($i = 1; $i <= 5; $i++) {
                                echo $i <= $r['rating']
                                    ? '<span>★</span>'
                                    : '<span class="empty">★</span>';
                            }
                            ?>
                        </span>
                    </div>
                    <div class="review-date"><?= date('M d, Y H:i', strtotime($r['created_at'])) ?></div>
                    <p class="review-desc"><?= nl2br(htmlspecialchars($r['description'])) ?></p>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>

</div>
</body>
</html>
<?php $conn->close(); ?>