<?php
include "include/db.php";
include "include/header.php";

$errors = [];
$success = '';

// Fetch current data
$hero = $conn->query("SELECT * FROM manage_index LIMIT 1")->fetch_assoc();

// Parse JSON
$videos = json_decode($hero['featured_videos'] ?? '[]', true) ?: [];
$features = json_decode($hero['why_choose_features'] ?? '[]', true) ?: [];
$testimonials = json_decode($hero['testimonials'] ?? '[]', true) ?: [];

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_hero'])) {
    $title       = trim($_POST['title'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $btn1_text   = trim($_POST['btn1_text'] ?? '');
    $btn1_url    = trim($_POST['btn1_url'] ?? '');
    $btn2_text   = trim($_POST['btn2_text'] ?? '');
    $btn2_url    = trim($_POST['btn2_url'] ?? '');
    $video_section_title = trim($_POST['featured_videos_title'] ?? '');
    $more_text   = trim($_POST['featured_videos_more_text'] ?? '');
    $more_url    = trim($_POST['featured_videos_more_url'] ?? '');
    $robotics_title = trim($_POST['robotics_section_title'] ?? '');
    $why_title   = trim($_POST['why_choose_title'] ?? '');
    $testimonials_title = trim($_POST['testimonials_title'] ?? '');
    $cta_title = trim($_POST['cta_title'] ?? '');
    $cta_description = trim($_POST['cta_description'] ?? '');
    $cta_button_text = trim($_POST['cta_button_text'] ?? '');
    $cta_button_url = trim($_POST['cta_button_url'] ?? '');
    $feature_titles = $_POST['feature_title'] ?? [];
    $testimonial_quotes = $_POST['testimonial_quote'] ?? [];
    $testimonial_names  = $_POST['testimonial_name'] ?? [];

    $image_path = $hero['image_path'];
    $why_image  = $hero['why_choose_image'];

    // === VALIDATION ===
    if (empty($title)) $errors[] = "Hero Title is required.";
    if (empty($description)) $errors[] = "Hero Description is required.";
    if (empty($btn1_text)) $errors[] = "Button 1 Text is required.";
    if (empty($btn1_url)) $errors[] = "Button 1 URL is required.";
    if (empty($btn2_text)) $errors[] = "Button 2 Text is required.";
    if (empty($btn2_url)) $errors[] = "Button 2 URL is required.";
    if (empty($video_section_title)) $errors[] = "Featured Videos Title is required.";
    if (empty($more_text)) $errors[] = "More Videos button text is required.";
    if (empty($more_url)) $errors[] = "More Videos button URL is required.";
    if (empty($robotics_title)) $errors[] = "Robotics Section Title is required.";
    if (empty($why_title)) $errors[] = "Why Choose Title is required.";
    if (empty($testimonials_title)) $errors[] = "Testimonials section title is required.";
    if (empty($cta_title)) $errors[] = "CTA Title is required.";
    if (empty($cta_description)) $errors[] = "CTA Description is required.";
    if (empty($cta_button_text)) $errors[] = "CTA Button Text is required.";
    if (empty($cta_button_url)) $errors[] = "CTA Button URL is required.";

    // Validate features
    $valid_features = array_filter(array_map('trim', $feature_titles));
    if (empty($valid_features)) $errors[] = "At least one feature is required.";

    // Validate testimonials
    $valid_testimonials = [];
    foreach ($testimonial_quotes as $i => $quote) {
        $quote = trim($quote);
        $name  = trim($testimonial_names[$i] ?? '');
        if ($quote && $name) $valid_testimonials[] = ['quote' => $quote, 'name' => $name];
    }
    if (empty($valid_testimonials)) $errors[] = "At least one testimonial is required.";

    // Validate videos
    $valid_videos = [];
    foreach ($_POST['youtube_url'] ?? [] as $i => $url) {
        $url = trim($url);
        $vtitle = trim($_POST['video_title'][$i] ?? '');
        if ($url && $vtitle && preg_match('/youtube\.com|youtu\.be/', $url)) {
            $valid_videos[] = ['title' => $vtitle, 'url' => $url];
        }
    }

    // === IMAGE UPLOADS ===
    if (isset($_FILES['hero_image']) && $_FILES['hero_image']['error'] === 0) {
        $ext = strtolower(pathinfo($_FILES['hero_image']['name'], PATHINFO_EXTENSION));
        if (in_array($ext, ['jpg','jpeg','png','gif','webp'])) {
            $dir = 'uploads/hero/';
            if (!is_dir($dir)) mkdir($dir, 0755, true);
            if ($image_path && file_exists($image_path)) @unlink($image_path);
            $image_path = $dir . 'hero_' . time() . '.' . $ext;
            move_uploaded_file($_FILES['hero_image']['tmp_name'], $image_path);
        } else $errors[] = "Invalid hero image.";
    }

    if (isset($_FILES['why_choose_image']) && $_FILES['why_choose_image']['error'] === 0) {
        $ext = strtolower(pathinfo($_FILES['why_choose_image']['name'], PATHINFO_EXTENSION));
        if (in_array($ext, ['jpg','jpeg','png','gif','webp'])) {
            $dir = 'uploads/why/';
            if (!is_dir($dir)) mkdir($dir, 0755, true);
            if ($why_image && file_exists($why_image)) @unlink($why_image);
            $why_image = $dir . 'why_' . time() . '.' . $ext;
            move_uploaded_file($_FILES['why_choose_image']['tmp_name'], $why_image);
        } else $errors[] = "Invalid Why Choose image.";
    }

    // === SAVE TO DB ===
    if (empty($errors)) {
        $videos_json = json_encode($valid_videos);
        $features_json = json_encode(array_map(fn($t) => ['title' => $t], $valid_features));
        $testimonials_json = json_encode($valid_testimonials);

        $stmt = $conn->prepare("
            UPDATE manage_index SET 
                title=?, description=?, image_path=?,
                button1_text=?, button1_url=?, button2_text=?, button2_url=?,
                featured_videos_title=?, featured_videos=?,
                featured_videos_more_text=?, featured_videos_more_url=?,
                robotics_section_title=?,
                why_choose_title=?, why_choose_image=?, why_choose_features=?,
                testimonials_title=?, testimonials=?,
                cta_title=?, cta_description=?, cta_button_text=?, cta_button_url=?
            WHERE id=?
        ");

        $stmt->bind_param(
            "sssssssssssssssssssssi",
            $title, $description, $image_path,
            $btn1_text, $btn1_url,
            $btn2_text, $btn2_url,
            $video_section_title, $videos_json,
            $more_text, $more_url,
            $robotics_title,
            $why_title, $why_image, $features_json,
            $testimonials_title, $testimonials_json,
            $cta_title, $cta_description, $cta_button_text, $cta_button_url,
            $hero['id']
        );

        if ($stmt->execute()) {
            $success = "All sections updated successfully!";
            $hero = $conn->query("SELECT * FROM manage_index LIMIT 1")->fetch_assoc();
            $videos = json_decode($hero['featured_videos'], true) ?: [];
            $features = json_decode($hero['why_choose_features'], true) ?: [];
            $testimonials = json_decode($hero['testimonials'], true) ?: [];
        } else {
            $errors[] = "Error: " . $stmt->error;
        }
        $stmt->close();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Index - IT Galaxy Academy</title>
    <script src="https://kit.fontawesome.com/a076d05399.js" crossorigin="anonymous"></script>
    <style>
        @import url('https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css');
        body { overflow-x: hidden; font-family: 'Inter', sans-serif; background: #f9fafb; }
        .content { transition: margin-left 0.3s ease; }
        .top-nav { background: linear-gradient(90deg, #1F2937, #374151); }
        .form-card { background: white; padding: 2rem; border-radius: 1rem; box-shadow: 0 10px 25px rgba(0,0,0,0.1); margin-bottom: 2rem; }
        .error { color: #DC2626; background: #FEE2E2; padding: 0.75rem; border-radius: 0.5rem; margin-bottom: 1rem; }
        .success { color: #10B981; background: #ECFDF5; padding: 1rem; border-radius: 0.5rem; text-align: center; font-weight: bold; margin-bottom: 1rem; }
        .preview-img { max-height: 180px; border-radius: 0.75rem; margin-top: 1rem; border: 2px dashed #CBD5E1; object-fit: cover; width: 100%; }
        .input-group { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
        .row { display: flex; gap: 1rem; align-items: flex-start; margin-bottom: 1rem; }
        .remove-btn { background: #EF4444; color: white; border: none; padding: 0.5rem 1rem; border-radius: 0.5rem; cursor: pointer; font-weight: bold; }
        .add-btn { background: #10B981; color: white; padding: 0.5rem 1rem; border-radius: 0.5rem; font-size: 0.875rem; }
        .section-divider { border-top: 2px solid #E5E7EB; padding-top: 1.5rem; margin-top: 1.5rem; }
        textarea { min-height: 80px; resize: vertical; }
        @media (max-width: 768px) { 
            .content { margin-left: 0 !important; } 
            .input-group, .row { display: block; }
            .remove-btn { width: 100%; }
        }
        @media (min-width: 769px) { .content { margin-left: 250px; } }
    </style>
</head>
<body>

<div id="content" class="content p-6 min-h-screen">
    <!-- Top Nav -->
    <nav class="top-nav sticky top-0 text-white p-4 flex justify-between items-center shadow-lg z-40">
        <div class="logo text-2xl font-bold">IT Galaxy Academy</div>
        <div class="right-nav flex items-center gap-4">
            <i class="fas fa-bell text-xl p-2 rounded-full hover:bg-yellow-500 cursor-pointer"></i>
            <i class="fas fa-envelope text-xl p-2 rounded-full hover:bg-yellow-500 cursor-pointer"></i>
            <div class="profile flex items-center gap-2">
                <img src="https://via.placeholder.com/40" alt="Profile" class="w-10 h-10 rounded-full">
                <span>Admin</span>
            </div>
            <i id="toggle" class="fas fa-bars text-xl p-2 rounded-full hover:bg-yellow-500 cursor-pointer"></i>
        </div>
    </nav>

    <div class="max-w-5xl mx-auto my-8">
        <h2 class="text-3xl font-bold text-gray-800 mb-6 text-center">Manage Index Page</h2>

        <!-- Success / Error -->
        <?php if ($success): ?>
            <div class="success"><?php echo htmlspecialchars($success); ?></div>
        <?php endif; ?>
        <?php if (!empty($errors)): ?>
            <div class="error">
                <?php foreach ($errors as $error): ?>
                    <p><?php echo htmlspecialchars($error); ?></p>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <!-- Full Form -->
        <form method="POST" enctype="multipart/form-data" class="space-y-6">
            <input type="hidden" name="update_hero" value="1">

            <!-- HERO -->
            <div class="form-card">
                <h3 class="text-xl font-semibold mb-4">Hero Section</h3>
                <input type="text" name="title" value="<?php echo htmlspecialchars($hero['title'] ?? ''); ?>" placeholder="Hero Title" class="w-full p-3 border rounded-lg" required>
                <textarea name="description" rows="3" placeholder="Hero Description" class="w-full p-3 border rounded-lg mt-3" required><?php echo htmlspecialchars($hero['description'] ?? ''); ?></textarea>
                <div class="grid grid-cols-2 gap-4 mt-3">
                    <input type="text" name="btn1_text" value="<?php echo htmlspecialchars($hero['button1_text'] ?? ''); ?>" placeholder="Button 1 Text" class="p-3 border rounded-lg" required>
                    <input type="url" name="btn1_url" value="<?php echo htmlspecialchars($hero['button1_url'] ?? ''); ?>" placeholder="Button 1 URL" class="p-3 border rounded-lg" required>
                    <input type="text" name="btn2_text" value="<?php echo htmlspecialchars($hero['button2_text'] ?? ''); ?>" placeholder="Button 2 Text" class="p-3 border rounded-lg" required>
                    <input type="url" name="btn2_url" value="<?php echo htmlspecialchars($hero['button2_url'] ?? ''); ?>" placeholder="Button 2 URL" class="p-3 border rounded-lg" required>
                </div>
                <div class="mt-3">
                    <?php if ($hero['image_path'] && file_exists($hero['image_path'])): ?>
                        <img src="<?php echo $hero['image_path']; ?>" class="preview-img">
                    <?php endif; ?>
                    <input type="file" name="hero_image" accept="image/*" class="w-full p-3 border rounded-lg mt-2">
                </div>
            </div>

            <!-- VIDEOS -->
            <div class="form-card section-divider">
                <h3 class="text-xl font-semibold mb-4">Featured Video Tutorials</h3>
                <input type="text" name="featured_videos_title" value="<?php echo htmlspecialchars($hero['featured_videos_title'] ?? ''); ?>" class="w-full p-3 border rounded-lg" required>
                <div class="grid grid-cols-2 gap-4 mt-3">
                    <input type="text" name="featured_videos_more_text" value="<?php echo htmlspecialchars($hero['featured_videos_more_text'] ?? ''); ?>" placeholder="More Button Text" class="p-3 border rounded-lg" required>
                    <input type="url" name="featured_videos_more_url" value="<?php echo htmlspecialchars($hero['featured_videos_more_url'] ?? ''); ?>" placeholder="More Button URL" class="p-3 border rounded-lg" required>
                </div>
                <div class="mt-4">
                    <button type="button" id="add-video" class="add-btn">+ Add Video</button>
                    <div id="video-container" class="mt-3">
                        <?php foreach ($videos as $v): ?>
                            <div class="row">
                                <input type="text" name="video_title[]" value="<?php echo htmlspecialchars($v['title']); ?>" class="flex-1 p-3 border rounded-lg" required>
                                <input type="url" name="youtube_url[]" value="<?php echo htmlspecialchars($v['url']); ?>" class="flex-1 p-3 border rounded-lg" required>
                                <button type="button" class="remove-btn" onclick="this.parentElement.remove()">X</button>
                            </div>
                        <?php endforeach; ?>
                        <div class="row">
                            <input type="text" name="video_title[]" placeholder="Video Title" class="flex-1 p-3 border rounded-lg" required>
                            <input type="url" name="youtube_url[]" placeholder="YouTube URL" class="flex-1 p-3 border rounded-lg" required>
                            <button type="button" class="remove-btn" onclick="this.parentElement.remove()">X</button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- ROBOTICS -->
            <div class="form-card section-divider">
                <h3 class="text-xl font-semibold mb-4">Explore Our Robotics Courses</h3>
                <input type="text" name="robotics_section_title" value="<?php echo htmlspecialchars($hero['robotics_section_title'] ?? ''); ?>" class="w-full p-3 border rounded-lg" required>
            </div>

            <!-- WHY CHOOSE -->
            <div class="form-card section-divider">
                <h3 class="text-xl font-semibold mb-4">Why Choose IT Galaxy Academy?</h3>
                <input type="text" name="why_choose_title" value="<?php echo htmlspecialchars($hero['why_choose_title'] ?? ''); ?>" class="w-full p-3 border rounded-lg" required>
                <div class="mt-4">
                    <button type="button" id="add-feature" class="add-btn">+ Add Feature</button>
                    <div id="feature-container" class="mt-3">
                        <?php foreach ($features as $f): ?>
                            <div class="row">
                                <input type="text" name="feature_title[]" value="<?php echo htmlspecialchars($f['title']); ?>" class="flex-1 p-3 border rounded-lg" required>
                                <button type="button" class="remove-btn" onclick="this.parentElement.remove()">X</button>
                            </div>
                        <?php endforeach; ?>
                        <div class="row">
                            <input type="text" name="feature_title[]" placeholder="Feature Title" class="flex-1 p-3 border rounded-lg" required>
                            <button type="button" class="remove-btn" onclick="this.parentElement.remove()">X</button>
                        </div>
                    </div>
                </div>
                <div class="mt-3">
                    <?php if ($hero['why_choose_image'] && file_exists($hero['why_choose_image'])): ?>
                        <img src="<?php echo $hero['why_choose_image']; ?>" class="preview-img">
                    <?php endif; ?>
                    <input type="file" name="why_choose_image" accept="image/*" class="w-full p-3 border rounded-lg mt-2">
                </div>
            </div>

            <!-- TESTIMONIALS -->
            <div class="form-card section-divider">
                <h3 class="text-xl font-semibold mb-4">What Our Students Say</h3>
                <input type="text" name="testimonials_title" value="<?php echo htmlspecialchars($hero['testimonials_title'] ?? ''); ?>" class="w-full p-3 border rounded-lg" required>
                <div class="mt-4">
                    <button type="button" id="add-testimonial" class="add-btn">+ Add Testimonial</button>
                    <div id="testimonial-container" class="mt-3">
                        <?php foreach ($testimonials as $t): ?>
                            <div class="row">
                                <textarea name="testimonial_quote[]" class="flex-1 p-3 border rounded-lg" required><?php echo htmlspecialchars($t['quote']); ?></textarea>
                                <input type="text" name="testimonial_name[]" value="<?php echo htmlspecialchars($t['name']); ?>" class="flex-1 p-3 border rounded-lg" required>
                                <button type="button" class="remove-btn" onclick="this.parentElement.remove()">X</button>
                            </div>
                        <?php endforeach; ?>
                        <div class="row">
                            <textarea name="testimonial_quote[]" placeholder="Quote" class="flex-1 p-3 border rounded-lg" required></textarea>
                            <input type="text" name="testimonial_name[]" placeholder="Name" class="flex-1 p-3 border rounded-lg" required>
                            <button type="button" class="remove-btn" onclick="this.parentElement.remove()">X</button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- CTA (NEW) -->
            <div class="form-card section-divider">
                <h3 class="text-xl font-semibold mb-4">Call to Action</h3>
                <input type="text" name="cta_title" value="<?php echo htmlspecialchars($hero['cta_title'] ?? ''); ?>" placeholder="Start Your Robotics Journey Today" class="w-full p-3 border rounded-lg" required>
                <textarea name="cta_description" rows="3" class="w-full p-3 border rounded-lg mt-3" required><?php echo htmlspecialchars($hero['cta_description'] ?? ''); ?></textarea>
                <div class="grid grid-cols-2 gap-4 mt-3">
                    <input type="text" name="cta_button_text" value="<?php echo htmlspecialchars($hero['cta_button_text'] ?? ''); ?>" placeholder="Sign Up Now" class="p-3 border rounded-lg" required>
                    <input type="url" name="cta_button_url" value="<?php echo htmlspecialchars($hero['cta_button_url'] ?? ''); ?>" placeholder="https://..." class="p-3 border rounded-lg" required>
                </div>
            </div>

            <!-- SUBMIT -->
            <div class="flex gap-4">
                <button type="submit" class="flex-1 bg-yellow-500 text-white p-4 rounded-lg hover:bg-yellow-600 font-bold text-lg">
                    Update All Sections
                </button>
                <a href="dashboard.php" class="flex-1 bg-gray-600 text-white p-4 rounded-lg text-center font-bold text-lg">
                    Back to Dashboard
                </a>
            </div>
        </form>
    </div>
</div>

<script>
    ['video', 'feature', 'testimonial'].forEach(type => {
        document.getElementById(`add-${type}`)?.addEventListener('click', () => {
            const container = document.getElementById(`${type}-container`);
            const row = document.createElement('div');
            row.className = 'row';
            if (type === 'video') {
                row.innerHTML = `<input type="text" name="video_title[]" placeholder="Video Title" class="flex-1 p-3 border rounded-lg" required>
                                 <input type="url" name="youtube_url[]" placeholder="YouTube URL" class="flex-1 p-3 border rounded-lg" required>
                                 <button type="button" class="remove-btn" onclick="this.parentElement.remove()">X</button>`;
            } else if (type === 'feature') {
                row.innerHTML = `<input type="text" name="feature_title[]" placeholder="Feature Title" class="flex-1 p-3 border rounded-lg" required>
                                 <button type="button" class="remove-btn" onclick="this.parentElement.remove()">X</button>`;
            } else {
                row.innerHTML = `<textarea name="testimonial_quote[]" placeholder="Quote" class="flex-1 p-3 border rounded-lg" required></textarea>
                                 <input type="text" name="testimonial_name[]" placeholder="Name" class="flex-1 p-3 border rounded-lg" required>
                                 <button type="button" class="remove-btn" onclick="this.parentElement.remove()">X</button>`;
            }
            container.appendChild(row);
        });
    });
</script>

<?php include "include/footer.php"; $conn->close(); ?>
</body>
</html>