<?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 json operations and file uploads
require_once __DIR__ . '/helpers/database_helper.php';

// load existing configuration
$config = DatabaseHelper::loadJson('customized_clothing.json', []);

// convenience vars
$sliderConfig = $config['slider'] ?? [];
$sectionConfig = $config['section'] ?? [];
$existingCats = $sectionConfig['categories'] ?? [];

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'update_slider') {
        // update hero slider title/description
        $sliderConfig['title'] = htmlspecialchars(trim($_POST['slider_title'] ?? ''));
        $sliderConfig['description'] = htmlspecialchars(trim($_POST['slider_description'] ?? ''));

        // manage slides (allow up to 5)
        $slides = [];
        for ($i = 1; $i <= 5; $i++) {
            $imgPath = htmlspecialchars(trim($_POST["slide_image_$i"] ?? ''));
            $altText = htmlspecialchars(trim($_POST["slide_alt_$i"] ?? ''));

            // file upload
            if (isset($_FILES["slide_file_$i"]) && $_FILES["slide_file_$i"]['size'] > 0) {
                try {
                    $uploadResult = DatabaseHelper::saveUploadedFile($_FILES["slide_file_$i"]);
                    if (is_array($uploadResult) && !empty($uploadResult['success']) && !empty($uploadResult['filename'])) {
                        $imgPath = $uploadResult['filename'];
                    } elseif (is_string($uploadResult)) {
                        $imgPath = $uploadResult;
                    }
                } catch (Exception $e) {
                    error_log("Customized clothing slider upload error: " . $e->getMessage());
                }
            }

            if (!empty($imgPath)) {
                $slides[] = ['image' => $imgPath, 'alt' => $altText];
            }
        }

        if (!empty($slides)) {
            $sliderConfig['slides'] = $slides;
        }

        // persist
        $config['slider'] = $sliderConfig;
        if (DatabaseHelper::saveJson('customized_clothing.json', $config)) {
            $message = 'Slider settings updated successfully!';
            $messageType = 'success';
        } else {
            $message = 'Error saving slider settings.';
            $messageType = 'error';
        }

    } elseif ($action === 'update_section') {
        $sectionConfig['title'] = htmlspecialchars(trim($_POST['section_title'] ?? ''));
        $sectionConfig['description'] = htmlspecialchars(trim($_POST['section_description'] ?? ''));

        $cats = [];
        // loop through a fixed number of category slots
        for ($i = 1; $i <= 5; $i++) {
            $catTitle = trim($_POST["cat{$i}_title"] ?? '');
            if ($catTitle === '') {
                // skip empty slot
                continue;
            }
            $catDesc = htmlspecialchars(trim($_POST["cat{$i}_desc"] ?? ''));
            $catImage = htmlspecialchars(trim($_POST["cat{$i}_image"] ?? ''));

            // upload category main 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'])) {
                        $catImage = $uploadResult['filename'];
                    } elseif (is_string($uploadResult)) {
                        $catImage = $uploadResult;
                    }
                } catch (Exception $e) {
                    error_log("Customized clothing category image upload error: " . $e->getMessage());
                }
            }

            // start gallery with existing if present
            $gallery = [];
            if (!empty($existingCats[$i - 1]['gallery']) && is_array($existingCats[$i - 1]['gallery'])) {
                $gallery = $existingCats[$i - 1]['gallery'];
            }

            // handle removal of existing gallery items
            if (!empty($_POST["cat{$i}_remove_gallery"]) && is_array($_POST["cat{$i}_remove_gallery"])) {
                foreach ($_POST["cat{$i}_remove_gallery"] as $remIndex) {
                    if (isset($gallery[$remIndex])) {
                        unset($gallery[$remIndex]);
                    }
                }
                // reindex
                $gallery = array_values($gallery);
            }

            // handle new gallery uploads
            if (isset($_FILES["cat{$i}_gallery_files"])) {
                $count = count($_FILES["cat{$i}_gallery_files"]['tmp_name']);
                for ($j = 0; $j < $count; $j++) {
                    if (!empty($_FILES["cat{$i}_gallery_files"]['tmp_name'][$j]) && $_FILES["cat{$i}_gallery_files"]['error'][$j] === UPLOAD_ERR_OK) {
                        try {
                            $fileArr = [
                                'name' => $_FILES["cat{$i}_gallery_files"]['name'][$j],
                                'tmp_name' => $_FILES["cat{$i}_gallery_files"]['tmp_name'][$j],
                                'error' => $_FILES["cat{$i}_gallery_files"]['error'][$j],
                                'size' => $_FILES["cat{$i}_gallery_files"]['size'][$j],
                                'type' => $_FILES["cat{$i}_gallery_files"]['type'][$j]
                            ];
                            $uploadResult = DatabaseHelper::saveUploadedFile($fileArr);
                            if (is_array($uploadResult) && !empty($uploadResult['success']) && !empty($uploadResult['filename'])) {
                                $gallery[] = ['image' => $uploadResult['filename'], 'alt' => ''];
                            } elseif (is_string($uploadResult)) {
                                $gallery[] = ['image' => $uploadResult, 'alt' => ''];
                            }
                        } catch (Exception $e) {
                            error_log("Customized clothing gallery upload error: " . $e->getMessage());
                        }
                    }
                }
            }

            $cats[] = [
                'id' => $i,
                'title' => htmlspecialchars($catTitle),
                'description' => $catDesc,
                'image' => $catImage,
                'gallery' => $gallery
            ];
        }

        $sectionConfig['categories'] = $cats;
        $config['section'] = $sectionConfig;

        if (DatabaseHelper::saveJson('customized_clothing.json', $config)) {
            $message = 'Section information saved successfully!';
            $messageType = 'success';
        } else {
            $message = 'Error saving section information.';
            $messageType = 'error';
        }
    }
}

// include 'admin_sidebar.php'; // sidebar omitted for simplicity
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Manage Customized Clothing Page</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, .form-group select { 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>
<main class="admin-container">
    <?php if (!empty($message)): ?>
        <div class="<?php echo $messageType === 'success' ? 'success' : 'error'; ?>"><?php echo htmlspecialchars($message); ?></div>
    <?php endif; ?>

    <a href="admin_dashboard.php" class="btn back-btn">← Back to Dashboard</a>

    <!-- Slider Section -->
    <div class="section-card">
        <h2>Slider Settings</h2>
        <form method="post" enctype="multipart/form-data">
            <input type="hidden" name="action" value="update_slider">
            <div class="form-group">
                <label>Section Title</label>
                <input type="text" name="slider_title" value="<?php echo htmlspecialchars($sliderConfig['title'] ?? ''); ?>">
            </div>
            <div class="form-group">
                <label>Section Description</label>
                <textarea name="slider_description"><?php echo htmlspecialchars($sliderConfig['description'] ?? ''); ?></textarea>
            </div>

            <?php for ($i = 1; $i <= 5; $i++): 
                $existingSlide = $sliderConfig['slides'][$i-1] ?? null;
            ?>
                <div class="section-card" style="padding:12px;">
                    <h3>Slide <?php echo $i; ?></h3>
                    <div class="form-group">
                        <label>Image URL</label>
                        <input type="text" name="slide_image_<?php echo $i; ?>" value="<?php echo htmlspecialchars($existingSlide['image'] ?? ''); ?>">
                    </div>
                    <div class="form-group">
                        <label>Alt text</label>
                        <input type="text" name="slide_alt_<?php echo $i; ?>" value="<?php echo htmlspecialchars($existingSlide['alt'] ?? ''); ?>">
                    </div>
                    <div class="form-group">
                        <label>Upload new file (optional)</label>
                        <input type="file" name="slide_file_<?php echo $i; ?>" accept="image/*">
                    </div>
                </div>
            <?php endfor; ?>
            <button class="btn" type="submit">Save Slider</button>
        </form>
    </div>

    <!-- Second Section (Categories) -->
    <div class="section-card">
        <h2>Second Section & Categories</h2>
        <form method="post" enctype="multipart/form-data">
            <input type="hidden" name="action" value="update_section">
            <div class="form-group">
                <label>Section Title</label>
                <input type="text" name="section_title" value="<?php echo htmlspecialchars($sectionConfig['title'] ?? ''); ?>">
            </div>
            <div class="form-group">
                <label>Section Description</label>
                <textarea name="section_description"><?php echo htmlspecialchars($sectionConfig['description'] ?? ''); ?></textarea>
            </div>

            <?php for ($i = 1; $i <= 5; $i++): 
                $cat = $existingCats[$i-1] ?? ['gallery'=>[]];
            ?>
                <div class="section-card" style="padding:12px;">
                    <h3>Category <?php echo $i; ?></h3>
                    <div class="form-group">
                        <label>Title</label>
                        <input type="text" name="cat<?php echo $i; ?>_title" value="<?php echo htmlspecialchars($cat['title'] ?? ''); ?>">
                    </div>
                    <div class="form-group">
                        <label>Description</label>
                        <textarea name="cat<?php echo $i; ?>_desc"><?php echo htmlspecialchars($cat['description'] ?? ''); ?></textarea>
                    </div>
                    <div class="form-group">
                        <label>Image URL</label>
                        <input type="text" name="cat<?php echo $i; ?>_image" value="<?php echo htmlspecialchars($cat['image'] ?? ''); ?>">
                    </div>
                    <div class="form-group">
                        <label>Upload new image (optional)</label>
                        <input type="file" name="cat_image_file_<?php echo $i; ?>" accept="image/*">
                    </div>

                    <?php if (!empty($cat['gallery']) && is_array($cat['gallery'])): ?>
                        <div class="form-group">
                            <label>Existing gallery images (check to remove)</label>
                            <div>
                                <?php foreach ($cat['gallery'] as $idx => $gimg): ?>
                                    <div style="display:inline-block; text-align:center; margin:4px;">
                                        <img src="<?php echo htmlspecialchars($gimg['image']); ?>" alt="" style="width:80px; height:80px; object-fit:cover; display:block;">
                                        <label><input type="checkbox" name="cat<?php echo $i; ?>_remove_gallery[]" value="<?php echo $idx; ?>"> Remove</label>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endif; ?>

                    <div class="form-group">
                        <label>Add gallery images (multiple files allowed)</label>
                        <input type="file" name="cat<?php echo $i; ?>_gallery_files[]" accept="image/*" multiple>
                    </div>
                </div>
            <?php endfor; ?>
            <button class="btn" type="submit">Save Section</button>
        </form>
    </div>

</main>
</body>
</html>