<?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;
}

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

// Load carousel settings and categories
$carousel = DatabaseHelper::loadJson('carousel.json', []);
$allCategories = DatabaseHelper::loadJson('categories.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'] ?: 5000;
        $carousel['items_per_view'] = (int)$_POST['items_per_view'] ?: 4;
        
        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'] = [];
        $categories = DatabaseHelper::loadJson('categories.json', []);
        
        for ($i = 1; $i <= 10; $i++) {
            if (!empty($_POST["cat_name_$i"])) {
                $catName = htmlspecialchars($_POST["cat_name_$i"]);
                $imagePath = htmlspecialchars($_POST["cat_image_$i"]);
                
                // Handle file upload
                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("Category carousel image upload error: " . $e->getMessage());
                    }
                }
                
                // Auto-create category if it doesn't exist
                $categoryExists = false;
                foreach ($categories as $cat) {
                    if ($cat['name'] === $catName) {
                        $categoryExists = true;
                        break;
                    }
                }
                
                if (!$categoryExists) {
                    $categories[] = ['name' => $catName];
                    DatabaseHelper::saveJson('categories.json', $categories);
                }
                
                $carousel['categories'][] = [
                    'id' => $i,
                    'name' => $catName,
                    'image' => $imagePath,
                    'category_url' => htmlspecialchars($_POST["cat_url_$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;
        border-radius: 6px;
        margin-bottom: 20px;
        font-weight: 500;
    }

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

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

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

    .section-title {
        font-size: 20px;
        font-weight: 600;
        margin-bottom: 20px;
        color: #333;
    }

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

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

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

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

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

    .submit-btn {
        background: #667eea;
        color: #fff;
        padding: 12px 30px;
        border: none;
        border-radius: 4px;
        font-size: 14px;
        font-weight: 600;
        cursor: pointer;
        transition: background 0.3s ease;
    }

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

    .item-card {
        background: #f9f9f9;
        padding: 20px;
        border-radius: 6px;
        margin-bottom: 20px;
        border: 1px solid #e0e0e0;
    }

    .item-card h4 {
        margin: 0 0 15px 0;
        color: #333;
        font-size: 16px;
    }

    .form-row {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 15px;
    }

    .preview-image {
        width: 120px;
        height: 120px;
        border-radius: 6px;
        object-fit: cover;
        margin-top: 10px;
        border: 1px solid #ddd;
    }
</style>

<div class="admin-content-area">
    <div class="admin-header">
        <h1>Manage Category Carousel</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 htmlspecialchars($messageType); ?>">
        <?php echo htmlspecialchars($message); ?>
    </div>
    <?php endif; ?>

    <!-- Settings Section -->
    <div class="settings-section">
        <h3 class="section-title">Carousel Settings</h3>
        <form method="POST">
            <input type="hidden" name="action" value="update_settings">
            
            <div class="form-group">
                <div class="checkbox-group">
                    <input type="checkbox" id="enabled" name="enabled" <?php echo (!empty($carousel['enabled']) ? 'checked' : ''); ?>>
                    <label for="enabled" style="margin-bottom: 0;">Enable Carousel</label>
                </div>
            </div>

            <div class="form-group">
                <div class="checkbox-group">
                    <input type="checkbox" id="autoplay" name="autoplay" <?php echo (!empty($carousel['autoplay']) ? 'checked' : ''); ?>>
                    <label for="autoplay" style="margin-bottom: 0;">Enable Autoplay</label>
                </div>
            </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'] ?? 5000); ?>" min="1000">
            </div>

            <div class="form-group">
                <label for="items_per_view">Items Per View</label>
                <input type="number" id="items_per_view" name="items_per_view" value="<?php echo htmlspecialchars($carousel['items_per_view'] ?? 4); ?>" min="1" max="10">
            </div>

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

    <!-- Items Section -->
    <div class="items-section">
        <h3 class="section-title">Carousel Categories (Add up to 10)</h3>
        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="action" value="update_items">
            
            <?php
            $categories = $carousel['categories'] ?? [];
            for ($i = 1; $i <= 10; $i++):
                $cat = $categories[$i - 1] ?? [];
            ?>
            <div class="item-card">
                <h4>Category <?php echo $i; ?></h4>
                
                <div class="form-row">
                    <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; ?>" 
                               value="<?php echo htmlspecialchars($cat['name'] ?? ''); ?>" 
                               placeholder="e.g., Watches">
                    </div>

                    <div class="form-group">
                        <label for="cat_image_<?php echo $i; ?>">Upload Image or Image URL</label>
                        <input type="file" id="cat_image_file_<?php echo $i; ?>" name="cat_image_file_<?php echo $i; ?>" accept="image/*" placeholder="Choose image">
                        <small style="color: #999; display: block; margin: 5px 0;">Or enter URL below:</small>
                        <input type="text" id="cat_image_<?php echo $i; ?>" name="cat_image_<?php echo $i; ?>" 
                               value="<?php echo htmlspecialchars($cat['image'] ?? ''); ?>" 
                               placeholder="e.g., uploads/watch.webp or https://...">
                        <?php if (!empty($cat['image'])): ?>
                        <img src="<?php echo htmlspecialchars($cat['image']); ?>" alt="Preview" class="preview-image" onerror="this.style.display='none'">
                        <?php endif; ?>
                    </div>

                    <div class="form-group">
                        <label for="cat_url_<?php echo $i; ?>">Category URL</label>
                        <input type="text" id="cat_url_<?php echo $i; ?>" name="cat_url_<?php echo $i; ?>" 
                               value="<?php echo htmlspecialchars($cat['category_url'] ?? ''); ?>" 
                               placeholder="e.g., category.php?cat=Watches">
                    </div>
                </div>
            </div>
            <?php endfor; ?>

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