<?php
require_once __DIR__ . '/config.php';
requireAdmin();
$pdo = getDB();
$sectionKey = 'client_section';
$homeDir = dirname(__DIR__) . '/uploads/home/';
if (!is_dir($homeDir)) @mkdir($homeDir, 0755, true);

function normalizeHomeUrl($url) {
    $url = trim((string)$url);
    if ($url === '') return '';
    // Allow absolute URLs and normal relative links
    return $url;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // ----- Hero slider: delete -----
    if (!empty($_POST['delete_hero_slide_id'])) {
        $id = (int)$_POST['delete_hero_slide_id'];
        try {
            $stmt = $pdo->prepare("SELECT image FROM home_hero_slides WHERE id = ? LIMIT 1");
            $stmt->execute([$id]);
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($row && !empty($row['image']) && is_file($homeDir . $row['image'])) @unlink($homeDir . $row['image']);
            $pdo->prepare("DELETE FROM home_hero_slides WHERE id = ?")->execute([$id]);
        } catch (Exception $e) {}
        header('Location: home-sections.php?saved=1#hero-slider');
        exit;
    }

    // ----- Hero slider: add / update -----
    if (isset($_POST['save_hero_slide'])) {
        $id = isset($_POST['hero_slide_id']) ? (int)$_POST['hero_slide_id'] : 0;
        $eyebrow = trim($_POST['hero_eyebrow'] ?? '');
        $title = trim($_POST['hero_title'] ?? '');
        $subtitle = trim($_POST['hero_subtitle'] ?? '');
        $description = trim($_POST['hero_description'] ?? '');
        $buttonText = trim($_POST['hero_button_text'] ?? '');
        $buttonUrl = normalizeHomeUrl($_POST['hero_button_url'] ?? '');
        $sort = (int)($_POST['hero_sort'] ?? 0);
        $active = !empty($_POST['hero_active']) ? 1 : 0;

        if (true) {
            $imageName = '';
            if (!empty($_FILES['hero_image']['name']) && ($_FILES['hero_image']['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_OK) {
                $ext = strtolower(pathinfo($_FILES['hero_image']['name'], PATHINFO_EXTENSION));
                if (in_array($ext, ['jpg','jpeg','png','gif','webp'])) {
                    $imageName = 'hero_slide_' . time() . '_' . ($id ?: 0) . '.' . $ext;
                    if (!move_uploaded_file($_FILES['hero_image']['tmp_name'], $homeDir . $imageName)) {
                        $imageName = '';
                    }
                }
            } elseif ($id > 0) {
                try {
                    $cur = $pdo->prepare("SELECT image FROM home_hero_slides WHERE id = ? LIMIT 1");
                    $cur->execute([$id]);
                    $row = $cur->fetch(PDO::FETCH_ASSOC);
                    if ($row && !empty($row['image'])) $imageName = $row['image'];
                } catch (Exception $e) {}
            }

            if ($imageName !== '') {
                if ($title === '') $title = getSetting('site_name', 'CRIMSON');
                try {
                    if ($id > 0) {
                        $stmt = $pdo->prepare("UPDATE home_hero_slides SET eyebrow=?, title=?, subtitle=?, description=?, button_text=?, button_url=?, image=?, sort_order=?, is_active=? WHERE id=?");
                        $stmt->execute([
                            $eyebrow !== '' ? $eyebrow : null,
                            $title,
                            $subtitle !== '' ? $subtitle : null,
                            $description !== '' ? $description : null,
                            $buttonText !== '' ? $buttonText : null,
                            $buttonUrl !== '' ? $buttonUrl : null,
                            $imageName,
                            $sort,
                            $active,
                            $id
                        ]);
                    } else {
                        $stmt = $pdo->prepare("INSERT INTO home_hero_slides (eyebrow, title, subtitle, description, button_text, button_url, image, sort_order, is_active) VALUES (?,?,?,?,?,?,?,?,?)");
                        $stmt->execute([
                            $eyebrow !== '' ? $eyebrow : null,
                            $title,
                            $subtitle !== '' ? $subtitle : null,
                            $description !== '' ? $description : null,
                            $buttonText !== '' ? $buttonText : null,
                            $buttonUrl !== '' ? $buttonUrl : null,
                            $imageName,
                            $sort,
                            $active
                        ]);
                    }
                } catch (Exception $e) {}
            }
        }

        header('Location: home-sections.php?saved=1#hero-slider');
        exit;
    }

    // Delete a strip image
    if (!empty($_POST['delete_image_id'])) {
        $deleteId = (int)$_POST['delete_image_id'];
        try {
            $stmt = $pdo->prepare("SELECT image FROM section_images WHERE id = ? AND section_key = ? LIMIT 1");
            $stmt->execute([$deleteId, $sectionKey]);
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($row && !empty($row['image'])) {
                $path = dirname(__DIR__) . '/uploads/home/' . $row['image'];
                if (is_file($path)) @unlink($path);
            }
            $pdo->prepare("DELETE FROM section_images WHERE id = ? AND section_key = ?")->execute([$deleteId, $sectionKey]);
        } catch (Exception $e) { /* table missing */ }
        header('Location: home-sections.php?saved=1');
        exit;
    }

    // Save strip image list (caption/sort/active)
    if (!empty($_POST['save_images']) && !empty($_POST['img_caption']) && is_array($_POST['img_caption'])) {
        try {
            $stmt = $pdo->prepare("UPDATE section_images SET caption=?, sort_order=?, is_active=? WHERE id=? AND section_key=?");
            foreach ($_POST['img_caption'] as $imgId => $captionRaw) {
                $imgId = (int)$imgId;
                $caption = trim((string)$captionRaw);
                $sort = isset($_POST['img_sort'][$imgId]) ? (int)$_POST['img_sort'][$imgId] : 0;
                $active = !empty($_POST['img_active'][$imgId]) ? 1 : 0;
                $stmt->execute([$caption, $sort, $active, $imgId, $sectionKey]);
            }
        } catch (Exception $e) { /* table missing */ }
        header('Location: home-sections.php?saved=1');
        exit;
    }

    $headline = trim($_POST['client_section_headline'] ?? '');
    $subtext = trim($_POST['client_section_subtext'] ?? '');
    $stmt = $pdo->prepare("INSERT INTO site_settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
    $stmt->execute(['client_section_headline', $headline, $headline]);
    $stmt->execute(['client_section_subtext', $subtext, $subtext]);

    // Upload multiple images for scroll strip
    if (!empty($_FILES['client_images']['name']) && is_array($_FILES['client_images']['name'])) {
        $dir = dirname(__DIR__) . '/uploads/home/';
        if (!is_dir($dir)) @mkdir($dir, 0755, true);
        try {
            $ins = $pdo->prepare("INSERT INTO section_images (section_key, image, caption, sort_order, is_active) VALUES (?,?,?,?,1)");
            foreach ($_FILES['client_images']['name'] as $idx => $orig) {
                if (empty($orig)) continue;
                $tmp = $_FILES['client_images']['tmp_name'][$idx] ?? '';
                if (!$tmp) continue;
                $ext = strtolower(pathinfo($orig, PATHINFO_EXTENSION));
                if (!in_array($ext, ['jpg','jpeg','png','gif','webp'])) continue;
                $name = 'client_strip_' . time() . '_' . $idx . '.' . $ext;
                if (move_uploaded_file($tmp, $dir . $name)) {
                    $ins->execute([$sectionKey, $name, '', 0]);
                }
            }
        } catch (Exception $e) { /* table missing */ }
    }

    if (!empty($_FILES['client_image']['name'])) {
        $ext = strtolower(pathinfo($_FILES['client_image']['name'], PATHINFO_EXTENSION));
        if (in_array($ext, ['jpg','jpeg','png','gif','webp'])) {
            $name = 'client_' . time() . '.' . $ext;
            $dir = dirname(__DIR__) . '/uploads/home/';
            if (!is_dir($dir)) mkdir($dir, 0755, true);
            if (move_uploaded_file($_FILES['client_image']['tmp_name'], $dir . $name)) {
                $stmt->execute(['client_section_image', $name, $name]);
            }
        }
    }
    if (!empty($_POST['remove_image'])) {
        $stmt->execute(['client_section_image', '', '']);
    }
    header('Location: home-sections.php?saved=1');
    exit;
}

$heroSlides = [];
$heroSlidesSupported = true;
try {
    $heroSlides = $pdo->query("SELECT * FROM home_hero_slides ORDER BY sort_order, id")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $heroSlides = []; $heroSlidesSupported = false; }

$headline = getSetting('client_section_headline', '');
$subtext = getSetting('client_section_subtext', '');
$image = getSetting('client_section_image', '');
$stripImages = [];
$imagesSupported = true;
try {
    $stmt = $pdo->prepare("SELECT id, image, caption, sort_order, is_active FROM section_images WHERE section_key = ? ORDER BY sort_order, id");
    $stmt->execute([$sectionKey]);
    $stripImages = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $stripImages = []; $imagesSupported = false; }
$pageTitle = 'Home — Client section';
require_once __DIR__ . '/includes/header.php';
?>
<div class="admin-page">
    <h1>Home page sections</h1>
    <?php if (isset($_GET['saved'])): ?><p class="success">Saved.</p><?php endif; ?>

    <section id="hero-slider">
        <h2 style="margin-top:0;">Hero section — Slider banners</h2>
        <p>Manage multiple hero banners (image + text + button). Text/button will appear on top of the banner on the homepage.</p>
        <?php if (!$heroSlidesSupported): ?>
            <p class="error">Hero slider is not available. Please run `database/migrate_home_hero_slides.sql` in your database.</p>
        <?php else: ?>
            <?php if (!empty($heroSlides)): ?>
                <h3 style="margin-top:18px;">Slides list</h3>
                <div style="overflow:auto; border:1px solid #e2e8f0; border-radius:12px; padding:12px;">
                    <table class="admin-table" style="min-width:980px;">
                        <thead><tr><th>Preview</th><th>Title</th><th>Button</th><th>Order</th><th>Active</th><th>Actions</th></tr></thead>
                        <tbody>
                        <?php foreach ($heroSlides as $s): ?>
                            <tr>
                                <td style="width:210px;">
                                    <?php if (!empty($s['image']) && is_file($homeDir . $s['image'])): ?>
                                        <img src="<?php echo htmlspecialchars(ADMIN_SITE_ROOT); ?>/uploads/home/<?php echo htmlspecialchars($s['image']); ?>" alt="" style="max-width:190px; max-height:90px; object-fit:contain; background:#0b1220; border-radius:10px;">
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <div style="font-weight:700;"><?php echo htmlspecialchars($s['title'] ?? ''); ?></div>
                                    <div class="muted" style="font-size:0.9rem;"><?php echo htmlspecialchars($s['subtitle'] ?? ''); ?></div>
                                </td>
                                <td>
                                    <div><?php echo htmlspecialchars($s['button_text'] ?? ''); ?></div>
                                    <div class="muted" style="font-size:0.9rem;"><?php echo htmlspecialchars($s['button_url'] ?? ''); ?></div>
                                </td>
                                <td style="width:90px;"><?php echo (int)($s['sort_order'] ?? 0); ?></td>
                                <td style="width:90px; text-align:center;"><?php echo !empty($s['is_active']) ? 'Yes' : 'No'; ?></td>
                                <td style="width:220px;">
                                    <a href="home-sections.php?edit_hero=<?php echo (int)$s['id']; ?>#hero-form" class="btn btn-secondary">Edit</a>
                                    <form method="post" style="display:inline;" onsubmit="return confirm('Delete this slide?');">
                                        <input type="hidden" name="delete_hero_slide_id" value="<?php echo (int)$s['id']; ?>">
                                        <button type="submit" class="btn btn-secondary">Delete</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <p class="muted">No slides yet. Add your first slide below.</p>
            <?php endif; ?>

            <div id="hero-form" style="margin-top:18px;">
                <?php
                $editHero = null;
                if (!empty($_GET['edit_hero'])) {
                    foreach ($heroSlides as $s) { if ((int)$s['id'] === (int)$_GET['edit_hero']) { $editHero = $s; break; } }
                }
                ?>
                <h3><?php echo $editHero ? 'Edit slide' : 'Add slide'; ?></h3>
                <form method="post" enctype="multipart/form-data" class="admin-form">
                    <input type="hidden" name="save_hero_slide" value="1">
                    <?php if ($editHero): ?><input type="hidden" name="hero_slide_id" value="<?php echo (int)$editHero['id']; ?>"><?php endif; ?>
                    <label>Top tag / eyebrow (optional)</label>
                    <input type="text" name="hero_eyebrow" value="<?php echo htmlspecialchars($editHero['eyebrow'] ?? ''); ?>" placeholder="Trusted packaging partner">
                    <label>Title (optional) — if empty, site name will be used</label>
                    <input type="text" name="hero_title" value="<?php echo htmlspecialchars($editHero['title'] ?? ''); ?>" placeholder="<?php echo htmlspecialchars(getSetting('site_name', 'CRIMSON')); ?>">
                    <label>Subtitle (optional)</label>
                    <input type="text" name="hero_subtitle" value="<?php echo htmlspecialchars($editHero['subtitle'] ?? ''); ?>" placeholder="Manufacturer of Corrugated Boxes">
                    <label>Description (optional)</label>
                    <textarea name="hero_description" rows="3" placeholder="Short supporting line..."><?php echo htmlspecialchars($editHero['description'] ?? ''); ?></textarea>
                    <label>Button text (optional)</label>
                    <input type="text" name="hero_button_text" value="<?php echo htmlspecialchars($editHero['button_text'] ?? ''); ?>" placeholder="Get a Quote">
                    <label>Button URL (optional)</label>
                    <input type="text" name="hero_button_url" value="<?php echo htmlspecialchars($editHero['button_url'] ?? ''); ?>" placeholder="enquiry.php or https://...">
                    <label>Banner image (required)</label>
                    <p class="muted" style="margin:0 0 8px; font-size:0.85rem;">Recommended hero banner size: <strong>1920×900</strong> (16:9). Minimum: <strong>1400×700</strong>.</p>
                    <?php if ($editHero && !empty($editHero['image']) && is_file($homeDir . $editHero['image'])): ?>
                        <p><img src="<?php echo htmlspecialchars(ADMIN_SITE_ROOT); ?>/uploads/home/<?php echo htmlspecialchars($editHero['image']); ?>" alt="" style="max-width:100%; max-height:220px; object-fit:contain; background:#0b1220; border-radius:12px; border:1px solid #e2e8f0;"></p>
                    <?php endif; ?>
                    <input type="file" name="hero_image" accept="image/*" <?php echo $editHero ? '' : 'required'; ?>>
                    <label>Sort order</label>
                    <input type="number" name="hero_sort" value="<?php echo $editHero ? (int)($editHero['sort_order'] ?? 0) : count($heroSlides); ?>">
                    <label style="margin-top:10px;"><input type="checkbox" name="hero_active" value="1" <?php echo ($editHero ? !empty($editHero['is_active']) : true) ? 'checked' : ''; ?>> Active</label>
                    <button type="submit" class="btn"><?php echo $editHero ? 'Update' : 'Add'; ?> slide</button>
                    <?php if ($editHero): ?><a href="home-sections.php#hero-form" class="btn btn-secondary">Cancel</a><?php endif; ?>
                </form>
            </div>
        <?php endif; ?>
    </section>

    <hr style="margin:32px 0 24px; border:0; border-top:1px solid #e2e8f0;">
    <h2>Client section</h2>
    <p>Headline, subtext and optional image appear above the stats row on the homepage.</p>
    <form method="post" enctype="multipart/form-data" class="admin-form">
        <label>Headline</label>
        <textarea name="client_section_headline" rows="3" placeholder="A ONE STOP SOLUTION..."><?php echo htmlspecialchars($headline); ?></textarea>
        <label>Subtext (italic on site)</label>
        <textarea name="client_section_subtext" rows="4"><?php echo htmlspecialchars($subtext); ?></textarea>
        <label>Scroll images (multiple)</label>
        <?php if (!$imagesSupported): ?>
            <p class="error">Multi-image strip is not available. Please run `database/migrate_section_images.sql` in your database.</p>
        <?php endif; ?>
        <p class="muted">Upload multiple images. They will show as a horizontal scroll strip on the homepage client section.</p>
        <p class="muted" style="margin:0 0 8px; font-size:0.85rem;">Recommended size: <strong>600×300</strong> (2:1) per image. Use PNG with transparent background for logos.</p>
        <input type="file" name="client_images[]" accept="image/*" multiple>
        <label>Section image (optional)</label>
        <?php if ($image && is_file(dirname(__DIR__) . '/uploads/home/' . $image)): ?>
        <p><img src="<?php echo ADMIN_SITE_ROOT; ?>/uploads/home/<?php echo htmlspecialchars($image); ?>" alt="" style="max-width:200px;"></p>
        <label><input type="checkbox" name="remove_image" value="1"> Remove image</label>
        <?php endif; ?>
        <p class="muted" style="margin:0 0 8px; font-size:0.85rem;">Recommended size: <strong>900×700</strong> (approx). Use a clean product/brand image.</p>
        <input type="file" name="client_image" accept="image/*">
        <button type="submit" class="btn">Save</button>
    </form>
    <?php if (!empty($stripImages)): ?>
        <h2 style="margin-top:26px;">Scroll images list</h2>
        <form method="post" class="admin-form" onsubmit="return true;">
            <input type="hidden" name="save_images" value="1">
            <div style="overflow:auto; border:1px solid #e2e8f0; border-radius:12px; padding:12px;">
                <table class="admin-table" style="min-width:760px;">
                    <thead><tr><th>Preview</th><th>Caption</th><th>Sort</th><th>Active</th><th>Delete</th></tr></thead>
                    <tbody>
                    <?php foreach ($stripImages as $img): ?>
                        <tr>
                            <td style="width:150px;">
                                <?php if (!empty($img['image']) && is_file(dirname(__DIR__) . '/uploads/home/' . $img['image'])): ?>
                                    <img src="<?php echo ADMIN_SITE_ROOT; ?>/uploads/home/<?php echo htmlspecialchars($img['image']); ?>" alt="" style="max-width:130px; border-radius:10px;">
                                <?php endif; ?>
                            </td>
                            <td>
                                <input type="text" name="img_caption[<?php echo (int)$img['id']; ?>]" value="<?php echo htmlspecialchars($img['caption'] ?? ''); ?>" placeholder="Optional caption">
                            </td>
                            <td style="width:90px;"><input type="number" name="img_sort[<?php echo (int)$img['id']; ?>]" value="<?php echo (int)$img['sort_order']; ?>" style="width:80px;"></td>
                            <td style="width:90px; text-align:center;"><input type="checkbox" name="img_active[<?php echo (int)$img['id']; ?>]" value="1" <?php echo !empty($img['is_active']) ? 'checked' : ''; ?>></td>
                            <td style="width:120px;">
                                <button type="submit" name="delete_image_id" value="<?php echo (int)$img['id']; ?>" class="btn btn-secondary" onclick="return confirm('Delete this image?');">Delete</button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <button type="submit" class="btn" style="margin-top:10px;">Save list</button>
        </form>
    <?php endif; ?>
    <p><a href="stats.php">Manage stat counters</a></p>
</div>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
