<?php

require_once __DIR__ . '/../lib/init.php';
Auth::requireLogin();
Auth::requireRole('admin');

$success = false;
$errors  = [];

// Debug API Kea (AJAX)
if (isset($_POST['kea_debug'])) {
    header('Content-Type: application/json');
    $command = trim($_POST['command'] ?? '');
    $service = trim($_POST['service'] ?? '');
    $args    = trim($_POST['arguments'] ?? '');

    if (!$command) {
        echo json_encode(['error' => 'Commande vide']);
        exit;
    }

    $payload = ['command' => $command];
    if ($service) {
        $payload['service'] = [$service];
    }
    if ($args !== '') {
        $decoded = json_decode($args, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            echo json_encode(['error' => 'Arguments JSON invalides : ' . json_last_error_msg()]);
            exit;
        }
        $payload['arguments'] = $decoded;
    }

    $url  = rtrim(Settings::get('kea_api_url', 'http://localhost:8000'), '/') . '/';
    $user = Settings::get('kea_api_user', '');
    $pass = Settings::get('kea_api_password', '');

    $opts = [
        'http' => [
            'method'  => 'POST',
            'header'  => 'Content-Type: application/json' . "\r\n" .
                         ($user !== '' ? 'Authorization: Basic ' . base64_encode("$user:$pass") . "\r\n" : ''),
            'content' => json_encode($payload),
            'timeout' => 10,
            'ignore_errors' => true,
        ],
    ];
    $raw = @file_get_contents($url, false, stream_context_create($opts));
    if ($raw === false) {
        echo json_encode(['error' => 'Impossible de joindre ' . $url]);
    } else {
        $decoded = json_decode($raw, true);
        echo json_encode($decoded ?? ['raw' => $raw]);
    }
    exit;
}

// Test de sync manuel
if (isset($_POST['test_sync'])) {
    $result = SyncService::sync();
    AuditLog::log('settings.test_sync', null, null, $result['message']);
    $_SESSION['flash'] = [
        'type'    => $result['success'] ? 'success' : 'danger',
        'message' => 'Test sync : ' . $result['message'],
    ];
    header('Location: settings.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['test_sync'])) {
    $allowed = [
        'app_name', 'kea_api_url', 'kea_api_user', 'kea_api_password', 'freebsd_mode',
        'sync_server_url', 'sync_token', 'domain_name', 'default_lease_time',
        'relay_mode', 'relay_interface',
    ];

    $toSave = [];
    foreach ($allowed as $key) {
        if (isset($_POST[$key])) {
            $toSave[$key] = trim($_POST[$key]);
        }
    }
    $toSave['freebsd_mode'] = isset($_POST['freebsd_mode']) ? '1' : '0';
    $toSave['relay_mode']   = isset($_POST['relay_mode'])   ? '1' : '0';

    Settings::setMany($toSave);
    AuditLog::log('settings.update', null, null, 'Paramètres mis à jour');
    $success = true;
}

$settings   = Settings::getAll();
$allUsers   = Auth::getAllUsers();
$page_title = 'Paramètres';
require_once APP_ROOT . '/lib/layout_header.php';

$flash = $_SESSION['flash'] ?? null;
unset($_SESSION['flash']);
?>

<style>
.settings-sticky-header {
    position: sticky;
    top: var(--topbar-height);
    z-index: 50;
    background: #fff;
    border-radius: 0 !important;
}
</style>

<?php if ($flash): ?>
<div class="alert alert-<?= h($flash['type']) ?> alert-dismissible fade show">
    <?= h($flash['message']) ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<?php if ($success): ?>
<div class="alert alert-success alert-dismissible fade show">
    <i class="bi bi-check-circle"></i> Paramètres enregistrés.
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<div class="row g-4">

<!-- Paramètres principaux -->
<div class="col-lg-8">
<div class="card mb-4">

    <!-- Header sticky avec les boutons toujours visibles -->
    <div class="card-header py-3 d-flex justify-content-between align-items-center settings-sticky-header">
        <span><i class="bi bi-gear me-2"></i>Configuration</span>
        <div class="d-flex gap-2">
            <button type="submit" form="settings-form" class="btn btn-sm btn-primary">
                <i class="bi bi-check-lg me-1"></i>Enregistrer
            </button>
            <button type="submit" form="settings-form" name="test_sync" value="1" class="btn btn-sm btn-outline-secondary">
                <i class="bi bi-arrow-repeat me-1"></i>Tester sync
            </button>
        </div>
    </div>

    <div class="card-body">
        <form method="post" id="settings-form">

            <!-- Onglets -->
            <ul class="nav nav-tabs mb-4" role="tablist">
                <li class="nav-item">
                    <button type="button" class="nav-link active" data-bs-toggle="tab" data-bs-target="#tab-general" role="tab">
                        <i class="bi bi-sliders me-1"></i>Général
                    </button>
                </li>
                <li class="nav-item">
                    <button type="button" class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-dhcp" role="tab">
                        <i class="bi bi-diagram-3 me-1"></i>DHCP
                    </button>
                </li>
                <li class="nav-item">
                    <button type="button" class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-api" role="tab">
                        <i class="bi bi-plug me-1"></i>Kea API
                    </button>
                </li>
                <li class="nav-item">
                    <button type="button" class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-debug" role="tab">
                        <i class="bi bi-terminal me-1"></i>Debug
                    </button>
                </li>
            </ul>

            <div class="tab-content">

                <!-- ── Onglet Général ── -->
                <div class="tab-pane fade show active" id="tab-general" role="tabpanel">
                    <div class="row g-3 mb-3">
                        <div class="col-sm-6">
                            <label class="form-label fw-semibold">Nom de l'application</label>
                            <input type="text" name="app_name" class="form-control"
                                   value="<?= h($settings['app_name'] ?? 'DHCPMan') ?>">
                        </div>
                        <div class="col-sm-6">
                            <label class="form-label fw-semibold">Domaine par défaut</label>
                            <input type="text" name="domain_name" class="form-control"
                                   value="<?= h($settings['domain_name'] ?? 'local') ?>">
                        </div>
                    </div>
                    <div class="row g-3">
                        <div class="col-sm-6">
                            <label class="form-label fw-semibold">Durée du bail DHCP (secondes)</label>
                            <input type="number" name="default_lease_time" class="form-control"
                                   value="<?= h($settings['default_lease_time'] ?? '86400') ?>" min="60">
                        </div>
                    </div>
                </div>

                <!-- ── Onglet DHCP ── -->
                <div class="tab-pane fade" id="tab-dhcp" role="tabpanel">
                    <h6 class="fw-bold mb-3">Mode de synchronisation</h6>
                    <div class="mb-4">
                        <div class="form-check form-switch">
                            <input type="checkbox" name="freebsd_mode" id="freebsd_mode"
                                   class="form-check-input" role="switch"
                                   <?= ($settings['freebsd_mode'] ?? '0') == '1' ? 'checked' : '' ?>>
                            <label class="form-check-label fw-semibold" for="freebsd_mode">
                                Mode FreeBSD (sync_server.py)
                            </label>
                        </div>
                        <div class="form-text">Désactivé = mode AlmaLinux (API Kea directe). Activé = mode FreeBSD (via sync_server.py).</div>
                    </div>

                    <hr class="my-4">
                    <h6 class="fw-bold mb-3">Mode relay DHCP</h6>
                    <div class="mb-3">
                        <div class="form-check form-switch">
                            <input type="checkbox" name="relay_mode" id="relay_mode"
                                   class="form-check-input" role="switch"
                                   <?= ($settings['relay_mode'] ?? '0') == '1' ? 'checked' : '' ?>
                                   onchange="toggleRelayMode(this.checked)">
                            <label class="form-check-label fw-semibold" for="relay_mode">
                                Mode relay (DHCP via core switch)
                            </label>
                        </div>
                        <div class="form-text">
                            Activé = Kea reçoit les paquets relayés (ex&nbsp;: Cisco C9500 avec <code>ip helper-address</code>).
                            Désactivé = mode direct (Kea lié sur une interface par subnet).
                        </div>
                    </div>

                    <div id="section-relay" class="<?= ($settings['relay_mode'] ?? '0') != '1' ? 'd-none' : '' ?>">
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Interface Kea (mode relay)</label>
                            <input type="text" name="relay_interface" class="form-control"
                                   value="<?= h($settings['relay_interface'] ?? '') ?>"
                                   placeholder="igc0">
                            <div class="form-text">
                                Interface sur laquelle Kea écoute les paquets UDP relayés.
                                Kea sera configuré avec <code>"dhcp-socket-type": "udp"</code>.
                            </div>
                        </div>
                        <?php if (($settings['freebsd_mode'] ?? '0') != '1'): ?>
                        <div class="alert alert-warning py-2">
                            <i class="bi bi-exclamation-triangle me-2"></i>
                            <strong>Mode AlmaLinux + relay :</strong> ajoutez manuellement
                            <code>"dhcp-socket-type": "udp"</code> dans le bloc <code>interfaces-config</code>
                            de votre <code>kea-dhcp4.conf</code> (ce paramètre n'est pas géré via le Config Backend).
                        </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- ── Onglet Kea API ── -->
                <div class="tab-pane fade" id="tab-api" role="tabpanel">
                    <div class="mb-3">
                        <label class="form-label fw-semibold">URL du Kea Control Agent</label>
                        <input type="text" name="kea_api_url" class="form-control font-monospace"
                               value="<?= h($settings['kea_api_url'] ?? 'http://localhost:8000') ?>"
                               placeholder="http://kea-server:8000">
                        <div class="form-text">
                            Utilisé pour les leases (tous les modes) et pour config-reload (mode AlmaLinux).
                            Le path « / » est ajouté automatiquement.
                        </div>
                    </div>
                    <div class="row g-3 mb-4">
                        <div class="col-sm-6">
                            <label class="form-label fw-semibold">Utilisateur HTTP Basic Auth</label>
                            <input type="text" name="kea_api_user" class="form-control font-monospace"
                                   value="<?= h($settings['kea_api_user'] ?? '') ?>"
                                   placeholder="Laisser vide si sans auth"
                                   autocomplete="off">
                        </div>
                        <div class="col-sm-6">
                            <label class="form-label fw-semibold">Mot de passe</label>
                            <input type="password" name="kea_api_password" class="form-control font-monospace"
                                   value="<?= h($settings['kea_api_password'] ?? '') ?>"
                                   autocomplete="new-password">
                        </div>
                    </div>

                    <div id="section-freebsd" class="<?= ($settings['freebsd_mode'] ?? '0') != '1' ? 'd-none' : '' ?>">
                        <hr class="mb-4">
                        <h6 class="fw-bold mb-3">Serveur de synchronisation FreeBSD</h6>
                        <div class="mb-3">
                            <label class="form-label fw-semibold">URL sync_server</label>
                            <input type="text" name="sync_server_url" class="form-control font-monospace"
                                   value="<?= h($settings['sync_server_url'] ?? 'http://localhost:8765/sync') ?>"
                                   placeholder="http://kea-vm:8765/sync">
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Token d'authentification</label>
                            <input type="text" name="sync_token" class="form-control font-monospace"
                                   value="<?= h($settings['sync_token'] ?? '') ?>"
                                   placeholder="secret-token-ici"
                                   autocomplete="off">
                        </div>
                    </div>
                </div>

                <!-- ── Onglet Debug ── -->
                <div class="tab-pane fade" id="tab-debug" role="tabpanel">
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Commande Kea</label>
                        <div class="input-group">
                            <input type="text" id="debug-command" class="form-control font-monospace"
                                   placeholder="config-get" list="debug-commands-list">
                            <datalist id="debug-commands-list">
                                <option value="config-get">
                                <option value="config-reload">
                                <option value="status-get">
                                <option value="version-get">
                                <option value="subnet4-list">
                                <option value="subnet4-get">
                                <option value="subnet4-add">
                                <option value="subnet4-update">
                                <option value="subnet4-del">
                                <option value="lease4-get-all">
                                <option value="lease4-get">
                                <option value="reservation-get-all">
                                <option value="list-commands">
                            </datalist>
                            <select id="debug-service" class="form-select" style="max-width:140px">
                                <option value="dhcp4">dhcp4</option>
                                <option value="dhcp6">dhcp6</option>
                                <option value="">— aucun —</option>
                            </select>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Arguments <span class="text-muted fw-normal">(JSON, optionnel)</span></label>
                        <textarea id="debug-args" class="form-control font-monospace" rows="5"
                                  placeholder='{"subnet-id": 1}'></textarea>
                    </div>
                    <div class="d-flex gap-2 mb-3">
                        <button type="button" class="btn btn-primary" onclick="debugSend()">
                            <i class="bi bi-send me-1"></i>Envoyer
                        </button>
                        <button type="button" class="btn btn-outline-secondary" onclick="debugClear()">
                            <i class="bi bi-x-lg me-1"></i>Effacer
                        </button>
                    </div>
                    <div id="debug-result" class="d-none">
                        <div class="d-flex justify-content-between align-items-center mb-1">
                            <label class="form-label fw-semibold mb-0">Réponse</label>
                            <small id="debug-status-badge"></small>
                        </div>
                        <pre id="debug-output" class="bg-dark text-light p-3 rounded font-monospace"
                             style="max-height:400px;overflow:auto;font-size:0.8rem"></pre>
                    </div>
                </div>

            </div><!-- /.tab-content -->
        </form>
    </div>
</div>
</div>

<!-- Utilisateurs -->
<div class="col-lg-4">
<div class="card">
    <div class="card-header py-3 d-flex justify-content-between align-items-center">
        <span><i class="bi bi-people me-2"></i>Utilisateurs</span>
        <button class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#addUserModal">
            <i class="bi bi-plus"></i>
        </button>
    </div>
    <ul class="list-group list-group-flush">
    <?php
    $roleColors = ['admin' => 'danger', 'tech' => 'primary', 'viewer' => 'secondary'];
    foreach ($allUsers as $u):
        $isSelf = ($u['id'] == Auth::currentUserId());
    ?>
        <li class="list-group-item py-2 px-3">
            <div class="d-flex justify-content-between align-items-center mb-1">
                <div>
                    <i class="bi bi-person-circle me-1 text-muted"></i>
                    <strong><?= h($u['username']) ?></strong>
                    <?php if ($isSelf): ?>
                        <span class="badge bg-primary ms-1">vous</span>
                    <?php endif; ?>
                    <?php if (!$u['is_active']): ?>
                        <span class="badge bg-secondary ms-1">inactif</span>
                    <?php endif; ?>
                </div>
                <small class="text-muted">
                    <?= $u['last_login'] ? h(substr($u['last_login'], 0, 10)) : 'jamais' ?>
                </small>
            </div>
            <div class="d-flex gap-1 align-items-center">
                <form method="post" action="user_role.php" class="d-flex gap-1 flex-grow-1">
                    <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                    <select name="role" class="form-select form-select-sm"
                            onchange="this.form.submit()" <?= $isSelf ? 'disabled' : '' ?>>
                        <?php foreach (['admin', 'tech', 'viewer'] as $r): ?>
                            <option value="<?= $r ?>" <?= $u['role'] === $r ? 'selected' : '' ?>><?= $r ?></option>
                        <?php endforeach; ?>
                    </select>
                </form>
                <?php if (!$isSelf): ?>
                <form method="post" action="user_toggle.php">
                    <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                    <button type="submit" class="btn btn-sm <?= $u['is_active'] ? 'btn-outline-secondary' : 'btn-outline-success' ?>"
                            title="<?= $u['is_active'] ? 'Désactiver' : 'Activer' ?>">
                        <i class="bi bi-<?= $u['is_active'] ? 'pause' : 'play' ?>"></i>
                    </button>
                </form>
                <button type="button" class="btn btn-sm btn-outline-warning"
                        title="Réinitialiser le mot de passe"
                        onclick="openResetPwd(<?= $u['id'] ?>, <?= h(json_encode($u['username'])) ?>)">
                    <i class="bi bi-key"></i>
                </button>
                <form method="post" action="user_delete.php"
                      onsubmit="return confirm('Supprimer « <?= h($u['username']) ?> » ?')">
                    <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                    <button type="submit" class="btn btn-sm btn-outline-danger" title="Supprimer">
                        <i class="bi bi-trash"></i>
                    </button>
                </form>
                <?php endif; ?>
            </div>
        </li>
    <?php endforeach; ?>
    </ul>
</div>
</div>

</div><!-- /.row -->

<!-- Modal ajout utilisateur -->
<div class="modal fade" id="addUserModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Nouvel utilisateur</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="post" action="user_add.php">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Nom d'utilisateur</label>
                        <input type="text" name="username" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Mot de passe</label>
                        <input type="password" name="password" class="form-control" required autocomplete="new-password">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Rôle</label>
                        <select name="role" class="form-select">
                            <option value="tech" selected>tech — tout sauf gestion utilisateurs</option>
                            <option value="viewer">viewer — lecture seule</option>
                            <option value="admin">admin — accès complet</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Annuler</button>
                    <button type="submit" class="btn btn-primary">Créer</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal reset mot de passe -->
<div class="modal fade" id="resetPwdModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Réinitialiser le mot de passe</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="post" action="user_reset_password.php">
                <div class="modal-body">
                    <p class="text-muted mb-3">
                        Utilisateur : <strong id="resetPwdUsername"></strong>
                    </p>
                    <input type="hidden" name="user_id" id="resetPwdUserId">
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Nouveau mot de passe</label>
                        <input type="password" name="password" class="form-control"
                               required autocomplete="new-password" minlength="6">
                        <div class="form-text">Minimum 6 caractères.</div>
                    </div>
                    <div class="mb-1">
                        <label class="form-label fw-semibold">Confirmer</label>
                        <input type="password" name="confirm" class="form-control"
                               required autocomplete="new-password">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Annuler</button>
                    <button type="submit" class="btn btn-warning">
                        <i class="bi bi-key"></i> Réinitialiser
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Affiche/masque les champs FreeBSD selon l'état du toggle au chargement de l'onglet API
document.querySelector('[data-bs-target="#tab-api"]').addEventListener('shown.bs.tab', function () {
    var freebsdOn = document.getElementById('freebsd_mode').checked;
    document.getElementById('section-freebsd').classList.toggle('d-none', !freebsdOn);
});

function toggleRelayMode(relay) {
    document.getElementById('section-relay').classList.toggle('d-none', !relay);
}

function debugSend() {
    const command = document.getElementById('debug-command').value.trim();
    if (!command) { alert('Entrez une commande'); return; }
    const btn = document.querySelector('#tab-debug .btn-primary');
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Envoi…';

    const fd = new FormData();
    fd.append('kea_debug', '1');
    fd.append('command',   command);
    fd.append('service',   document.getElementById('debug-service').value);
    fd.append('arguments', document.getElementById('debug-args').value.trim());

    fetch('settings.php', { method: 'POST', body: fd })
        .then(r => r.json())
        .then(data => {
            const out   = document.getElementById('debug-output');
            const badge = document.getElementById('debug-status-badge');
            const res   = document.getElementById('debug-result');
            out.textContent = JSON.stringify(data, null, 2);
            res.classList.remove('d-none');
            // colorier le badge selon result
            const result = Array.isArray(data) ? data[0]?.result : data?.result;
            if (data.error) {
                badge.innerHTML = '<span class="badge bg-danger">Erreur</span>';
            } else if (result === 0) {
                badge.innerHTML = '<span class="badge bg-success">result: 0 — OK</span>';
            } else if (result === 3) {
                badge.innerHTML = '<span class="badge bg-warning text-dark">result: 3 — vide</span>';
            } else if (result !== undefined) {
                badge.innerHTML = '<span class="badge bg-danger">result: ' + result + '</span>';
            } else {
                badge.innerHTML = '';
            }
        })
        .catch(e => {
            document.getElementById('debug-output').textContent = 'Erreur fetch : ' + e;
            document.getElementById('debug-result').classList.remove('d-none');
        })
        .finally(() => {
            btn.disabled = false;
            btn.innerHTML = '<i class="bi bi-send me-1"></i>Envoyer';
        });
}

function debugClear() {
    document.getElementById('debug-command').value = '';
    document.getElementById('debug-args').value    = '';
    document.getElementById('debug-output').textContent = '';
    document.getElementById('debug-status-badge').innerHTML = '';
    document.getElementById('debug-result').classList.add('d-none');
}

function openResetPwd(userId, username) {
    document.getElementById('resetPwdUserId').value = userId;
    document.getElementById('resetPwdUsername').textContent = username;
    document.querySelectorAll('#resetPwdModal input[type=password]').forEach(function(i) {
        i.value = '';
    });
    new bootstrap.Modal(document.getElementById('resetPwdModal')).show();
}
</script>

<?php require_once APP_ROOT . '/lib/layout_footer.php'; ?>
