<?php
$pageTitle = 'Website CMS';
require_once __DIR__ . '/includes/header.php';

$db = Database::getInstance();

$settings = [];
$allSettings = $db->query("SELECT * FROM website_settings ORDER BY group_name, id ASC")->fetchAll();
foreach ($allSettings as $s) {
    $settings[$s['setting_key']] = $s['setting_value'];
}

$sections = $db->query("SELECT * FROM website_sections ORDER BY sort_order ASC")->fetchAll();

$activeTab = $_GET['tab'] ?? 'general';
?>

<ul class="nav nav-tabs mb-3">
    <li class="nav-item"><a class="nav-link <?php echo $activeTab === 'general' ? 'active' : ''; ?>" href="?tab=general">General</a></li>
    <li class="nav-item"><a class="nav-link <?php echo $activeTab === 'contact' ? 'active' : ''; ?>" href="?tab=contact">Contact</a></li>
    <li class="nav-item"><a class="nav-link <?php echo $activeTab === 'social' ? 'active' : ''; ?>" href="?tab=social">Social Media</a></li>
    <li class="nav-item"><a class="nav-link <?php echo $activeTab === 'seo' ? 'active' : ''; ?>" href="?tab=seo">SEO</a></li>
    <li class="nav-item"><a class="nav-link <?php echo $activeTab === 'appearance' ? 'active' : ''; ?>" href="?tab=appearance">Appearance</a></li>
    <li class="nav-item"><a class="nav-link <?php echo $activeTab === 'sections' ? 'active' : ''; ?>" href="?tab=sections">Sections</a></li>
</ul>

<?php if ($activeTab === 'sections'): ?>
<div class="form-card">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h6 class="mb-0">Website Sections</h6>
        <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addSectionModal"><i class="fas fa-plus me-1"></i>Add Section</button>
    </div>
    <div class="table-responsive">
        <table class="table table-hover">
            <thead class="table-light">
                <tr><th>Sort</th><th>Key</th><th>Title</th><th>Subtitle</th><th>Active</th><th>Actions</th></tr>
            </thead>
            <tbody>
                <?php foreach ($sections as $sec): ?>
                <tr>
                    <td><?php echo $sec['sort_order']; ?></td>
                    <td><code><?php echo sanitize($sec['section_key']); ?></code></td>
                    <td><?php echo sanitize($sec['title'] ?? ''); ?></td>
                    <td><?php echo sanitize($sec['subtitle'] ?? ''); ?></td>
                    <td><span class="badge bg-<?php echo $sec['is_active'] ? 'success' : 'secondary'; ?>"><?php echo $sec['is_active'] ? 'Active' : 'Inactive'; ?></span></td>
                    <td>
                        <button class="btn btn-sm btn-outline-primary btn-action edit-section-btn"
                            data-id="<?php echo $sec['id']; ?>"
                            data-title="<?php echo sanitize($sec['title'] ?? ''); ?>"
                            data-subtitle="<?php echo sanitize($sec['subtitle'] ?? ''); ?>"
                            data-content="<?php echo sanitize($sec['content'] ?? ''); ?>"
                            data-active="<?php echo $sec['is_active']; ?>"
                            data-sort="<?php echo $sec['sort_order']; ?>"><i class="fas fa-edit"></i></button>
                        <button class="btn btn-sm btn-outline-danger btn-action delete-section-btn" data-id="<?php echo $sec['id']; ?>"><i class="fas fa-trash"></i></button>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<div class="modal fade" id="editSectionModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header"><h5 class="modal-title">Edit Section</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <form id="editSectionForm">
                <div class="modal-body">
                    <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                    <input type="hidden" name="action" value="save_section">
                    <input type="hidden" name="section_id" id="edit_section_id">
                    <div class="mb-3"><label class="form-label">Title</label><input type="text" class="form-control" name="title" id="edit_section_title"></div>
                    <div class="mb-3"><label class="form-label">Subtitle</label><input type="text" class="form-control" name="subtitle" id="edit_section_subtitle"></div>
                    <div class="mb-3"><label class="form-label">Content</label><textarea class="form-control" name="content" id="edit_section_content" rows="4"></textarea></div>
                    <div class="row g-3">
                        <div class="col-6"><label class="form-label">Sort Order</label><input type="number" class="form-control" name="sort_order" id="edit_section_sort"></div>
                        <div class="col-6"><div class="form-check mt-4"><input class="form-check-input" type="checkbox" name="is_active" id="edit_section_active" value="1"><label class="form-check-label">Active</label></div></div>
                    </div>
                </div>
                <div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button><button type="submit" class="btn btn-primary">Save</button></div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="addSectionModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header"><h5 class="modal-title">Add Section</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <form id="addSectionForm">
                <div class="modal-body">
                    <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                    <input type="hidden" name="action" value="add_section">
                    <div class="mb-3"><label class="form-label">Section Key <span class="text-danger">*</span></label><input type="text" class="form-control" name="section_key" required placeholder="e.g. my_section"></div>
                    <div class="mb-3"><label class="form-label">Title</label><input type="text" class="form-control" name="title"></div>
                    <div class="mb-3"><label class="form-label">Subtitle</label><input type="text" class="form-control" name="subtitle"></div>
                </div>
                <div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button><button type="submit" class="btn btn-primary">Add</button></div>
            </form>
        </div>
    </div>
</div>

<script>
document.querySelectorAll('.edit-section-btn').forEach(function(btn) {
    btn.addEventListener('click', function() {
        document.getElementById('edit_section_id').value = this.dataset.id;
        document.getElementById('edit_section_title').value = this.dataset.title;
        document.getElementById('edit_section_subtitle').value = this.dataset.subtitle;
        document.getElementById('edit_section_content').value = this.dataset.content;
        document.getElementById('edit_section_sort').value = this.dataset.sort;
        document.getElementById('edit_section_active').checked = this.dataset.active == '1';
        new bootstrap.Modal(document.getElementById('editSectionModal')).show();
    });
});

function handleSectionForm(formId) {
    document.getElementById(formId).addEventListener('submit', function(e) {
        e.preventDefault();
        var formData = new FormData(this);
        fetch(BASE_URL + '/admin/cms_save.php', { method: 'POST', body: new URLSearchParams(formData) })
        .then(function(r) { return r.json(); })
        .then(function(data) {
            if (data.success) { showAlert('success', data.message); setTimeout(function() { location.reload(); }, 1000); }
            else { showAlert('danger', data.message); }
        });
    });
}
handleSectionForm('editSectionForm');
handleSectionForm('addSectionForm');

document.querySelectorAll('.delete-section-btn').forEach(function(btn) {
    btn.addEventListener('click', function() {
        var id = this.dataset.id;
        if (confirm('Delete this section?')) {
            ajaxPost(BASE_URL + '/admin/cms_save.php', 'action=delete_section&section_id=' + id + '&csrf_token=' + encodeURIComponent(CSRF_TOKEN), function(data) {
                if (data.success) { showAlert('success', data.message); setTimeout(function() { location.reload(); }, 1000); }
                else { showAlert('danger', data.message); }
            });
        }
    });
});
</script>

<?php else: ?>

<div class="form-card">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h6 class="mb-0"><?php echo ucfirst($activeTab); ?> Settings</h6>
    </div>
    <form id="cmsSettingsForm">
        <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
        <?php
        $fields = [];
        if ($activeTab === 'general') {
            $fields = ['site_name','site_tagline','site_description','site_logo','site_favicon','copyright_text'];
        } elseif ($activeTab === 'contact') {
            $fields = ['contact_email','contact_phone','contact_whatsapp','contact_address'];
        } elseif ($activeTab === 'social') {
            $fields = ['social_facebook','social_instagram','social_twitter','social_linkedin','social_youtube'];
        } elseif ($activeTab === 'seo') {
            $fields = ['meta_title','meta_description','meta_keywords','google_analytics_id','facebook_pixel_id'];
        } elseif ($activeTab === 'appearance') {
            $fields = ['primary_color','secondary_color','accent_color'];
        }

        foreach ($fields as $field):
            $value = $settings[$field] ?? '';
            $label = ucwords(str_replace(['_','-'], ' ', $field));
            $inputType = 'text';
            if (strpos($field, 'color') !== false) { $inputType = 'color'; }
            elseif (strpos($field, 'description') !== false || strpos($field, 'keywords') !== false) { $inputType = 'textarea'; }
        ?>
        <div class="mb-3">
            <label class="form-label"><?php echo $label; ?></label>
            <?php if ($inputType === 'textarea'): ?>
                <textarea class="form-control" name="settings[<?php echo $field; ?>]" rows="3"><?php echo sanitize($value); ?></textarea>
            <?php else: ?>
                <input type="<?php echo $inputType; ?>" class="form-control" name="settings[<?php echo $field; ?>]" value="<?php echo sanitize($value); ?>">
            <?php endif; ?>
        </div>
        <?php endforeach; ?>

        <button type="submit" class="btn btn-primary"><i class="fas fa-save me-1"></i>Save Settings</button>
    </form>
</div>

<script>
document.getElementById('cmsSettingsForm').addEventListener('submit', function(e) {
    e.preventDefault();
    var formData = new FormData(this);
    var settingsObj = {};
    for (var pair of formData.entries()) {
        if (pair[0].startsWith('settings[')) {
            var key = pair[0].replace('settings[', '').replace(']', '');
            settingsObj[key] = pair[1];
        }
    }
    var payload = 'csrf_token=' + encodeURIComponent(CSRF_TOKEN) + '&settings=' + encodeURIComponent(JSON.stringify(settingsObj));
    fetch(BASE_URL + '/admin/cms_save.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest'}, body: payload })
    .then(function(r) { return r.json(); })
    .then(function(data) {
        if (data.success) { showAlert('success', data.message); }
        else { showAlert('danger', data.message); }
    });
});
</script>

<?php endif; ?>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
