<?php
require_once __DIR__ . '/config.php';
require_admin_login();

// --- FINAL CORRECTED FORM SUBMISSION LOGIC ---
if (is_post()) {
    verify_csrf();
    if (isset($_POST['settings']) && is_array($_POST['settings'])) {
        
        try {
            // Prepare all necessary SQL statements once
            $check_stmt = $pdo->prepare("SELECT COUNT(*) FROM settings WHERE setting_key = ?");
            $update_stmt = $pdo->prepare("UPDATE settings SET setting_value = ? WHERE setting_key = ?");
            $insert_stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?)");

            // Process each setting from the form
            foreach ($_POST['settings'] as $key => $value) {
                $trimmed_value = trim($value);

                // 1. Check if the setting key already exists in the database
                $check_stmt->execute([$key]);
                $exists = $check_stmt->fetchColumn() > 0;

                // 2. Perform UPDATE or INSERT based on whether it exists
                if ($exists) {
                    $update_stmt->execute([$trimmed_value, $key]);
                } else {
                    $insert_stmt->execute([$key, $trimmed_value]);
                }
            }

            set_flash("Settings have been updated successfully!", "success");
            
        } catch (Throwable $e) {
            set_flash("An error occurred: " . $e->getMessage(), "danger");
        }

        redirect('site_info.php');
    }
}

// --- Fetch Existing Settings ---
try {
    $settings_stmt = $pdo->query("SELECT setting_key, setting_value FROM settings");
    $settings_from_db = $settings_stmt->fetchAll();
    
    $settings = [];
    foreach ($settings_from_db as $setting) {
        $settings[$setting['setting_key']] = $setting['setting_value'];
    }
} catch (Exception $e) {
    $settings = [];
    set_flash("Could not load settings: The 'settings' table may be missing.", "danger");
}

require_once 'header.php';
?>

<style>
    /* Custom Brand Colors #230133 */
    :root {
        --brand-color: #230133;
        --brand-hover: #3b0354;
    }

    .text-brand { color: var(--brand-color) !important; }
    .bg-brand { background-color: var(--brand-color) !important; }
    
    .btn-brand {
        background-color: var(--brand-color) !important;
        border-color: var(--brand-color) !important;
        color: white !important;
    }
    
    .btn-brand:hover {
        background-color: var(--brand-hover) !important;
        border-color: var(--brand-hover) !important;
    }

    .card-header-brand {
        background-color: var(--brand-color) !important;
        color: white !important;
    }

    .form-control:focus, .form-select:focus {
        border-color: var(--brand-color);
        box-shadow: 0 0 0 0.25rem rgba(35, 1, 51, 0.25);
    }

    .section-title {
        border-left: 5px solid var(--brand-color);
        padding-left: 10px;
        margin-bottom: 20px;
        color: var(--brand-color);
        font-weight: bold;
    }
</style>

<div class="container-fluid py-4">
    <h1 class="h3 mb-4 text-brand fw-bold">Content Management System (CMS)</h1>
    <?php show_flash(); ?>

    <div class="card shadow-sm mb-5 border-0">
        <div class="card-header card-header-brand py-3">
            <h6 class="m-0 fw-bold"><i class="bi bi-pencil-square me-2"></i>Edit Site Content & Notifications</h6>
        </div>
        <div class="card-body">
            <form method="post">
                <?php csrf_field(); ?>

                <h5 class="section-title">General Settings</h5>
                <div class="mb-3">
                    <label for="site_name" class="form-label fw-bold small">Site Name</label>
                    <input type="text" class="form-control" id="site_name" name="settings[site_name]" 
                           value="<?php echo h($settings['site_name'] ?? 'Online Server'); ?>">
                </div>
                <div class="mb-3">
                    <label for="top_bar_notice" class="form-label fw-bold small">Top Notice Bar Text (Scrolling)</label>
                    <textarea class="form-control" id="top_bar_notice" name="settings[top_bar_notice]" rows="2"><?php echo h($settings['top_bar_notice'] ?? ''); ?></textarea>
                </div>

                <hr class="my-4">

                <h5 class="section-title">Service Rates & API Charges</h5>
                <div class="row bg-light p-3 rounded border mb-3 mx-1">
                    <div class="col-md-6 mb-3">
                        <label for="server_copy_charge" class="form-label fw-bold text-danger small">Server Copy API Charge (প্রতি কপির মূল্য)</label>
                        <div class="input-group">
                            <span class="input-group-text bg-brand text-white">৳</span>
                            <input type="number" step="0.01" class="form-control" id="server_copy_charge" name="settings[server_copy_charge]" 
                                   value="<?php echo h($settings['server_copy_charge'] ?? '0'); ?>" placeholder="0.00">
                        </div>
                        <small class="text-muted">ইউজার যখন সার্ভার কপি রিকোয়েস্ট করবে, তখন তার ব্যালেন্স থেকে এই টাকাটি কাটা হবে।</small>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label for="api_service_status" class="form-label fw-bold small">Service Status</label>
                        <select class="form-select" name="settings[api_service_status]">
                            <option value="1" <?php echo ($settings['api_service_status'] ?? '1') == '1' ? 'selected' : ''; ?>>Active (চালু)</option>
                            <option value="0" <?php echo ($settings['api_service_status'] ?? '1') == '0' ? 'selected' : ''; ?>>Maintenance (বন্ধ)</option>
                        </select>
                    </div>
                </div>

                <hr class="my-4">

                <h5 class="section-title">Notices & Popups</h5>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label for="service_page_notice" class="form-label fw-bold small">Service/Server Copy Page Notice</label>
                        <textarea class="form-control" id="service_page_notice" name="settings[service_page_notice]" rows="3"><?php echo h($settings['service_page_notice'] ?? ''); ?></textarea>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label for="login_page_notice" class="form-label fw-bold small">Login Page Notice</label>
                        <textarea class="form-control" id="login_page_notice" name="settings[login_page_notice]" rows="3"><?php echo h($settings['login_page_notice'] ?? ''); ?></textarea>
                    </div>
                    <div class="col-12 mb-3">
                        <label for="popup_notice" class="form-label fw-bold small text-danger">User Panel Popup Notice Content</label>
                        <textarea class="form-control border-danger" id="popup_notice" name="settings[popup_notice]" rows="4"><?php echo h($settings['popup_notice'] ?? ''); ?></textarea>
                    </div>
                </div>

                <hr class="my-4">

                <h5 class="section-title">Payment Wallet Settings</h5>
                <div class="row">
                    <div class="col-md-4 mb-3">
                        <label class="form-label fw-bold small">Bikash Number</label>
                        <input type="text" class="form-control" name="settings[bikash_number]" value="<?php echo h($settings['bikash_number'] ?? ''); ?>">
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label fw-bold small">Nagad Number</label>
                        <input type="text" class="form-control" name="settings[nagad_number]" value="<?php echo h($settings['nagad_number'] ?? ''); ?>">
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label fw-bold small">Rocket Number</label>
                        <input type="text" class="form-control" name="settings[rocket_number]" value="<?php echo h($settings['rocket_number'] ?? ''); ?>">
                    </div>
                </div>

                <hr class="my-4">

                <h5 class="section-title">Support & Telegram API</h5>
                <div class="row">
                    <div class="col-md-12 mb-3">
                        <label class="form-label fw-bold small">WhatsApp Support Group Link</label>
                        <input type="url" class="form-control" name="settings[support_group_link]" value="<?php echo h($settings['support_group_link'] ?? ''); ?>">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label fw-bold small">Telegram Bot Token</label>
                        <input type="text" class="form-control" name="settings[telegram_bot_token]" value="<?php echo h($settings['telegram_bot_token'] ?? ''); ?>">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label fw-bold small">Telegram Chat ID</label>
                        <input type="text" class="form-control" name="settings[telegram_chat_id]" value="<?php echo h($settings['telegram_chat_id'] ?? ''); ?>">
                    </div>
                </div>

                <div class="mt-5 pb-4">
                    <button type="submit" class="btn btn-brand btn-lg shadow w-100 fw-bold">
                        <i class="bi bi-save-fill me-2"></i>SAVE ALL CHANGES
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php
require_once 'footer.php';
?>