<?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 latest products settings
$latestProducts = DatabaseHelper::loadJson('latest_products.json', []);

// Load all products
$allProducts = DatabaseHelper::loadJson('products.json', []);

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

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action']) && $_POST['action'] === 'update_settings') {
        $latestProducts['enabled'] = isset($_POST['enabled']) ? true : false;
        $latestProducts['title'] = htmlspecialchars($_POST['title'] ?? 'Latest Arrivals');
        $latestProducts['description'] = htmlspecialchars($_POST['description'] ?? 'Check out our newest collection');
        $latestProducts['show_description'] = isset($_POST['show_description']) ? true : false;
        $latestProducts['display_count'] = min((int)$_POST['display_count'] ?? 6, 12);
        
        // Process selected product IDs
        $selectedIds = [];
        for ($i = 1; $i <= 12; $i++) {
            if (isset($_POST["product_$i"])) {
                $selectedIds[] = (int)$_POST["product_$i"];
            }
        }
        $latestProducts['product_ids'] = $selectedIds ?: [1, 2, 3, 4, 5, 6];
        
        if (DatabaseHelper::saveJson('latest_products.json', $latestProducts)) {
            $message = 'Latest products settings updated successfully!';
            $messageType = 'success';
        } else {
            $message = 'Error saving latest products settings.';
            $messageType = 'error';
        }
    }
}

include 'admin_sidebar.php';
?>

<style>
    .admin-content-area {
        padding: 30px;
        margin-left: 320px;
        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 textarea,
    .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="text"]:focus,
    .form-group input[type="number"]:focus,
    .form-group textarea:focus,
    .form-group select:focus {
        outline: none;
        border-color: #F07E2D;
        box-shadow: 0 0 0 3px rgba(225, 123, 169, 0.1);
    }

    .form-group textarea {
        resize: vertical;
        min-height: 60px;
    }

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

    .products-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
        gap: 15px;
        margin-top: 20px;
    }

    .product-item {
        border: 2px solid #ddd;
        border-radius: 8px;
        padding: 12px;
        text-align: center;
        cursor: pointer;
        transition: all 0.3s ease;
        background: #fafafa;
    }

    .product-item:hover {
        border-color: #F07E2D;
        background: #fff5f8;
    }

    .product-item input[type="checkbox"] {
        display: none;
    }

    .product-item input[type="checkbox"]:checked + .product-info {
        color: #F07E2D;
    }

    .product-item input[type="checkbox"]:checked ~ .checkmark {
        display: flex;
    }

    .product-info {
        pointer-events: none;
    }

    .product-item img {
        width: 100%;
        height: 100px;
        object-fit: cover;
        border-radius: 4px;
        margin-bottom: 8px;
    }

    .product-item h4 {
        margin: 8px 0 4px;
        font-size: 12px;
        font-weight: 600;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: #333;
    }

    .product-item .price {
        font-size: 13px;
        color: #F07E2D;
        font-weight: 600;
    }

    .product-item .product-id {
        font-size: 11px;
        color: #999;
    }

    .checkmark {
        position: absolute;
        top: 10px;
        right: 10px;
        width: 24px;
        height: 24px;
        background: #F07E2D;
        border-radius: 50%;
        display: none;
        align-items: center;
        justify-content: center;
        color: #fff;
        font-size: 14px;
        font-weight: bold;
    }

    .product-item {
        position: relative;
    }

    .form-row {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 20px;
    }

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

    .help-text {
        font-size: 12px;
        color: #999;
        margin-top: 5px;
    }

    .info-box {
        background: #e3f2fd;
        border-left: 4px solid #667eea;
        padding: 15px;
        border-radius: 4px;
        margin-top: 20px;
        font-size: 13px;
        color: #1565c0;
    }

    @media (max-width: 768px) {
        .form-row {
            grid-template-columns: 1fr;
        }

        .products-grid {
            grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
        }
    }
</style>

<div class="admin-content-area">
    <div class="admin-header">
        <h1>Latest Products Management</h1>
        <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; ?>

    <!-- Latest Products Settings Form -->
    <div class="form-section">
        <h2>Latest Products 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 ($latestProducts['enabled'] ?? true) ? 'checked' : ''; ?>>
                <label for="enabled">Enable Latest Products Section on Homepage</label>
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label for="title">Section Title</label>
                    <input type="text" id="title" name="title" value="<?php echo htmlspecialchars($latestProducts['title'] ?? 'Latest Arrivals'); ?>" placeholder="e.g., Latest Arrivals">
                </div>

                <div class="form-group">
                    <label for="display_count">Display Count</label>
                    <input type="number" id="display_count" name="display_count" value="<?php echo htmlspecialchars($latestProducts['display_count'] ?? 6); ?>" min="1" max="12">
                    <div class="help-text">Maximum 12 products can be displayed</div>
                </div>
            </div>

            <div class="form-group">
                <label for="description">Section Description</label>
                <textarea id="description" name="description" placeholder="Brief description of latest products"><?php echo htmlspecialchars($latestProducts['description'] ?? 'Check out our newest collection'); ?></textarea>
            </div>

            <div class="checkbox-group">
                <input type="checkbox" id="show_description" name="show_description" <?php echo ($latestProducts['show_description'] ?? true) ? 'checked' : ''; ?>>
                <label for="show_description">Show Description Below Title</label>
            </div>

            <div style="border-top: 1px solid #e0e0e0; padding-top: 20px; margin-top: 20px;">
                <h3 style="margin-top: 0; color: #333; font-size: 14px;">Select Products (Choose up to 12)</h3>
                <p style="font-size: 13px; color: #666; margin-bottom: 15px;">Click on products to select them for the latest products section. Selected products will appear in the order you choose them.</p>

                <div class="products-grid">
                    <?php
                    foreach ($allProducts as $product) {
                        $prodId = $product['id'] ?? 0;
                        $prodTitle = htmlspecialchars($product['title'] ?? 'Product');
                        $prodPrice = htmlspecialchars($product['price'] ?? '0');
                        $prodImage = !empty($product['image']) ? htmlspecialchars($product['image']) : 'pics_ecom/placeholder.png';
                        $isSelected = in_array($prodId, $latestProducts['product_ids'] ?? []);
                        ?>
                        <label class="product-item">
                            <input type="checkbox" name="product_<?php echo $prodId; ?>" value="<?php echo $prodId; ?>" <?php echo $isSelected ? 'checked' : ''; ?>>
                            <div class="product-info">
                                <img src="<?php echo $prodImage; ?>" alt="<?php echo $prodTitle; ?>" onerror="this.src='pics_ecom/placeholder.png'">
                                <h4><?php echo $prodTitle; ?></h4>
                                <div class="price">$<?php echo $prodPrice; ?></div>
                                <div class="product-id">#<?php echo $prodId; ?></div>
                            </div>
                            <div class="checkmark">✓</div>
                        </label>
                        <?php
                    }
                    ?>
                </div>
            </div>

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

    <div class="info-box">
        <strong>💡 Info:</strong>
        <ul style="margin: 8px 0; padding-left: 20px;">
            <li>Up to 12 products can be selected and displayed</li>
            <li>Products appear in the order they are selected</li>
            <li>Enable/disable the section without losing your selection</li>
            <li>Changes appear on the homepage immediately</li>
        </ul>
    </div>
</div>

