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

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

// ---------- FETCH CURRENT DATA ----------
$home_result = $conn->query("SELECT * FROM manage_home LIMIT 1");
$home = $home_result->num_rows > 0 ? $home_result->fetch_assoc() : [];

// ---------- IMAGE UPLOAD SETTINGS ----------
$upload_dir = "uploads/hero/";               // <-- create this folder (chmod 755)
$allowed    = ['jpg','jpeg','png','gif'];
$max_size   = 2 * 1024 * 1024;               // 2 MB

if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);

// ---------- HANDLE FORM ----------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_home'])) {

    // ----- TEXT FIELDS -----
    $shop_category_title   = trim($_POST['shop_category_title'] ?? '');
    $flash_sale_title      = trim($_POST['flash_sale_title'] ?? '');
    $flash_sale_timer      = trim($_POST['flash_sale_timer'] ?? '');
    $flash_sale_button_text= trim($_POST['flash_sale_button_text'] ?? '');
    $flash_sale_button_url = trim($_POST['flash_sale_button_url'] ?? '');
    $featured_products_title = trim($_POST['featured_products_title'] ?? '');
    $best_sellers_title    = trim($_POST['best_sellers_title'] ?? '');

    // ----- HERO SECTION -----
    $hero_title        = trim($_POST['hero_title'] ?? '');
    $hero_description  = trim($_POST['hero_description'] ?? '');
    $hero_btn1_text    = trim($_POST['hero_btn1_text'] ?? '');
    $hero_btn1_url     = trim($_POST['hero_btn1_url'] ?? '');
    $hero_btn2_text    = trim($_POST['hero_btn2_text'] ?? '');
    $hero_btn2_url     = trim($_POST['hero_btn2_url'] ?? '');

    // ----- VALIDATION -----
    if (empty($shop_category_title))   $errors[] = "Shop by Category title is required.";
    if (empty($flash_sale_title))      $errors[] = "Flash Sale title is required.";
    if (empty($flash_sale_timer))      $errors[] = "Flash Sale timer is required.";
    if (empty($flash_sale_button_text))$errors[] = "Flash Sale button text is required.";
    if (empty($flash_sale_button_url)) $errors[] = "Flash Sale button URL is required.";
    if (empty($featured_products_title))$errors[] = "Featured Products title is required.";
    if (empty($best_sellers_title))    $errors[] = "Best Sellers title is required.";

    // Hero required fields
    if (empty($hero_title))            $errors[] = "Hero title is required.";
    if (empty($hero_description))      $errors[] = "Hero description is required.";
    if (empty($hero_btn1_text))        $errors[] = "Start Shopping button text is required.";
    if (empty($hero_btn1_url))         $errors[] = "Start Shopping button URL is required.";

    // ----- IMAGE HANDLING -----
    $hero_image = $home['hero_image'] ?? '';   // keep old if no new upload
    if (isset($_FILES['hero_image']) && $_FILES['hero_image']['error'] === UPLOAD_ERR_OK) {
        $file_tmp  = $_FILES['hero_image']['tmp_name'];
        $file_name = basename($_FILES['hero_image']['name']);
        $file_size = $_FILES['hero_image']['size'];
        $file_ext  = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

        if (!in_array($file_ext, $allowed)) {
            $errors[] = "Hero image: only JPG, JPEG, PNG & GIF are allowed.";
        } elseif ($file_size > $max_size) {
            $errors[] = "Hero image must be ≤ 2 MB.";
        } else {
            $new_name = uniqid('hero_') . '.' . $file_ext;
            $dest     = $upload_dir . $new_name;
            if (move_uploaded_file($file_tmp, $dest)) {
                // delete old image if exists
                if (!empty($hero_image) && file_exists($upload_dir . $hero_image)) {
                    @unlink($upload_dir . $hero_image);
                }
                $hero_image = $new_name;
            } else {
                $errors[] = "Failed to upload hero image.";
            }
        }
    }

    // ----- SAVE TO DB -----
    if (empty($errors)) {
        if (!empty($home['id'])) {
            // UPDATE
            $stmt = $conn->prepare("
                UPDATE manage_home SET
                    shop_category_title=?, flash_sale_title=?, flash_sale_timer=?,
                    flash_sale_button_text=?, flash_sale_button_url=?,
                    featured_products_title=?, best_sellers_title=?,
                    hero_title=?, hero_description=?, hero_btn1_text=?, hero_btn1_url=?,
                    hero_btn2_text=?, hero_btn2_url=?, hero_image=?
                WHERE id=?
            ");
            $stmt->bind_param(
                "ssssssssssssssi",
                $shop_category_title, $flash_sale_title, $flash_sale_timer,
                $flash_sale_button_text, $flash_sale_button_url,
                $featured_products_title, $best_sellers_title,
                $hero_title, $hero_description, $hero_btn1_text, $hero_btn1_url,
                $hero_btn2_text, $hero_btn2_url, $hero_image,
                $home['id']
            );
        } else {
            // INSERT
            $stmt = $conn->prepare("
                INSERT INTO manage_home (
                    shop_category_title, flash_sale_title, flash_sale_timer,
                    flash_sale_button_text, flash_sale_button_url,
                    featured_products_title, best_sellers_title,
                    hero_title, hero_description, hero_btn1_text, hero_btn1_url,
                    hero_btn2_text, hero_btn2_url, hero_image
                ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)
            ");
            $stmt->bind_param(
                "ssssssssssssss",
                $shop_category_title, $flash_sale_title, $flash_sale_timer,
                $flash_sale_button_text, $flash_sale_button_url,
                $featured_products_title, $best_sellers_title,
                $hero_title, $hero_description, $hero_btn1_text, $hero_btn1_url,
                $hero_btn2_text, $hero_btn2_url, $hero_image
            );
        }

        if ($stmt->execute()) {
            $success = "Home page updated successfully!";
            $home = $conn->query("SELECT * FROM manage_home LIMIT 1")->fetch_assoc();
        } else {
            $errors[] = "Database 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 Home Page - 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 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; }
        .input-group { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
        .section-divider { border-top: 2px solid #E5E7EB; padding-top: 1.5rem; margin-top: 1.5rem; }
        .preview-img { max-width: 100%; height: auto; margin-top: .5rem; border-radius: .5rem; }
        @media (max-width: 768px) {
            .content { margin-left: 0 !important; }
            .input-group { display: block; }
        }
        @media (min-width: 769px) { .content { margin-left: 250px; } }
    </style>
</head>
<body>
<div id="content" class="content p-6 min-h-screen">
    <?php include "include/topnav.php"; // keep your existing top nav if you have one ?>

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

        <?php if ($success): ?>
            <div class="success"><?php echo htmlspecialchars($success); ?></div>
        <?php endif; ?>

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

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

            <!-- ==================== HERO SECTION ==================== -->
            <div class="form-card">
                <h3 class="text-xl font-semibold mb-4">Hero Section</h3>

                <input type="text" name="hero_title"
                       value="<?php echo htmlspecialchars($home['hero_title'] ?? ''); ?>"
                       placeholder="Welcome to IT Galaxy Academy" class="w-full p-3 border rounded-lg" required>

                <textarea name="hero_description" rows="4" placeholder="Short description..."
                          class="w-full p-3 border rounded-lg mt-3" required><?php echo htmlspecialchars($home['hero_description'] ?? ''); ?></textarea>

                <div class="input-group mt-3">
                    <input type="text" name="hero_btn1_text"
                           value="<?php echo htmlspecialchars($home['hero_btn1_text'] ?? ''); ?>"
                           placeholder="Start Shopping" class="p-3 border rounded-lg" required>
                    <input type="url" name="hero_btn1_url"
                           value="<?php echo htmlspecialchars($home['hero_btn1_url'] ?? ''); ?>"
                           placeholder="https://..." class="p-3 border rounded-lg" required>
                </div>

                <div class="input-group mt-3">
                    <input type="text" name="hero_btn2_text"
                           value="<?php echo htmlspecialchars($home['hero_btn2_text'] ?? ''); ?>"
                           placeholder="All Products" class="p-3 border rounded-lg">
                    <input type="url" name="hero_btn2_url"
                           value="<?php echo htmlspecialchars($home['hero_btn2_url'] ?? ''); ?>"
                           placeholder="https://..." class="p-3 border rounded-lg">
                </div>

                <div class="mt-4">
                    <label class="block font-medium mb-1">Hero Image (JPG/PNG/GIF ≤ 2 MB)</label>
                    <input type="file" name="hero_image" accept="image/*" class="w-full p-2 border rounded-lg">
                    <?php if (!empty($home['hero_image'])): ?>
                        <img src="<?php echo htmlspecialchars($upload_dir . $home['hero_image']); ?>"
                             alt="Current hero" class="preview-img mt-2">
                    <?php endif; ?>
                </div>
            </div>

            <!-- ==================== SHOP BY CATEGORY ==================== -->
            <div class="form-card section-divider">
                <h3 class="text-xl font-semibold mb-4">Shop by Category</h3>
                <input type="text" name="shop_category_title"
                       value="<?php echo htmlspecialchars($home['shop_category_title'] ?? ''); ?>"
                       placeholder="Shop by Category" class="w-full p-3 border rounded-lg" required>
            </div>

            <!-- ==================== FLASH SALE ==================== -->
            <div class="form-card section-divider">
                <h3 class="text-xl font-semibold mb-4">Flash Sale Section</h3>
                <input type="text" name="flash_sale_title"
                       value="<?php echo htmlspecialchars($home['flash_sale_title'] ?? ''); ?>"
                       placeholder="Flash Sale! Up to 40% OFF" class="w-full p-3 border rounded-lg" required>

                <input type="text" name="flash_sale_timer"
                       value="<?php echo htmlspecialchars($home['flash_sale_timer'] ?? ''); ?>"
                       placeholder="23:59:59" class="w-full p-3 border rounded-lg mt-3" required>

                <div class="input-group mt-3">
                    <input type="text" name="flash_sale_button_text"
                           value="<?php echo htmlspecialchars($home['flash_sale_button_text'] ?? ''); ?>"
                           placeholder="Shop Sales" class="p-3 border rounded-lg" required>
                    <input type="url" name="flash_sale_button_url"
                           value="<?php echo htmlspecialchars($home['flash_sale_button_url'] ?? ''); ?>"
                           placeholder="https://..." class="p-3 border rounded-lg" required>
                </div>
            </div>

            <!-- ==================== PRODUCT TITLES ==================== -->
            <div class="form-card section-divider">
                <h3 class="text-xl font-semibold mb-4">Product Section Titles</h3>
                <input type="text" name="featured_products_title"
                       value="<?php echo htmlspecialchars($home['featured_products_title'] ?? ''); ?>"
                       placeholder="Featured Products" class="w-full p-3 border rounded-lg" required>

                <input type="text" name="best_sellers_title"
                       value="<?php echo htmlspecialchars($home['best_sellers_title'] ?? ''); ?>"
                       placeholder="Best Sellers" class="w-full p-3 border rounded-lg mt-3" required>
            </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 Home Page
                </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>

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