<?php
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

// Check if admin is logged in
if (empty($_SESSION['is_admin']) || $_SESSION['is_admin'] !== true) {
    header('Location: admin_login.php');
    exit;
}

// Load DatabaseHelper for cross-platform compatibility
require_once __DIR__ . '/helpers/database_helper.php';

// Load carousel settings using DatabaseHelper
$carousel = DatabaseHelper::loadJson('carousel.json', []);

$message = '';
$messageType = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Update carousel settings
    if (isset($_POST['action']) && $_POST['action'] === 'update_settings') {
        $carousel['enabled'] = isset($_POST['enabled']) ? true : false;
        $carousel['autoplay'] = isset($_POST['autoplay']) ? true : false;
        $carousel['autoplay_interval'] = (int)$_POST['autoplay_interval'] ?: 30000;
        $carousel['show_arrows'] = isset($_POST['show_arrows']) ? true : false;
        $carousel['show_dots'] = isset($_POST['show_dots']) ? true : false;
        
        if (DatabaseHelper::saveJson('carousel.json', $carousel)) {
            $message = 'Carousel settings updated successfully!';
            $messageType = 'success';
        } else {
            $message = 'Error saving carousel settings.';
            $messageType = 'error';
        }
    }
    
    // Update carousel items
    if (isset($_POST['action']) && $_POST['action'] === 'update_items') {
        $carousel['categories'] = [];
        
        for ($i = 1; $i <= 6; $i++) {
            if (!empty($_POST["cat_name_$i"])) {
                $imagePath = htmlspecialchars($_POST["cat_image_$i"]);
                
                // Handle file upload for carousel image
                if (isset($_FILES["cat_image_file_$i"]) && $_FILES["cat_image_file_$i"]['size'] > 0) {
                    try {
                        $uploadResult = DatabaseHelper::saveUploadedFile($_FILES["cat_image_file_$i"]);
                        if (is_array($uploadResult) && !empty($uploadResult['success']) && !empty($uploadResult['filename'])) {
                            $imagePath = $uploadResult['filename'];
                        } elseif (is_string($uploadResult)) {
                            $imagePath = $uploadResult;
                        }
                    } catch (Exception $e) {
                        error_log("Carousel image upload error: " . $e->getMessage());
                    }
                }
                
                $carousel['categories'][] = [
                    'id' => $i,
                    'name' => htmlspecialchars($_POST["cat_name_$i"]),
                    'image' => $imagePath,
                    'color' => htmlspecialchars($_POST["cat_color_$i"])
                ];
            }
        }
        
        if (DatabaseHelper::saveJson('carousel.json', $carousel)) {
            $message = 'Carousel items updated successfully!';
            $messageType = 'success';
        } else {
            $message = 'Error saving carousel items.';
            $messageType = 'error';
        }
    }
}

// include 'admin_sidebar.php';
?>

<style>
    .admin-content-area {
        padding: 30px;
         margin-left: 20%; 
        background: #f9f9f9;
        min-height: calc(100vh - 200px);
    }

    .admin-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 30px;
    }

    .admin-header h1 {
        font-size: 28px;
        margin: 0;
        color: #333;
    }

    .back-btn {
        background: #667eea;
        color: #fff;
        padding: 10px 20px;
        text-decoration: none;
        border-radius: 6px;
        font-size: 14px;
    }

    .back-btn:hover {
        background: #5568d3;
    }

    .message {
        padding: 15px 20px;
        border-radius: 6px;
        margin-bottom: 20px;
        font-weight: 600;
    }

    .message.success {
        background: #d4edda;
        color: #155724;
        border: 1px solid #c3e6cb;
    }

    .message.error {
        background: #f8d7da;
        color: #721c24;
        border: 1px solid #f5c6cb;
    }

    .form-section {
        background: #fff;
        padding: 25px;
        border-radius: 8px;
        margin-bottom: 25px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    }

    .form-section h2 {
        font-size: 18px;
        margin-top: 0;
        margin-bottom: 20px;
        color: #333;
        border-bottom: 2px solid #F07E2D;
        padding-bottom: 10px;
    }

    .form-group {
        margin-bottom: 20px;
    }

    .form-group label {
        display: block;
        margin-bottom: 8px;
        font-weight: 600;
        color: #333;
        font-size: 14px;
    }

    .form-group input[type="text"],
    .form-group input[type="number"],
    .form-group input[type="color"],
    .form-group input[type="file"],
    .form-group select {
        width: 100%;
        padding: 10px 12px;
        border: 1px solid #ddd;
        border-radius: 6px;
        font-size: 14px;
        font-family: inherit;
    }

    .form-group input[type="file"] {
        padding: 8px 12px;
        cursor: pointer;
    }

    .form-group input[type="text"]:focus,
    .form-group input[type="number"]:focus,
    .form-group input[type="color"]:focus,
    .form-group input[type="file"]:focus,
    .form-group select:focus {
        outline: none;
        border-color: #F07E2D;
        box-shadow: 0 0 0 3px rgba(225, 123, 169, 0.1);
    }

    .checkbox-group {
        display: flex;
        align-items: center;
        gap: 10px;
        margin-bottom: 15px;
    }

    .checkbox-group input[type="checkbox"] {
        width: 18px;
        height: 18px;
        cursor: pointer;
    }

    .checkbox-group label {
        margin: 0;
        cursor: pointer;
        font-weight: 500;
    }

    .carousel-items-container {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        gap: 20px;
        margin-top: 20px;
    }

    .carousel-item-form {
        border: 1px solid #ddd;
        border-radius: 8px;
        padding: 15px;
        background: #fafafa;
    }

    .carousel-item-form h3 {
        margin-top: 0;
        margin-bottom: 15px;
        font-size: 14px;
        color: #667eea;
    }

    .carousel-item-form .form-group {
        margin-bottom: 12px;
    }

    .carousel-item-form label {
        font-size: 12px;
        margin-bottom: 6px;
    }

    .carousel-item-form input {
        font-size: 13px;
        padding: 8px 10px;
    }

    .preview-box {
        margin-top: 15px;
        padding: 15px;
        border-radius: 6px;
        background: #f0f0f0;
        border: 1px solid #ddd;
        text-align: center;
        min-height: 150px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        color: #666;
        font-size: 13px;
    }

    .preview-box img {
        max-width: 100%;
        max-height: 120px;
        margin-bottom: 8px;
        border-radius: 4px;
    }

    .btn-group {
        display: flex;
        gap: 10px;
        margin-top: 25px;
        justify-content: flex-end;
    }

    .btn {
        padding: 12px 24px;
        border: none;
        border-radius: 6px;
        font-size: 14px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .btn-primary {
        background: #F07E2D;
        color: #fff;
    }

    .btn-primary:hover {
        background: #c76b8a;
    }

    .btn-secondary {
        background: #667eea;
        color: #fff;
    }

    .btn-secondary:hover {
        background: #5568d3;
    }

    .settings-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 20px;
        margin-bottom: 20px;
    }

    .settings-card {
        border: 1px solid #ddd;
        border-radius: 8px;
        padding: 15px;
        background: #fafafa;
    }

    .settings-card h3 {
        margin-top: 0;
        margin-bottom: 12px;
        font-size: 14px;
        color: #333;
    }

    .help-text {
        font-size: 12px;
        color: #999;
        margin-top: 5px;
    }
</style>
</head>
<!-- <body class="admin-with-sidebar"> -->
<!-- ?php include 'header.php'; ?> -->
<div class="admin-main-content">
<div class="admin-content-area">
    <div class="admin-header">
        <h1>Carousel Management</h1>

        <?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;
}
.back-btn:hover {
    background-color: darkorange;
}
</style>
        <!-- <a href="admin_dashboard.php" class="back-btn">← Back to Dashboard</a>
     -->
    </div>

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

    <!-- Carousel Settings Form -->
    <div class="form-section">
        <h2>Carousel Settings</h2>
        <form method="POST" action="">
            <input type="hidden" name="action" value="update_settings">
            
            <div class="checkbox-group">
                <input type="checkbox" id="enabled" name="enabled" <?php echo ($carousel['enabled'] ?? true) ? 'checked' : ''; ?>>
                <label for="enabled">Enable Carousel on Homepage</label>
            </div>

            <div class="checkbox-group">
                <input type="checkbox" id="autoplay" name="autoplay" <?php echo ($carousel['autoplay'] ?? true) ? 'checked' : ''; ?>>
                <label for="autoplay">Enable Autoplay</label>
            </div>

            <div class="form-group">
                <label for="autoplay_interval">Autoplay Interval (milliseconds)</label>
                <input type="number" id="autoplay_interval" name="autoplay_interval" value="<?php echo htmlspecialchars($carousel['autoplay_interval'] ?? 30000); ?>" min="5000" step="1000">
                <div class="help-text">Time between automatic carousel slides (e.g., 30000 = 30 seconds)</div>
            </div>

            <div class="checkbox-group">
                <input type="checkbox" id="show_arrows" name="show_arrows" <?php echo ($carousel['show_arrows'] ?? true) ? 'checked' : ''; ?>>
                <label for="show_arrows">Show Navigation Arrows</label>
            </div>

            <div class="checkbox-group">
                <input type="checkbox" id="show_dots" name="show_dots" <?php echo ($carousel['show_dots'] ?? true) ? 'checked' : ''; ?>>
                <label for="show_dots">Show Pagination Dots</label>
            </div>

            <div class="btn-group">
                <button type="submit" class="btn btn-primary">Save Settings</button>
            </div>
        </form>
    </div>

    <!-- Carousel Items Form -->
    <div class="form-section">
        <h2>Carousel Categories (Up to 6)</h2>
        <form method="POST" action="" enctype="multipart/form-data">
            <input type="hidden" name="action" value="update_items">
            
            <div class="carousel-items-container">
                <?php
                $categories = $carousel['categories'] ?? [];
                for ($i = 1; $i <= 6; $i++) {
                    $cat = $categories[$i - 1] ?? [];
                    ?>
                    <div class="carousel-item-form">
                        <h3>Category <?php echo $i; ?></h3>
                        
                        <div class="form-group">
                            <label for="cat_name_<?php echo $i; ?>">Category Name</label>
                            <input type="text" id="cat_name_<?php echo $i; ?>" name="cat_name_<?php echo $i; ?>" placeholder="e.g., Electronics" value="<?php echo htmlspecialchars($cat['name'] ?? ''); ?>">
                        </div>

                        <div class="form-group">
                            <label for="cat_image_<?php echo $i; ?>">Image URL</label>
                            <input type="text" id="cat_image_<?php echo $i; ?>" name="cat_image_<?php echo $i; ?>" placeholder="https://..." value="<?php echo htmlspecialchars($cat['image'] ?? ''); ?>">
                        </div>

                        <div class="form-group">
                            <label for="cat_image_file_<?php echo $i; ?>">Or Upload Image</label>
                            <input type="file" id="cat_image_file_<?php echo $i; ?>" name="cat_image_file_<?php echo $i; ?>" accept="image/*" placeholder="Choose image file">
                            <small style="color: #999; display: block; margin-top: 5px;">Supported formats: JPG, PNG, GIF, WebP (Max 5MB)</small>
                        </div>

                        <div class="form-group">
                            <label for="cat_color_<?php echo $i; ?>">Overlay Color</label>
                            <input type="color" id="cat_color_<?php echo $i; ?>" name="cat_color_<?php echo $i; ?>" value="<?php echo htmlspecialchars($cat['color'] ?? '#667eea'); ?>">
                        </div>

                        <?php if (!empty($cat['image'])): ?>
                        <div class="preview-box">
                            <img src="<?php echo htmlspecialchars($cat['image']); ?>" alt="<?php echo htmlspecialchars($cat['name']); ?>" onload="this.style.display='block'" onerror="this.style.display='none'">
                            <span><?php echo htmlspecialchars($cat['name']); ?></span>
                        </div>
                        <?php else: ?>
                        <div class="preview-box">
                            No image
                        </div>
                        <?php endif; ?>
                    </div>
                    <?php
                }
                ?>
            </div>

            <div class="btn-group">
                <button type="submit" class="btn btn-primary">Save Categories</button>
            </div>
        </form>
    </div>

    <div style="margin-top: 30px; padding: 20px; background: #e3f2fd; border-radius: 8px; border-left: 4px solid #667eea; color: #1565c0; font-size: 13px;">
        <strong>💡 Tip:</strong> Categories appear in a scrolling carousel on the homepage. Users can manually click arrows or it auto-scrolls every X seconds. Use high-quality images (recommended size: 400x250px) and ensure category names are short and descriptive.
    </div>
</div>

