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

// ----- Why choose us form submit -----
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_why_choose'])) {
    $stmt = $pdo->prepare("INSERT INTO site_settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
    $stmt->execute(['why_choose_title', trim($_POST['why_choose_title'] ?? ''), trim($_POST['why_choose_title'] ?? '')]);
    $stmt->execute(['why_choose_lead', trim($_POST['why_choose_lead'] ?? ''), trim($_POST['why_choose_lead'] ?? '')]);
    $stmt->execute(['why_choose_list', trim($_POST['why_choose_list'] ?? ''), trim($_POST['why_choose_list'] ?? '')]);
    $stmt->execute(['why_choose_btn_text', trim($_POST['why_choose_btn_text'] ?? ''), trim($_POST['why_choose_btn_text'] ?? '')]);
    $stmt->execute(['why_choose_btn_url', trim($_POST['why_choose_btn_url'] ?? ''), trim($_POST['why_choose_btn_url'] ?? '')]);
    if (!empty($_POST['remove_why_choose_image'])) {
        $stmt->execute(['why_choose_image', '', '']);
    }
    if (!empty($_FILES['why_choose_image']['name']) && $_FILES['why_choose_image']['error'] === UPLOAD_ERR_OK) {
        $ext = strtolower(pathinfo($_FILES['why_choose_image']['name'], PATHINFO_EXTENSION));
        if (in_array($ext, ['jpg','jpeg','png','gif','webp'])) {
            $name = 'why_choose_' . time() . '.' . $ext;
            if (move_uploaded_file($_FILES['why_choose_image']['tmp_name'], $homeDir . $name)) {
                $stmt->execute(['why_choose_image', $name, $name]);
            }
        }
    }
    header('Location: home-blocks.php?saved=1#why-choose');
    exit;
}

// ----- Features section title/sub -----
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_features_heading'])) {
    $stmt = $pdo->prepare("INSERT INTO site_settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
    $stmt->execute(['features_section_title', trim($_POST['features_section_title'] ?? ''), trim($_POST['features_section_title'] ?? '')]);
    $stmt->execute(['features_section_sub', trim($_POST['features_section_sub'] ?? ''), trim($_POST['features_section_sub'] ?? '')]);
    header('Location: home-blocks.php?saved=1#features');
    exit;
}

// ----- Feature: delete -----
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['delete_feature_id'])) {
    $id = (int)$_POST['delete_feature_id'];
    try {
        $row = $pdo->prepare("SELECT icon_type, icon_value FROM home_features WHERE id = ?");
        $row->execute([$id]);
        $r = $row->fetch(PDO::FETCH_ASSOC);
        if ($r && $r['icon_type'] === 'image' && $r['icon_value'] && is_file($homeDir . $r['icon_value'])) {
            @unlink($homeDir . $r['icon_value']);
        }
        $pdo->prepare("DELETE FROM home_features WHERE id = ?")->execute([$id]);
    } catch (Exception $e) {}
    header('Location: home-blocks.php?saved=1#features');
    exit;
}

// ----- Feature: add / update -----
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_feature'])) {
    $id = isset($_POST['feature_id']) ? (int)$_POST['feature_id'] : 0;
    $title = trim($_POST['feature_title'] ?? '');
    $description = trim($_POST['feature_description'] ?? '');
    $icon_type = ($_POST['feature_icon_type'] ?? '') === 'image' ? 'image' : 'emoji';
    $icon_value = $icon_type === 'emoji' ? trim($_POST['feature_icon_emoji'] ?? '') : '';
    $color_class = preg_replace('/[^a-z0-9_-]/', '', $_POST['feature_color'] ?? 'teal');
    $sort_order = (int)($_POST['feature_sort'] ?? 0);
    if ($title !== '') {
        if ($icon_type === 'image') {
            if (!empty($_FILES['feature_icon_image']['name']) && $_FILES['feature_icon_image']['error'] === UPLOAD_ERR_OK) {
                $ext = strtolower(pathinfo($_FILES['feature_icon_image']['name'], PATHINFO_EXTENSION));
                if (in_array($ext, ['jpg','jpeg','png','gif','webp','svg'])) {
                    $name = 'feature_icon_' . time() . '_' . ($id ?: 0) . '.' . $ext;
                    if (move_uploaded_file($_FILES['feature_icon_image']['tmp_name'], $homeDir . $name)) {
                        $icon_value = $name;
                    }
                }
            } elseif ($id > 0) {
                $cur = $pdo->prepare("SELECT icon_value FROM home_features WHERE id = ?");
                $cur->execute([$id]);
                $row = $cur->fetch(PDO::FETCH_ASSOC);
                if ($row && !empty($row['icon_value'])) $icon_value = $row['icon_value'];
            }
        }
        if ($id > 0) {
            $stmt = $pdo->prepare("UPDATE home_features SET title=?, description=?, icon_type=?, icon_value=?, sort_order=?, color_class=? WHERE id=?");
            $stmt->execute([$title, $description, $icon_type, $icon_value ?: null, $sort_order, $color_class ?: null, $id]);
        } else {
            $stmt = $pdo->prepare("INSERT INTO home_features (title, description, icon_type, icon_value, sort_order, color_class, is_active) VALUES (?,?,?,?,?,?,1)");
            $stmt->execute([$title, $description, $icon_type, $icon_value ?: null, $sort_order, $color_class ?: null]);
        }
    }
    header('Location: home-blocks.php?saved=1#features');
    exit;
}

$featuresTitle = getSetting('features_section_title', 'Why businesses choose us');
$featuresSub = getSetting('features_section_sub', 'Quality corrugated solutions from one reliable partner.');
$whyChooseTitle = getSetting('why_choose_title', 'Why choose us?');
$whyChooseLead = getSetting('why_choose_lead', '');
$whyChooseList = getSetting('why_choose_list', '');
$whyChooseBtnText = getSetting('why_choose_btn_text', 'About us');
$whyChooseBtnUrl = getSetting('why_choose_btn_url', 'about.php');
$whyChooseImage = getSetting('why_choose_image', '');

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

$pageTitle = 'Home blocks';
require_once __DIR__ . '/includes/header.php';
?>
<div class="admin-page">
    <h1>Home page blocks</h1>
    <p>Manage &quot;Why businesses choose us&quot; and &quot;Why choose us?&quot; sections.</p>
    <?php if (isset($_GET['saved'])): ?><p class="success">Saved.</p><?php endif; ?>

    <section id="features" style="margin-top:28px;">
        <h2>Why businesses choose us</h2>
        <form method="post" class="admin-form">
            <input type="hidden" name="save_features_heading" value="1">
            <label>Section title</label>
            <input type="text" name="features_section_title" value="<?php echo htmlspecialchars($featuresTitle); ?>">
            <label>Section subtitle</label>
            <input type="text" name="features_section_sub" value="<?php echo htmlspecialchars($featuresSub); ?>">
            <button type="submit" class="btn">Save heading</button>
        </form>

        <h3 style="margin-top:24px;">Feature cards</h3>
        <table class="admin-table" style="margin-bottom:20px;">
            <thead><tr><th>Icon</th><th>Title</th><th>Color</th><th>Order</th><th>Actions</th></tr></thead>
            <tbody>
            <?php foreach ($features as $f): ?>
                <tr>
                    <td>
                        <?php if (($f['icon_type'] ?? '') === 'image' && !empty($f['icon_value']) && is_file($homeDir . $f['icon_value'])): ?>
                            <img src="<?php echo htmlspecialchars(ADMIN_SITE_ROOT); ?>/uploads/home/<?php echo htmlspecialchars($f['icon_value']); ?>" alt="" style="max-width:48px; max-height:48px; object-fit:contain;">
                        <?php else: ?>
                            <span style="font-size:1.5rem;"><?php echo htmlspecialchars($f['icon_value'] ?? '—'); ?></span>
                        <?php endif; ?>
                    </td>
                    <td><?php echo htmlspecialchars($f['title']); ?></td>
                    <td><?php echo htmlspecialchars($f['color_class'] ?? '—'); ?></td>
                    <td><?php echo (int)$f['sort_order']; ?></td>
                    <td>
                        <a href="home-blocks.php?edit=<?php echo (int)$f['id']; ?>#feature-form" class="btn btn-secondary">Edit</a>
                        <form method="post" style="display:inline;" onsubmit="return confirm('Delete this feature?');">
                            <input type="hidden" name="delete_feature_id" value="<?php echo (int)$f['id']; ?>">
                            <button type="submit" class="btn btn-secondary">Delete</button>
                        </form>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>

        <div id="feature-form">
            <h3><?php echo isset($_GET['edit']) ? 'Edit feature' : 'Add feature'; ?></h3>
            <?php
            $edit = null;
            if (!empty($_GET['edit'])) {
                foreach ($features as $f) { if ((int)$f['id'] === (int)$_GET['edit']) { $edit = $f; break; } }
            }
            ?>
            <form method="post" enctype="multipart/form-data" class="admin-form">
                <input type="hidden" name="save_feature" value="1">
                <?php if ($edit): ?><input type="hidden" name="feature_id" value="<?php echo (int)$edit['id']; ?>"><?php endif; ?>
                <label>Title</label>
                <input type="text" name="feature_title" value="<?php echo $edit ? htmlspecialchars($edit['title']) : ''; ?>" required>
                <label>Description</label>
                <textarea name="feature_description" rows="3"><?php echo $edit ? htmlspecialchars($edit['description']) : ''; ?></textarea>
                <label>Icon type</label>
                <select name="feature_icon_type" id="feature_icon_type">
                    <option value="emoji" <?php echo ($edit && ($edit['icon_type'] ?? '') === 'image') ? '' : 'selected'; ?>>Emoji</option>
                    <option value="image" <?php echo ($edit && ($edit['icon_type'] ?? '') === 'image') ? 'selected' : ''; ?>>Image / icon</option>
                </select>
                <div id="feature-emoji-wrap">
                    <label>Emoji (e.g. 📦 ⚙️ 🌱)</label>
                    <input type="text" name="feature_icon_emoji" value="<?php echo ($edit && ($edit['icon_type'] ?? '') !== 'image') ? htmlspecialchars($edit['icon_value'] ?? '') : ''; ?>" maxlength="20" placeholder="📦">
                </div>
                <div id="feature-image-wrap" style="display:none;">
                    <label>Upload icon/image</label>
                    <input type="file" name="feature_icon_image" accept="image/*">
                    <?php if ($edit && ($edit['icon_type'] ?? '') === 'image' && !empty($edit['icon_value'])): ?>
                        <p><img src="<?php echo htmlspecialchars(ADMIN_SITE_ROOT); ?>/uploads/home/<?php echo htmlspecialchars($edit['icon_value']); ?>" alt="" style="max-width:80px;"></p>
                    <?php endif; ?>
                </div>
                <label>Color class</label>
                <select name="feature_color">
                    <option value="teal" <?php echo ($edit['color_class'] ?? '') === 'teal' ? 'selected' : ''; ?>>Teal</option>
                    <option value="amber" <?php echo ($edit['color_class'] ?? '') === 'amber' ? 'selected' : ''; ?>>Amber</option>
                    <option value="violet" <?php echo ($edit['color_class'] ?? '') === 'violet' ? 'selected' : ''; ?>>Violet</option>
                </select>
                <label>Sort order</label>
                <input type="number" name="feature_sort" value="<?php echo $edit ? (int)$edit['sort_order'] : count($features); ?>">
                <button type="submit" class="btn"><?php echo $edit ? 'Update' : 'Add'; ?> feature</button>
                <?php if ($edit): ?><a href="home-blocks.php#feature-form" class="btn btn-secondary">Cancel</a><?php endif; ?>
            </form>
        </div>
    </section>

    <hr style="margin:40px 0 28px; border:0; border-top:1px solid #e2e8f0;">
    <section id="why-choose">
        <h2>Why choose us?</h2>
        <form method="post" enctype="multipart/form-data" class="admin-form">
            <input type="hidden" name="save_why_choose" value="1">
            <label>Title</label>
            <input type="text" name="why_choose_title" value="<?php echo htmlspecialchars($whyChooseTitle); ?>">
            <label>Lead paragraph</label>
            <textarea name="why_choose_lead" rows="2"><?php echo htmlspecialchars($whyChooseLead); ?></textarea>
            <label>List items (one per line)</label>
            <textarea name="why_choose_list" rows="5"><?php echo htmlspecialchars($whyChooseList); ?></textarea>
            <label>Button text</label>
            <input type="text" name="why_choose_btn_text" value="<?php echo htmlspecialchars($whyChooseBtnText); ?>">
            <label>Button URL (e.g. about.php)</label>
            <input type="text" name="why_choose_btn_url" value="<?php echo htmlspecialchars($whyChooseBtnUrl); ?>">
            <label>Section image (optional)</label>
            <?php if ($whyChooseImage && is_file($homeDir . $whyChooseImage)): ?>
                <p><img src="<?php echo htmlspecialchars(ADMIN_SITE_ROOT); ?>/uploads/home/<?php echo htmlspecialchars($whyChooseImage); ?>" alt="" style="max-width:200px; border-radius:8px;"></p>
                <label><input type="checkbox" name="remove_why_choose_image" value="1"> Remove image</label><br><br>
            <?php endif; ?>
            <input type="file" name="why_choose_image" accept="image/*">
            <button type="submit" class="btn">Save Why choose us</button>
        </form>
    </section>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
    var sel = document.getElementById('feature_icon_type');
    var emojiWrap = document.getElementById('feature-emoji-wrap');
    var imageWrap = document.getElementById('feature-image-wrap');
    function toggle() {
        var isImage = sel && sel.value === 'image';
        if (emojiWrap) emojiWrap.style.display = isImage ? 'none' : 'block';
        if (imageWrap) imageWrap.style.display = isImage ? 'block' : 'none';
    }
    if (sel) { sel.addEventListener('change', toggle); toggle(); }
});
</script>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
