<?php
require __DIR__ . '/../includes/bootstrap.php';
require_login();
require_admin();

$pdo = db();
$errors = [];
$userId = current_user()['id'];

if (is_post()) {
    if (!validate_csrf_token($_POST['csrf_token'] ?? null)) {
        $errors[] = 'Invalid session token.';
    } else {
        $action = $_POST['action'] ?? 'save';

        if ($action === 'save') {
            $settings = $_POST['settings'] ?? [];
            $stmt = $pdo->prepare(
                'INSERT INTO system_settings (setting_key, setting_value, description, updated_by)
                 VALUES (:key, :value, :description, :updated_by)
                 ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value), description = VALUES(description),
                                         updated_by = VALUES(updated_by), updated_at = CURRENT_TIMESTAMP'
            );
            foreach ($settings as $key => $data) {
                $stmt->execute([
                    'key' => $key,
                    'value' => $data['value'] ?? '',
                    'description' => $data['description'] ?? '',
                    'updated_by' => $userId,
                ]);
            }
            add_flash('success', 'Settings updated.');
            redirect('admin/settings.php');
        }

        if ($action === 'create') {
            $key = strtolower(trim($_POST['new_key'] ?? ''));
            $value = trim($_POST['new_value'] ?? '');
            $description = trim($_POST['new_description'] ?? '');

            if ($key === '') {
                $errors[] = 'Setting key is required.';
            } else {
                $stmt = $pdo->prepare(
                    'INSERT INTO system_settings (setting_key, setting_value, description, updated_by)
                     VALUES (:key, :value, :description, :updated_by)'
                );
                $stmt->execute([
                    'key' => $key,
                    'value' => $value,
                    'description' => $description,
                    'updated_by' => $userId,
                ]);
                add_flash('success', 'Setting created.');
                redirect('admin/settings.php');
            }
        }
    }
}

$settings = $pdo->query(
    'SELECT ss.*, u.full_name AS updated_by_name
     FROM system_settings ss
     LEFT JOIN users u ON ss.updated_by = u.id
     ORDER BY ss.setting_key ASC'
)->fetchAll();

render_header('Settings', ['active' => 'settings']);
?>
<div class="row g-4">
    <div class="col-lg-8">
        <div class="card shadow-sm">
            <div class="card-header bg-white d-flex justify-content-between align-items-center">
                <h5 class="mb-0">System Settings</h5>
                <form method="post" class="d-inline">
                    <input type="hidden" name="csrf_token" value="<?= sanitize(ensure_csrf_token()) ?>">
                    <input type="hidden" name="action" value="save">
                    <button type="submit" class="btn btn-primary btn-sm">Save Changes</button>
                </form>
            </div>
            <div class="card-body">
                <?php if ($errors): ?>
                    <div class="alert alert-danger">
                        <?php foreach ($errors as $error): ?>
                            <div><?= sanitize($error) ?></div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
                <?php if (!$settings): ?>
                    <p class="text-muted">No settings found. Use the form on the right to add one.</p>
                <?php else: ?>
                    <form method="post">
                        <input type="hidden" name="csrf_token" value="<?= sanitize(ensure_csrf_token()) ?>">
                        <input type="hidden" name="action" value="save">
                        <div class="table-responsive">
                            <table class="table align-middle">
                                <thead>
                                <tr>
                                    <th>Key</th>
                                    <th>Value</th>
                                    <th>Description</th>
                                    <th>Updated</th>
                                </tr>
                                </thead>
                                <tbody>
                                <?php foreach ($settings as $setting): ?>
                                    <tr>
                                        <td class="text-uppercase fw-semibold"><?= sanitize($setting['setting_key']) ?></td>
                                        <td style="width: 25%;">
                                            <input type="text" name="settings[<?= sanitize($setting['setting_key']) ?>][value]"
                                                   class="form-control" value="<?= sanitize($setting['setting_value']) ?>">
                                        </td>
                                        <td>
                                            <input type="text" name="settings[<?= sanitize($setting['setting_key']) ?>][description]"
                                                   class="form-control" value="<?= sanitize($setting['description']) ?>">
                                        </td>
                                        <td class="text-muted-sm">
                                            <?= format_datetime($setting['updated_at']) ?><br>
                                            <?= sanitize($setting['updated_by_name'] ?? 'System') ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        <div class="text-end">
                            <button type="submit" class="btn btn-primary">Save Changes</button>
                        </div>
                    </form>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <div class="col-lg-4">
        <div class="card shadow-sm h-100">
            <div class="card-header bg-white">
                <h5 class="mb-0">Add Setting</h5>
            </div>
            <div class="card-body">
                <form method="post" class="v-stack gap-3">
                    <input type="hidden" name="csrf_token" value="<?= sanitize(ensure_csrf_token()) ?>">
                    <input type="hidden" name="action" value="create">
                    <div>
                        <label class="form-label">Key</label>
                        <input type="text" name="new_key" class="form-control text-lowercase"
                               placeholder="attendance.cutoff" required>
                    </div>
                    <div>
                        <label class="form-label">Value</label>
                        <input type="text" name="new_value" class="form-control" placeholder="Value">
                    </div>
                    <div>
                        <label class="form-label">Description</label>
                        <textarea name="new_description" class="form-control" rows="2"></textarea>
                    </div>
                    <button type="submit" class="btn btn-outline-primary">Create Setting</button>
                </form>
            </div>
        </div>
    </div>
</div>
<?php
render_footer();
