<?php
session_start();
if (empty($_SESSION['is_admin']) || $_SESSION['is_admin'] !== true) {
    header('Location: admin_login.php');
    exit;
}

require_once __DIR__ . '/classes/ImageHandler.php';
require_once __DIR__ . '/helpers/database_helper.php';

$dataDir = __DIR__ . '/data';
$homepageSectionsFile = $dataDir . '/homepage_sections.json';
$productsFile = $dataDir . '/products.json';
$uploadsDir = __DIR__ . '/uploads';

if (!is_dir($uploadsDir)) @mkdir($uploadsDir, 0755, true);

$imageHandler = new ImageHandler($uploadsDir);
$homepageSections = DatabaseHelper::loadJson('homepage_sections.json', []);

$products = [];
$prods = DatabaseHelper::loadJson('products.json', []);
foreach ($prods as $p) {
    $products[$p['id']] = $p;
}

$categories = [];
$cats = DatabaseHelper::loadJson('categories.json', []);
foreach ($cats as $cat) {
    $categories[] = $cat;
}

$success = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'update_featured_categories') {
        $cat1_id = trim($_POST['cat1_id'] ?? '');
        $cat1_name = trim($_POST['cat1_name'] ?? '');
        $cat1_image = trim($_POST['cat1_image'] ?? '');
        $cat1_desc = trim($_POST['cat1_desc'] ?? '');
        $cat1_carousel = isset($_POST['cat1_carousel']) ? 1 : 0;
        
        $cat2_id = trim($_POST['cat2_id'] ?? '');
        $cat2_name = trim($_POST['cat2_name'] ?? '');
        $cat2_image = trim($_POST['cat2_image'] ?? '');
        $cat2_desc = trim($_POST['cat2_desc'] ?? '');
        $cat2_carousel = isset($_POST['cat2_carousel']) ? 1 : 0;
        
        // Handle image uploads
        if (!empty($_FILES['cat1_image_file']['name'])) {
            $upload = $imageHandler->uploadImage($_FILES['cat1_image_file'], 'featured_cat_1');
            if ($upload['success']) {
                $cat1_image = $upload['filename'];
            } else {
                $error = 'Failed to upload Category 1 image: ' . $upload['error'];
            }
        }
        
        if (!empty($_FILES['cat2_image_file']['name'])) {
            $upload = $imageHandler->uploadImage($_FILES['cat2_image_file'], 'featured_cat_2');
            if ($upload['success']) {
                $cat2_image = $upload['filename'];
            } else {
                $error = 'Failed to upload Category 2 image: ' . $upload['error'];
                $cat2_image = '';
            }
        }
        
        if (!empty($cat1_image) && !empty($cat2_image) && !$error) {
            $homepageSections['featured_categories'] = [
                ['id' => 1, 'category_id' => $cat1_id, 'name' => $cat1_name, 'image' => $cat1_image, 'description' => $cat1_desc, 'add_to_carousel' => $cat1_carousel],
                ['id' => 2, 'category_id' => $cat2_id, 'name' => $cat2_name, 'image' => $cat2_image, 'description' => $cat2_desc, 'add_to_carousel' => $cat2_carousel]
            ];
            DatabaseHelper::saveJson('homepage_sections.json', $homepageSections);
            $success = 'Featured categories updated successfully!';
        } elseif (!$error) {
            $error = 'Please fill all required fields.';
        }
    }
    
    if ($action === 'update_info_cards') {
        $infoCards = [];
        for ($i = 1; $i <= 3; $i++) {
            $icon = trim($_POST["card{$i}_icon"] ?? '');
            $title = trim($_POST["card{$i}_title"] ?? '');
            $desc = trim($_POST["card{$i}_desc"] ?? '');
            if ($icon && $title && $desc) {
                $infoCards[] = ['id' => $i, 'icon' => $icon, 'title' => $title, 'description' => $desc];
            }
        }
        if (count($infoCards) === 3) {
            $homepageSections['info_cards'] = $infoCards;
            DatabaseHelper::saveJson('homepage_sections.json', $homepageSections);
            $success = 'Info cards updated successfully!';
        } else {
            $error = 'Please fill all info card fields.';
        }
    }
}

$featuredCats = $homepageSections['featured_categories'] ?? [];
$infoCards = $homepageSections['info_cards'] ?? [];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Manage Homepage Sections - Admin</title>
    <link rel="stylesheet" href="styles.css">
    <style>
        body { background:#f5f5f5; }
        .admin-container { max-width:1000px; margin-left: 20%;  place-items:center; padding:20px; }
        .section-card { display: block; place-items: center; background:#fff; padding:24px; border-radius:8px; margin-bottom:24px; box-shadow:0 2px 8px rgba(0,0,0,0.05); }
        .section-card h2 { margin-top:0; color:#333; border-bottom:2px solid #F07E2D; padding-bottom:12px; }
        .form-group { margin-bottom:16px; display:flex; flex-direction:column; gap:6px; }
        .form-group label { font-weight:600; font-size:14px; }
        .form-group input, .form-group textarea { padding:10px; border:1px solid #e6e6e6; border-radius:6px; font-size:14px; font-family:inherit; }
        .form-row { display:grid; grid-template-columns:1fr 1fr; gap:16px; }
        .btn { background:#F07E2D; color:#fff; padding:10px 16px; border:none; border-radius:6px; cursor:pointer; font-weight:600; }
        .btn:hover { background:#d16a95; }
        .success { background:#d4edda; color:#155724; padding:12px; border-radius:6px; margin-bottom:16px; }
        .error { background:#f8d7da; color:#721c24; padding:12px; border-radius:6px; margin-bottom:16px; }
        .preview { background:#f9f9f9; padding:12px; border-radius:6px; margin-top:8px; font-size:12px; color:#666; }
        .back-btn { background:#999; margin-bottom:20px; }
    </style>
</head>
<!-- <body class="admin-with-sidebar">
<php include __DIR__ . '/admin_sidebar.php'; ?> -->
<!-- ?php include __DIR__ . '/header.php'; ?> -->

<main class="admin-container">

<?php
// Default link
$dashboardLink = "admin_dashboard.php";

// Adjust based on role
if (isset($_SESSION['role'])) {
    switch ($_SESSION['role']) {
        case 'admin':
            $dashboardLink = "admin_dashboard.php";
            break;
        case 'subadmin':
            $dashboardLink = "subadmin_dashboard.php";
            break;
        case 'editor':
            $dashboardLink = "subadmin_dashboard.php";
            break;
        default:
            $dashboardLink = "admin_dashboard.php"; // fallback
    }
}
?>

<a href="<?php echo $dashboardLink; ?>" class="back-btn">← Back to Dashboard</a>

<style>
.back-btn {
    background-color: orange;
    color: white;
    padding: 8px 14px;
    text-decoration: none;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 500;
    margin-bottom: 20px;
}
.back-btn:hover {
    background-color: darkorange;
}
</style>

    <!-- <a href="admin_dashboard.php" class="btn back-btn">← Back to Dashboard</a>
     -->
    <?php if (!empty($success)): ?>
        <div class="success"><?php echo htmlspecialchars($success); ?></div>
    <?php endif; ?>
    <?php if (!empty($error)): ?>
        <div class="error"><?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>

    <!-- Featured Categories Section -->
    <div class="section-card" style="place-items: center; ">
        <h2>Featured Categories (2 Only)</h2>
        <p style="color:#666; margin-bottom:20px;">Select and customize the two featured categories that appear on your homepage.</p>
        
        <form method="post" enctype="multipart/form-data">
            <input type="hidden" name="action" value="update_featured_categories">
            
            <h3 style="margin-top:0; margin-bottom:16px;">Category 1</h3>
            <div class="form-row">
                <div class="form-group">
                    <label>Select Category:</label>
                    <select name="cat1_id" style="padding:10px; border:1px solid #e6e6e6; border-radius:6px; font-size:14px;">
                        <option value="">-- Choose Category --</option>
                        <?php foreach ($categories as $cat): ?>
                            <option value="<?php echo htmlspecialchars($cat['id']); ?>" <?php echo (($featuredCats[0]['category_id'] ?? '') == $cat['id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($cat['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>Category Name:</label>
                    <input type="text" name="cat1_name" value="<?php echo htmlspecialchars($featuredCats[0]['name'] ?? ''); ?>" placeholder="Display name for category" required>
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>Upload Category Image (467x589):</label>
                    <input type="file" name="cat1_image_file" accept="image/jpeg,image/png" style="padding:10px; border:1px solid #e6e6e6; border-radius:6px;">
                    <div class="preview">JPG or PNG. Recommended size: 467x589px. Image will be automatically resized.</div>
                </div>
                <div class="form-group">
                    <label>Or Use Existing Image:</label>
                    <input type="text" name="cat1_image" value="<?php echo htmlspecialchars($featuredCats[0]['image'] ?? ''); ?>" placeholder="e.g., uploads/featured_cat_1.png">
                    <div class="preview">If no file uploaded, this will be used</div>
                </div>
            </div>
            <div class="form-group">
                <label>Description:</label>
                <input type="text" name="cat1_desc" value="<?php echo htmlspecialchars($featuredCats[0]['description'] ?? ''); ?>" placeholder="Short description">
            </div>
            <div class="form-group">
                <label style="display:flex; align-items:center; gap:8px;">
                    <input type="checkbox" name="cat1_carousel" value="1" <?php echo (!empty($featuredCats[0]['add_to_carousel']) ? 'checked' : ''); ?> style="width:auto;">
                    Add to Carousel
                </label>
                <div class="preview">Check this to also display this image in the homepage carousel</div>
            </div>
            
            <h3 style="margin-top:24px; margin-bottom:16px;">Category 2</h3>
            <div class="form-row">
                <div class="form-group">
                    <label>Select Category:</label>
                    <select name="cat2_id" style="padding:10px; border:1px solid #e6e6e6; border-radius:6px; font-size:14px;">
                        <option value="">-- Choose Category --</option>
                        <?php foreach ($categories as $cat): ?>
                            <option value="<?php echo htmlspecialchars($cat['id']); ?>" <?php echo (($featuredCats[1]['category_id'] ?? '') == $cat['id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($cat['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>Category Name:</label>
                    <input type="text" name="cat2_name" value="<?php echo htmlspecialchars($featuredCats[1]['name'] ?? ''); ?>" placeholder="Display name for category" required>
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>Upload Category Image (467x589):</label>
                    <input type="file" name="cat2_image_file" accept="image/jpeg,image/png" style="padding:10px; border:1px solid #e6e6e6; border-radius:6px;">
                    <div class="preview">JPG or PNG. Recommended size: 467x589px. Image will be automatically resized.</div>
                </div>
                <div class="form-group">
                    <label>Or Use Existing Image:</label>
                    <input type="text" name="cat2_image" value="<?php echo htmlspecialchars($featuredCats[1]['image'] ?? ''); ?>" placeholder="e.g., uploads/featured_cat_2.png">
                    <div class="preview">If no file uploaded, this will be used</div>
                </div>
            </div>
            <div class="form-group">
                <label>Description:</label>
                <input type="text" name="cat2_desc" value="<?php echo htmlspecialchars($featuredCats[1]['description'] ?? ''); ?>" placeholder="Short description">
            </div>
            <div class="form-group">
                <label style="display:flex; align-items:center; gap:8px;">
                    <input type="checkbox" name="cat2_carousel" value="1" <?php echo (!empty($featuredCats[1]['add_to_carousel']) ? 'checked' : ''); ?> style="width:auto;">
                    Add to Carousel
                </label>
                <div class="preview">Check this to also display this image in the homepage carousel</div>
            </div>
            
            <button type="submit" class="btn" style="margin-top:16px;">Save Featured Categories</button>
        </form>
    </div>

    <!-- Info Cards Section -->
    <div class="section-card" style="display:none;" >
        <h2>Info Cards (Customizable)</h2>
        <p style="color:#666; margin-bottom:20px;">Customize the three info cards that appear on your homepage (Free Shipping, Customer Support, Secure Payment).</p>
        
        <form method="post">
            <input type="hidden" name="action" value="update_info_cards">
            
            <?php for ($i = 1; $i <= 3; $i++): 
                $card = $infoCards[$i-1] ?? [];
                $titles = ['Free Shipping & Return', 'Customer Support 24/7', '100% Secure Payment'];
                $icons = ['🚚', '📞', '🔒'];
            ?>
            <h3 style="margin-top:<?php echo $i === 1 ? '0' : '24px'; ?>; margin-bottom:16px;">Card <?php echo $i; ?></h3>
            <div class="form-row">
                <div class="form-group">
                    <label>Icon/Emoji:</label>
                    <input type="text" name="card<?php echo $i; ?>_icon" value="<?php echo htmlspecialchars($card['icon'] ?? $icons[$i-1]); ?>" maxlength="5" required>
                    <div class="preview">Choose an emoji or icon character</div>
                </div>
                <div class="form-group">
                    <label>Title:</label>
                    <input type="text" name="card<?php echo $i; ?>_title" value="<?php echo htmlspecialchars($card['title'] ?? $titles[$i-1]); ?>" required>
                </div>
            </div>
            <div class="form-group">
                <label>Description:</label>
                <input type="text" name="card<?php echo $i; ?>_desc" value="<?php echo htmlspecialchars($card['description'] ?? ''); ?>" required>
            </div>
            <?php endfor; ?>
            
            <button type="submit" class="btn" style="margin-top:16px;">Save Info Cards</button>
        </form>
    </div>
</main>

<?php include __DIR__ . '/footer.php'; ?>
</body>
</html>
