<?php
include 'admin-header.php';

// Fetch all settings for the page
$result = $conn->query("SELECT * FROM site_settings");
$settings = [];
while ($row = $result->fetch_assoc()) {
    $settings[$row['setting_name']] = $row['setting_value'];
}
function selected($val1, $val2) { if ($val1 == $val2) echo 'selected'; }
?>
<style>
    /* Styles for live image previews and other UI enhancements */
    .image-preview-container {
        position: relative; display: inline-block;
        min-height: 80px; width: 100%; max-width: 250px;
        border: 2px dashed var(--bs-border-color);
        border-radius: .375rem; background-color: var(--bs-tertiary-bg);
    }
    .image-preview {
        max-width: 100%; max-height: 100px; padding: 5px;
    }
    .nav-pills .nav-link { text-align: left; }
</style>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">Site Settings</h1>
    <div class="text-muted small">
        <i class="bi bi-cloud-check-fill text-success"></i> Changes are saved automatically.
    </div>
</div>

<div id="toast-container" style="position: fixed; top: 20px; right: 20px; z-index: 1055;"></div>

<div class="row">
    <div class="col-md-3">
        <div class="nav flex-column nav-pills" role="tablist" aria-orientation="vertical">
            <button class="nav-link active" data-bs-toggle="pill" data-bs-target="#tab-general" type="button"><i class="bi bi-gear-fill me-2"></i>General</button>
            <button class="nav-link" data-bs-toggle="pill" data-bs-target="#tab-branding" type="button"><i class="bi bi-gem me-2"></i>Branding & Theme</button>
            <button class="nav-link" data-bs-toggle="pill" data-bs-target="#tab-announcements" type="button"><i class="bi bi-megaphone-fill me-2"></i>Announcements</button>
            <button class="nav-link" data-bs-toggle="pill" data-bs-target="#tab-payments" type="button"><i class="bi bi-credit-card-2-front-fill me-2"></i>Payment Gateways</button>
            <button class="nav-link" data-bs-toggle="pill" data-bs-target="#tab-email" type="button"><i class="bi bi-envelope-at-fill me-2"></i>Email (SMTP)</button>
            <button class="nav-link" data-bs-toggle="pill" data-bs-target="#tab-apis" type="button"><i class="bi bi-key-fill me-2"></i>API Credentials</button>
        </div>
    </div>

    <div class="col-md-9">
        <div class="tab-content">

            <div class="tab-pane fade show active" id="tab-general" role="tabpanel">
                <div class="card shadow-sm"><div class="card-header fw-bold">General Settings</div><div class="card-body">
                    <div class="mb-3"><label class="form-label">Site Name</label><input type="text" class="form-control setting-input" name="site_name" value="<?php echo htmlspecialchars($settings['site_name'] ?? ''); ?>"></div>
                    <div class="mb-3"><label class="form-label">Footer Copyright Text</label><textarea class="form-control setting-input" name="site_footer_text"><?php echo htmlspecialchars($settings['site_footer_text'] ?? 'Copyright © {year} Your Company. All Rights Reserved.'); ?></textarea><small class="text-muted">Use <code>{year}</code> for the current year.</small></div>
                    <hr>
                    <div class="mb-3"><label class="form-label">Website Timezone</label><select class="form-select setting-input" name="site_timezone"><?php $current_tz = $settings['site_timezone'] ?? 'Asia/Manila'; foreach (DateTimeZone::listIdentifiers(DateTimeZone::ALL) as $tz) { echo '<option value="'.$tz.'"'.($tz == $current_tz ? ' selected' : '').'>'.$tz.'</option>'; } ?></select></div>
                </div></div>
            </div>

            <div class="tab-pane fade" id="tab-branding" role="tabpanel">
                <div class="card shadow-sm"><div class="card-header fw-bold">Branding & Theme</div><div class="card-body">
                    <div class="mb-4"><label class="form-label fw-medium">Site Color Theme</label><?php $current_theme = $settings['site_theme'] ?? 'auto'; ?>
                        <div class="form-check"><input class="form-check-input setting-input" type="radio" name="site_theme" value="light" <?php if($current_theme=='light') echo 'checked';?>><label class="form-check-label">Light Mode</label></div>
                        <div class="form-check"><input class="form-check-input setting-input" type="radio" name="site_theme" value="dark" <?php if($current_theme=='dark') echo 'checked';?>><label class="form-check-label">Dark Mode</label></div>
                        <div class="form-check"><input class="form-check-input setting-input" type="radio" name="site_theme" value="auto" <?php if($current_theme=='auto') echo 'checked';?>><label class="form-check-label">Auto (User's system preference)</label></div>
                    </div><hr>
                    <div class="row pt-2">
                        <div class="col-md-6 mb-3"><label class="form-label">Main Logo</label><input type="file" class="form-control image-upload-input" data-setting-name="site_logo_url" data-preview-id="logo-preview"><div class="image-preview-container mt-2"><img id="logo-preview" src="/<?php echo htmlspecialchars($settings['site_logo_url'] ?? ''); ?>" class="image-preview" style="<?php if(empty($settings['site_logo_url'])) echo 'display:none;'; ?>"></div></div>
                        <div class="col-md-6 mb-3"><label class="form-label">Light Logo (for dark BG)</label><input type="file" class="form-control image-upload-input" data-setting-name="site_logo_light_url" data-preview-id="logo-light-preview"><div class="image-preview-container mt-2 bg-dark"><img id="logo-light-preview" src="/<?php echo htmlspecialchars($settings['site_logo_light_url'] ?? ''); ?>" class="image-preview" style="<?php if(empty($settings['site_logo_light_url'])) echo 'display:none;'; ?>"></div></div>
                    </div><hr>
                    <div class="row pt-2">
                        <div class="col-md-6 mb-3"><label class="form-label">Favicon</label><input type="file" class="form-control image-upload-input" data-setting-name="favicon" data-preview-id="favicon-preview"><div class="image-preview-container mt-2"><img id="favicon-preview" src="/favicon-32x32.png?v=<?php echo time();?>" class="image-preview"></div><small class="text-muted">Upload a square image. Will be resized.</small></div>
                        <div class="col-md-6 mb-3"><label class="form-label">Homepage Background</label><input type="file" class="form-control image-upload-input" data-setting-name="hero_background_url" data-preview-id="hero-preview"><div class="image-preview-container mt-2"><img id="hero-preview" src="/<?php echo htmlspecialchars($settings['hero_background_url'] ?? ''); ?>" class="image-preview" style="<?php if(empty($settings['hero_background_url'])) echo 'display:none;'; ?>"></div></div>
                    </div>
                </div></div>
            </div>

            <div class="tab-pane fade" id="tab-announcements" role="tabpanel">
                <div class="card shadow-sm"><div class="card-header fw-bold">Announcement Bar</div><div class="card-body">
                    <div class="form-check form-switch mb-3"><input class="form-check-input setting-input" type="checkbox" role="switch" name="announcement_bar_enabled" value="1" <?php echo ($settings['announcement_bar_enabled'] ?? 0) == 1 ? 'checked' : ''; ?>><label class="form-check-label">Show Announcement Bar on Website</label></div>
                    <div class="mb-3"><label class="form-label">Announcement Text</label><input type="text" class="form-control setting-input" name="announcement_bar_text" value="<?php echo htmlspecialchars($settings['announcement_bar_text'] ?? ''); ?>"></div>
                    <div class="mb-3"><label class="form-label">Bar Color Style</label><select class="form-select setting-input" name="announcement_bar_color"><option value="primary" <?php selected($settings['announcement_bar_color'] ?? '','primary'); ?>>Blue</option><option value="success" <?php selected($settings['announcement_bar_color'] ?? '','success'); ?>>Green</option><option value="warning" <?php selected($settings['announcement_bar_color'] ?? '','warning'); ?>>Yellow</option><option value="danger" <?php selected($settings['announcement_bar_color'] ?? '','danger'); ?>>Red</option><option value="dark" <?php selected($settings['announcement_bar_color'] ?? '','dark'); ?>>Black</option></select></div>
                </div></div>
            </div>
            
            <div class="tab-pane fade" id="tab-payments" role="tabpanel">
                <div class="card shadow-sm"><div class="card-header fw-bold">Payment Gateways</div><div class="card-body">
                    <h5>PayMongo</h5>
                    <div class="form-check form-switch mb-3"><input class="form-check-input setting-input" type="checkbox" role="switch" name="paymongo_enabled" value="1" <?php echo ($settings['paymongo_enabled'] ?? 0) == 1 ? 'checked' : ''; ?>><label class="form-check-label">Enable PayMongo</label></div>
                    <div class="mb-3"><label class="form-label">PayMongo Public Key</label><input type="text" class="form-control setting-input" name="paymongo_public_key" value="<?php echo htmlspecialchars($settings['paymongo_public_key'] ?? ''); ?>"></div>
                    <div class="mb-3"><label class="form-label">PayMongo Secret Key</label><div class="input-group"><input type="password" class="form-control setting-input" name="paymongo_secret_key" value="<?php echo htmlspecialchars($settings['paymongo_secret_key'] ?? ''); ?>"><button class="btn btn-outline-secondary toggle-visibility" type="button"><i class="bi bi-eye-fill"></i></button></div></div>
                    <hr>
                    <h5 class="mt-4">PayPal</h5>
                    <div class="form-check form-switch mb-3"><input class="form-check-input setting-input" type="checkbox" role="switch" name="paypal_enabled" value="1" <?php echo ($settings['paypal_enabled'] ?? 0) == 1 ? 'checked' : ''; ?>><label class="form-check-label">Enable PayPal</label></div>
                    <div class="form-check form-switch mb-3"><input class="form-check-input setting-input" type="checkbox" role="switch" name="paypal_sandbox_mode" value="1" <?php echo ($settings['paypal_sandbox_mode'] ?? 0) == 1 ? 'checked' : ''; ?>><label class="form-check-label">Enable PayPal Sandbox (Testing)</label></div>
                    <div class="mb-3"><label class="form-label">PayPal Client ID</label><input type="text" class="form-control setting-input" name="paypal_client_id" value="<?php echo htmlspecialchars($settings['paypal_client_id'] ?? ''); ?>"></div>
                </div></div>
            </div>
            
            <div class="tab-pane fade" id="tab-email" role="tabpanel">
                <div class="card shadow-sm"><div class="card-header fw-bold">Email (SMTP) Settings</div><div class="card-body">
                    <p class="text-muted small">Configure a real email account for reliable system email delivery.</p>
                    <div class="mb-3"><label class="form-label">SMTP Host</label><input type="text" class="form-control setting-input" name="smtp_host" value="<?php echo htmlspecialchars($settings['smtp_host'] ?? 'smtp.gmail.com'); ?>"></div>
                    <div class="mb-3"><label class="form-label">SMTP Port</label><input type="text" class="form-control setting-input" name="smtp_port" value="<?php echo htmlspecialchars($settings['smtp_port'] ?? '587'); ?>"></div>
                    <div class="mb-3"><label class="form-label">SMTP Encryption</label><input type="text" class="form-control setting-input" name="smtp_secure" value="<?php echo htmlspecialchars($settings['smtp_secure'] ?? 'tls'); ?>"><small>Use 'tls' or 'ssl'</small></div>
                    <div class="mb-3"><label class="form-label">SMTP Username (Email)</label><input type="email" class="form-control setting-input" name="smtp_user" value="<?php echo htmlspecialchars($settings['smtp_user'] ?? ''); ?>"></div>
                    <div class="mb-3"><label class="form-label">SMTP Password</label><div class="input-group"><input type="password" class="form-control setting-input" name="smtp_pass" value="<?php echo htmlspecialchars($settings['smtp_pass'] ?? ''); ?>"><button class="btn btn-outline-secondary toggle-visibility" type="button"><i class="bi bi-eye-fill"></i></button></div></div>
                </div></div>
            </div>

            <div class="tab-pane fade" id="tab-apis" role="tabpanel">
                <div class="card shadow-sm"><div class="card-header fw-bold">API Credentials</div><div class="card-body">
                    <h6 class="text-muted">Social Login APIs</h6>
                    <div class="mb-3"><label class="form-label">Google Client ID</label><input type="text" class="form-control setting-input" name="google_client_id" value="<?php echo htmlspecialchars($settings['google_client_id'] ?? ''); ?>"></div>
                    <div class="mb-3"><label class="form-label">Google Client Secret</label><div class="input-group"><input type="password" class="form-control setting-input" name="google_client_secret" value="<?php echo htmlspecialchars($settings['google_client_secret'] ?? ''); ?>"><button class="btn btn-outline-secondary toggle-visibility" type="button"><i class="bi bi-eye-fill"></i></button></div></div>
                    <div class="mb-3"><label class="form-label">Facebook App ID</label><input type="text" class="form-control setting-input" name="facebook_app_id" value="<?php echo htmlspecialchars($settings['facebook_app_id'] ?? ''); ?>"></div>
                    <div class="mb-3"><label class="form-label">Facebook App Secret</label><div class="input-group"><input type="password" class="form-control setting-input" name="facebook_app_secret" value="<?php echo htmlspecialchars($settings['facebook_app_secret'] ?? ''); ?>"><button class="btn btn-outline-secondary toggle-visibility" type="button"><i class="bi bi-eye-fill"></i></button></div></div>
                    <hr class="my-4">
                    <h6 class="text-muted">Content & Service APIs</h6>
                    <div class="mb-3"><label class="form-label">OpenAI API Key</label><div class="input-group"><input type="password" class="form-control setting-input" name="openai_api_key" value="<?php echo htmlspecialchars($settings['openai_api_key'] ?? ''); ?>"><button class="btn btn-outline-secondary toggle-visibility" type="button"><i class="bi bi-eye-fill"></i></button></div></div>
                    <div class="mb-3"><label class="form-label">TinyMCE API Key</label><div class="input-group"><input type="password" class="form-control setting-input" name="tinymce_api_key" value="<?php echo htmlspecialchars($settings['tinymce_api_key'] ?? ''); ?>"><button class="btn btn-outline-secondary toggle-visibility" type="button"><i class="bi bi-eye-fill"></i></button></div></div>
                    <div class="mb-3"><label class="form-label">Exchange Rate API Key</label><input type="text" class="form-control setting-input" name="exchange_rate_api_key" value="<?php echo htmlspecialchars($settings['exchange_rate_api_key'] ?? ''); ?>"></div>
                </div></div>
            </div>

        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const toastContainer = document.getElementById('toast-container');
    let saveTimeout;
    function showToast(message, type = 'success') {
        const toast = document.createElement('div');
        toast.className = `alert alert-${type} alert-dismissible fade show`;
        toast.innerHTML = `${message}<button type="button" class="btn-close" data-bs-dismiss="alert"></button>`;
        toastContainer.appendChild(toast);
        setTimeout(() => bootstrap.Alert.getOrCreateInstance(toast).close(), 4000);
    }
    function saveSetting(name, value) {
        const formData = new FormData();
        formData.append('action', 'save_setting');
        formData.append('name', name);
        formData.append('value', value);
        fetch('ajax-handler.php', { method: 'POST', body: formData })
            .then(response => response.json())
            .then(data => { if (data.success) { showToast('Saved: ' + name.replace(/_/g, " ")); } else { showToast(data.message || 'Error', 'danger'); } })
            .catch(() => showToast('Network error.', 'danger'));
    }
    document.querySelectorAll('.setting-input').forEach(input => {
        const eventType = (input.tagName === 'INPUT' && (input.type === 'text' || input.type === 'email' || input.type === 'password')) ? 'keyup' : 'change';
        input.addEventListener(eventType, function () {
            clearTimeout(saveTimeout);
            saveTimeout = setTimeout(() => {
                let value = (input.type === 'checkbox') ? (input.checked ? '1' : '0') : input.value;
                if(input.type === 'radio') { if(input.checked) saveSetting(input.name, value); }
                else { saveSetting(this.name, value); }
            }, 750);
        });
    });
    document.querySelectorAll('.image-upload-input').forEach(input => {
        input.addEventListener('change', function () {
            const file = this.files[0];
            const settingName = this.dataset.settingName;
            const previewId = this.dataset.previewId;
            const previewImg = document.getElementById(previewId);
            if (file) {
                const reader = new FileReader();
                reader.onload = e => { previewImg.src = e.target.result; previewImg.style.display = 'block'; };
                reader.readAsDataURL(file);
                const formData = new FormData();
                formData.append('action', 'upload_image_setting');
                formData.append('name', settingName);
                const fileInputName = (settingName === 'favicon') ? 'favicon_image' : this.name;
                formData.append('file_input_name', fileInputName);
                formData.append(fileInputName, file);
                fetch('ajax-handler.php', { method: 'POST', body: formData })
                .then(response => response.json())
                .then(data => { if (data.success) { showToast(data.message); previewImg.src = data.url; } else { showToast(data.message, 'danger'); } })
                .catch(() => showToast('Upload failed.', 'danger'));
            }
        });
    });
    document.querySelectorAll('.toggle-visibility').forEach(button => {
        button.addEventListener('click', function () {
            const input = this.previousElementSibling; const icon = this.querySelector('i');
            if (input.type === 'password') { input.type = 'text'; icon.classList.replace('bi-eye-fill', 'bi-eye-slash-fill'); }
            else { input.type = 'password'; icon.classList.replace('bi-eye-slash-fill', 'bi-eye-fill'); }
        });
    });
});
</script>

<?php include 'admin-footer.php'; ?>
