<?php
include 'auth.php';
require_once '../config/db.php';

// Self-heal
$conn->query("CREATE TABLE IF NOT EXISTS `google_reviews` (
    `id` INT AUTO_INCREMENT PRIMARY KEY,
    `reviewer_name` VARCHAR(200) NOT NULL,
    `reviewer_photo` VARCHAR(500) DEFAULT NULL,
    `rating` TINYINT(1) DEFAULT 5,
    `review_text` TEXT NOT NULL,
    `review_date` VARCHAR(100) DEFAULT NULL,
    `is_active` TINYINT(1) DEFAULT 1,
    `sort_order` INT DEFAULT 0,
    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

$error = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $reviewer_name = sanitize($conn, $_POST['reviewer_name']);
    $review_text   = sanitize($conn, $_POST['review_text']);
    $rating        = max(1, min(5, (int)$_POST['rating']));
    $review_date   = sanitize($conn, $_POST['review_date']);
    $is_active     = isset($_POST['is_active']) ? 1 : 0;
    $sort_order    = (int)$_POST['sort_order'];

    if (empty($reviewer_name) || empty($review_text)) {
        $error = "Reviewer name and review text are required.";
    } else {
        // Handle photo upload
        $reviewer_photo = '';
        if (!empty($_FILES['reviewer_photo']['name'])) {
            $ext = strtolower(pathinfo($_FILES['reviewer_photo']['name'], PATHINFO_EXTENSION));
            $allowed = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
            if (in_array($ext, $allowed)) {
                $reviewer_photo = 'grev_' . time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '', $_FILES['reviewer_photo']['name']);
                move_uploaded_file($_FILES['reviewer_photo']['tmp_name'], "../uploads/" . $reviewer_photo);
            }
        }

        $photo_val = $reviewer_photo ? "'$reviewer_photo'" : "NULL";
        $sql = "INSERT INTO google_reviews (reviewer_name, reviewer_photo, rating, review_text, review_date, is_active, sort_order)
                VALUES ('$reviewer_name', $photo_val, $rating, '$review_text', '$review_date', $is_active, $sort_order)";

        if ($conn->query($sql)) {
            $_SESSION['success_msg'] = "Google review added successfully!";
            header("Location: google-reviews.php");
            exit();
        } else {
            $error = "Database error: " . $conn->error;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Google Review | Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700;800&display=swap" rel="stylesheet">
    <style>
        * { font-family: 'Inter', sans-serif; }
        body { background: #f0f2f5; margin: 0; }
        .admin-sidebar { position: fixed; top: 0; left: 0; width: 260px; height: 100vh; background: linear-gradient(180deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%); z-index: 100; padding: 30px 0; display: flex; flex-direction: column; box-shadow: 4px 0 20px rgba(0,0,0,0.3); }
        .sidebar-logo { text-align: center; padding: 0 20px 30px; border-bottom: 1px solid rgba(255,255,255,0.1); margin-bottom: 20px; }
        .sidebar-logo img { height: 70px; filter: brightness(0) invert(1); }
        .sidebar-logo h6 { color: #aaa; font-size: 11px; text-transform: uppercase; letter-spacing: 3px; margin-top: 8px; }
        .sidebar-nav a { display: flex; align-items: center; padding: 12px 25px; color: rgba(255,255,255,0.65); text-decoration: none; font-size: 14px; font-weight: 500; transition: 0.3s; gap: 12px; border-left: 3px solid transparent; }
        .sidebar-nav a:hover, .sidebar-nav a.active { color: #fff; background: rgba(255,255,255,0.08); border-left-color: #ff6900; }
        .sidebar-nav a i { width: 20px; text-align: center; font-size: 15px; }
        .sidebar-section { padding: 15px 25px 5px; color: rgba(255,255,255,0.3); font-size: 10px; text-transform: uppercase; letter-spacing: 2px; }
        .sidebar-bottom { margin-top: auto; padding: 20px 25px; border-top: 1px solid rgba(255,255,255,0.1); }
        .sidebar-bottom a { display: flex; align-items: center; gap: 10px; color: rgba(255,255,255,0.6); text-decoration: none; font-size: 14px; padding: 10px; border-radius: 10px; transition: 0.3s; }
        .sidebar-bottom a:hover { color: #fff; background: rgba(255,0,0,0.2); }
        .admin-main { margin-left: 260px; min-height: 100vh; padding: 30px; }
        .admin-topbar { display: flex; justify-content: space-between; align-items: center; background: #fff; border-radius: 16px; padding: 15px 25px; margin-bottom: 30px; box-shadow: 0 2px 20px rgba(0,0,0,0.06); }
        .form-section { background: #fff; border-radius: 20px; box-shadow: 0 4px 20px rgba(0,0,0,0.06); padding: 35px; margin-bottom: 24px; }
        .form-section h6 { font-size: 13px; font-weight: 700; text-transform: uppercase; letter-spacing: 1.5px; color: #4285F4; margin-bottom: 20px; padding-bottom: 10px; border-bottom: 2px solid #e8f0fe; }
        .form-label { font-weight: 600; font-size: 13px; color: #444; margin-bottom: 6px; }
        .form-control, .form-select { border-radius: 12px; padding: 12px 16px; border: 1.5px solid #e8e8e8; font-size: 14px; transition: 0.2s; }
        .form-control:focus, .form-select:focus { border-color: #4285F4; box-shadow: 0 0 0 3px rgba(66,133,244,0.1); outline: none; }
        /* Star rating */
        .star-picker { display: flex; gap: 8px; }
        .star-picker span { font-size: 32px; cursor: pointer; color: #ddd; transition: 0.15s; line-height: 1; }
        .star-picker span.active { color: #ffc107; }
        .star-picker span:hover { transform: scale(1.15); }
        /* Preview card */
        .review-preview-card { background: #fff; border: 1.5px solid #e8e8e8; border-radius: 16px; padding: 20px; box-shadow: 0 2px 12px rgba(0,0,0,0.06); }
        .preview-avatar { width: 44px; height: 44px; border-radius: 50%; background: linear-gradient(135deg, #4285F4, #34A853); color: #fff; display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: 18px; }
        .preview-avatar img { width: 44px; height: 44px; border-radius: 50%; object-fit: cover; }
        .google-logo { display: inline-flex; align-items: center; gap: 4px; }
        .google-logo span { font-family: 'Product Sans', 'Inter', sans-serif; font-size: 13px; font-weight: 700; }
        .g-blue { color: #4285F4; }
        .g-red { color: #EA4335; }
        .g-yellow { color: #FBBC05; }
        .g-green { color: #34A853; }
    </style>
</head>
<body>

<div class="admin-sidebar">
    <div class="sidebar-logo">
        <img src="../assets/img/logo.png" alt="Logo" onerror="this.style.display='none'">
        <h6>Admin Panel</h6>
    </div>
    <div class="sidebar-nav">
        <a href="index.php"><i class="fas fa-home"></i> Dashboard</a>
        <div class="sidebar-section" style="padding-top:20px;">Tour Management</div>
        <a href="packages.php"><i class="fas fa-globe"></i> International Tours</a>
        <a href="add-package.php"><i class="fas fa-plus-circle"></i> Add Tour</a>
        <a href="local-tours.php"><i class="fas fa-map-marked-alt"></i> Local Tours</a>
        <a href="add-local-tour.php"><i class="fas fa-plus"></i> Add Local Tour</a>
        <a href="categories.php"><i class="fas fa-tags"></i> Categories</a>
        <div class="sidebar-section" style="padding-top:20px;">Homepage</div>
        <a href="destinations.php"><i class="fas fa-map-pin"></i> Destinations</a>
        <a href="add-destination.php"><i class="fas fa-plus-circle"></i> Add Destination</a>
        <a href="testimonials.php"><i class="fas fa-star"></i> Testimonials</a>
        <a href="add-testimonial.php"><i class="fas fa-plus-circle"></i> Add Testimonial</a>
        <a href="google-reviews.php" class="active"><i class="fab fa-google"></i> Google Reviews</a>
        <div class="sidebar-section" style="padding-top:20px;">Media</div>
        <a href="manage-gallery.php"><i class="fas fa-images"></i> Gallery Manager</a>
        <div class="sidebar-section" style="padding-top:20px;">Site</div>
        <a href="../index.php" target="_blank"><i class="fas fa-external-link-alt"></i> View Website</a>
    </div>
    <div class="sidebar-bottom">
        <a href="logout.php"><i class="fas fa-sign-out-alt text-danger"></i> Logout</a>
    </div>
</div>

<div class="admin-main">
    <div class="admin-topbar">
        <div>
            <a href="google-reviews.php" class="text-decoration-none text-muted small"><i class="fas fa-arrow-left me-1"></i> Back to Google Reviews</a>
            <h5 class="fw-bold mb-0 mt-1"><i class="fab fa-google me-2" style="color:#4285F4;"></i>Add Google Review</h5>
        </div>
    </div>

    <?php if ($error): ?>
        <div class="alert alert-danger border-0 rounded-4 shadow-sm mb-4">
            <i class="fas fa-exclamation-circle me-2"></i><?= $error ?>
        </div>
    <?php endif; ?>

    <div class="row g-4">
        <div class="col-lg-8">
            <form method="POST" enctype="multipart/form-data">

                <div class="form-section">
                    <h6><i class="fas fa-user me-2"></i>Reviewer Information</h6>
                    <div class="row g-4">
                        <div class="col-md-7">
                            <label class="form-label">Reviewer Full Name <span class="text-danger">*</span></label>
                            <input type="text" name="reviewer_name" id="prev-name" class="form-control"
                                   placeholder="e.g. Amira Perera"
                                   value="<?= htmlspecialchars($_POST['reviewer_name'] ?? '') ?>" required>
                        </div>
                        <div class="col-md-5">
                            <label class="form-label">Review Date</label>
                            <input type="text" name="review_date" class="form-control"
                                   placeholder="e.g. a week ago, June 2025"
                                   value="<?= htmlspecialchars($_POST['review_date'] ?? '') ?>">
                        </div>
                        <div class="col-md-12">
                            <label class="form-label">Reviewer Photo <span class="text-muted small">(optional)</span></label>
                            <input type="file" name="reviewer_photo" id="photo-input" class="form-control" accept="image/*">
                            <small class="text-muted">Upload the reviewer's profile photo. Leave blank to use initials avatar.</small>
                        </div>
                    </div>
                </div>

                <div class="form-section">
                    <h6><i class="fas fa-star me-2"></i>Review Details</h6>
                    <div class="row g-4">
                        <div class="col-md-12">
                            <label class="form-label">Star Rating <span class="text-danger">*</span></label>
                            <div class="star-picker" id="star-picker">
                                <input type="hidden" name="rating" id="rating-val" value="5">
                                <span data-val="1" class="active">★</span>
                                <span data-val="2" class="active">★</span>
                                <span data-val="3" class="active">★</span>
                                <span data-val="4" class="active">★</span>
                                <span data-val="5" class="active">★</span>
                            </div>
                            <small class="text-muted mt-1 d-block" id="rating-text">5 out of 5 stars</small>
                        </div>
                        <div class="col-md-12">
                            <label class="form-label">Review Text <span class="text-danger">*</span></label>
                            <textarea name="review_text" id="prev-review" class="form-control" rows="5"
                                      placeholder="Paste or type the Google review text here..."
                                      required><?= htmlspecialchars($_POST['review_text'] ?? '') ?></textarea>
                        </div>
                    </div>
                </div>

                <div class="form-section">
                    <h6><i class="fas fa-cog me-2"></i>Settings</h6>
                    <div class="row g-4">
                        <div class="col-md-4">
                            <label class="form-label">Sort Order</label>
                            <input type="number" name="sort_order" class="form-control"
                                   value="<?= htmlspecialchars($_POST['sort_order'] ?? '0') ?>" min="0">
                            <small class="text-muted">Higher = appears first</small>
                        </div>
                        <div class="col-md-8 d-flex align-items-center pt-4">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" name="is_active" id="is_active"
                                       style="width:44px;height:24px;" <?= !isset($_POST['is_active']) || $_POST['is_active'] ? 'checked' : '' ?>>
                                <label class="form-check-label fw-semibold ms-2" for="is_active">
                                    Show on homepage (Active)
                                </label>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="d-flex gap-3">
                    <button type="submit" class="btn btn-primary rounded-pill px-5 py-3 fw-bold shadow-sm">
                        <i class="fas fa-plus me-2"></i>Add Review
                    </button>
                    <a href="google-reviews.php" class="btn btn-light rounded-pill px-4 py-3">Cancel</a>
                </div>
            </form>
        </div>

        <!-- Live Preview -->
        <div class="col-lg-4">
            <div class="form-section" style="position: sticky; top: 20px;">
                <h6><i class="fas fa-eye me-2"></i>Live Preview</h6>
                <div class="review-preview-card">
                    <div class="d-flex justify-content-between align-items-start mb-3">
                        <div class="d-flex align-items-center gap-2">
                            <div class="preview-avatar" id="prev-avatar-init">A</div>
                            <div>
                                <div class="fw-bold small" id="prev-name-display">Reviewer Name</div>
                                <div class="google-badge mt-1" style="display:inline-flex;align-items:center;gap:4px;font-size:11px;color:#555;background:#f8f9fa;border:1px solid #e0e0e0;padding:2px 8px;border-radius:50px;">
                                    <span class="g-blue">G</span><span class="g-red">o</span><span class="g-yellow">o</span><span class="g-blue">g</span><span class="g-green">l</span><span class="g-red">e</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="mb-2" id="prev-stars" style="color:#ffc107;font-size:16px;letter-spacing:2px;">★★★★★</div>
                    <p class="small text-muted mb-0" id="prev-review-display" style="line-height:1.6;">
                        Your review text will appear here...
                    </p>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Star rating picker
const stars = document.querySelectorAll('#star-picker span');
const ratingVal = document.getElementById('rating-val');
const ratingText = document.getElementById('rating-text');
const prevStars = document.getElementById('prev-stars');

function setRating(val) {
    ratingVal.value = val;
    ratingText.textContent = val + ' out of 5 stars';
    stars.forEach(s => s.classList.toggle('active', parseInt(s.dataset.val) <= val));
    prevStars.textContent = '★'.repeat(val) + '☆'.repeat(5-val);
}

stars.forEach(star => {
    star.addEventListener('click', () => setRating(parseInt(star.dataset.val)));
    star.addEventListener('mouseenter', () => {
        const val = parseInt(star.dataset.val);
        stars.forEach(s => s.classList.toggle('active', parseInt(s.dataset.val) <= val));
    });
    star.addEventListener('mouseleave', () => setRating(parseInt(ratingVal.value)));
});

// Live name preview
document.getElementById('prev-name').addEventListener('input', function() {
    const name = this.value || 'Reviewer Name';
    document.getElementById('prev-name-display').textContent = name;
    document.getElementById('prev-avatar-init').textContent = name.charAt(0).toUpperCase() || 'A';
});

// Live review preview
document.getElementById('prev-review').addEventListener('input', function() {
    const text = this.value || 'Your review text will appear here...';
    document.getElementById('prev-review-display').textContent = text.substring(0, 200) + (text.length > 200 ? '...' : '');
});

// Init
setRating(5);
</script>
</body>
</html>
