<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/auth.php';

require_role(['super_admin']);

$page_title = 'Global Settings';
$pdo = Database::getConnection();
$messages = [];
$errors   = [];

$keys = [
    'smtp_host',
    'smtp_port',
    'smtp_encryption',
    'smtp_username',
    'smtp_password',
    'system_email_from_name',
    'system_email_from_address',
    'support_email',
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Collect posted values
    $values = [];
    foreach ($keys as $key) {
        $values[$key] = trim($_POST[$key] ?? '');
    }

    // Basic validation
    if ($values['smtp_port'] !== '' && !ctype_digit($values['smtp_port'])) {
        $errors[] = 'SMTP port must be a number.';
    }

    if (empty($errors)) {
        $stmt = $pdo->prepare("
            INSERT INTO global_settings (setting_key, setting_value)
            VALUES (:setting_key, :setting_value)
            ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)
        ");

        foreach ($values as $k => $v) {
            $stmt->execute([
                'setting_key'   => $k,
                'setting_value' => $v,
            ]);
        }

        $messages[] = 'Global settings saved successfully.';
    }
}

// Fetch current settings
$current = array_fill_keys($keys, '');

$stmt = $pdo->query("SELECT setting_key, setting_value FROM global_settings");
while ($row = $stmt->fetch()) {
    if (array_key_exists($row['setting_key'], $current)) {
        $current[$row['setting_key']] = $row['setting_value'];
    }
}

include __DIR__ . '/../includes/header.php';
?>

<section class="content">
    <div class="container-fluid">
        <h1 class="mb-4">Global Settings</h1>

        <?php if ($messages): ?>
            <div class="alert alert-success">
                <?php foreach ($messages as $msg): ?>
                    <div><?= e($msg) ?></div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <?php if ($errors): ?>
            <div class="alert alert-danger">
                <?php foreach ($errors as $err): ?>
                    <div><?= e($err) ?></div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <div class="card card-primary">
            <div class="card-header">
                <h3 class="card-title">SMTP Settings</h3>
            </div>
            <form method="post">
                <div class="card-body">
                    <div class="form-group">
                        <label for="smtp_host">SMTP Host</label>
                        <input type="text" name="smtp_host" id="smtp_host"
                               class="form-control"
                               value="<?= e($current['smtp_host']) ?>">
                    </div>
                    <div class="form-group">
                        <label for="smtp_port">SMTP Port</label>
                        <input type="text" name="smtp_port" id="smtp_port"
                               class="form-control"
                               value="<?= e($current['smtp_port']) ?>">
                    </div>
                    <div class="form-group">
                        <label for="smtp_encryption">SMTP Encryption (tls/ssl/none)</label>
                        <input type="text" name="smtp_encryption" id="smtp_encryption"
                               class="form-control"
                               value="<?= e($current['smtp_encryption']) ?>">
                    </div>
                    <div class="form-group">
                        <label for="smtp_username">SMTP Username</label>
                        <input type="text" name="smtp_username" id="smtp_username"
                               class="form-control"
                               value="<?= e($current['smtp_username']) ?>">
                    </div>
                    <div class="form-group">
                        <label for="smtp_password">SMTP Password</label>
                        <input type="password" name="smtp_password" id="smtp_password"
                               class="form-control"
                               value="<?= e($current['smtp_password']) ?>">
                    </div>
                </div>

            <div class="card-header">
                <h3 class="card-title">System Email Defaults</h3>
            </div>
            <div class="card-body">
                <div class="form-group">
                    <label for="system_email_from_name">From Name</label>
                    <input type="text" name="system_email_from_name" id="system_email_from_name"
                           class="form-control"
                           value="<?= e($current['system_email_from_name']) ?>">
                </div>
                <div class="form-group">
                    <label for="system_email_from_address">From Address</label>
                    <input type="email" name="system_email_from_address" id="system_email_from_address"
                           class="form-control"
                           value="<?= e($current['system_email_from_address']) ?>">
                </div>
                <div class="form-group">
                    <label for="support_email">Support Email</label>
                    <input type="email" name="support_email" id="support_email"
                           class="form-control"
                           value="<?= e($current['support_email']) ?>">
                </div>
            </div>

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

<?php include __DIR__ . '/../includes/footer.php'; ?>
