<?php
require_once 'auth.php'; 
$message = '';
$type = '';

$politique_html = "<p>Politique de confidentialité en cours de rédaction.</p>";
try {
    $stmtPol = $pdo->prepare("SELECT valeur FROM parametres WHERE cle = 'politique_confidentialite'");
    $stmtPol->execute();
    $resPol = $stmtPol->fetch(PDO::FETCH_ASSOC);
    if ($resPol) { $politique_html = $resPol['valeur']; }
} catch (Exception $e) { }

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $prenom = ucfirst(mb_strtolower(trim($_POST['prenom'] ?? ''), 'UTF-8'));
    $nom_famille = ucfirst(mb_strtolower(trim($_POST['nom'] ?? ''), 'UTF-8'));
    $email = trim($_POST['email'] ?? '');
    $numero = trim($_POST['numero'] ?? '');
    $rue = ($_POST['rue'] === 'autre') ? trim($_POST['rue_autre']) : $_POST['rue'];
    $adresse_complete = $numero . ' ' . $rue . ', 80310 Saint vast en Chaussée';
    $pass = $_POST['password'] ?? '';
    $pass_confirm = $_POST['password_confirm'] ?? '';

    // Vérification supplémentaire de la case RGPD côté serveur
    if (!isset($_POST['accept_rgpd'])) {
        $message = "Vous devez accepter la politique de confidentialité.";
        $type = "erreur";
    } elseif (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        if ($pass === $pass_confirm && preg_match('/^(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,}$/', $pass)) {
            if (!empty($numero) && !empty($rue)) {
                $check = $pdo->prepare("SELECT id FROM utilisateurs WHERE email = ?");
                $check->execute([$email]);
                if ($check->fetch()) {
                    $message = "Cette adresse email est déjà utilisée.";
                    $type = "erreur";
                } else {
                    $hashed = password_hash($pass, PASSWORD_DEFAULT);
                    $ins = $pdo->prepare("INSERT INTO utilisateurs (nom, prenom, email, password, adresse, est_valide) VALUES (?, ?, ?, ?, ?, 0)");
                    $ins->execute([$nom_famille, $prenom, $email, $hashed, $adresse_complete]);
                    $userId = $pdo->lastInsertId();
                    $pdo->prepare("INSERT INTO utilisateurs_roles (utilisateur_id, role_id) VALUES (?, 4)")->execute([$userId]);

                    require_once 'mail_helper.php';
                    $sujet = "Votre inscription sur le site de Saint vast en Chaussée";
                    $message_mail = "<h3 style='color:#4a7c44;'>Bonjour " . htmlspecialchars($prenom . ' ' . $nom_famille) . ",</h3><p>Votre compte a bien été créé. Il doit maintenant être validé par la mairie pour garantir la sécurité de l'espace citoyen.</p><p>À très bientôt !</p>";
                    envoyerMailHabitant($email, $sujet, $message_mail);

                    $message = "Votre demande a été transmise à la mairie. Vous allez recevoir un email de confirmation.";
                    $type = "succes";
                }
            } else { $message = "Veuillez renseigner votre adresse complète."; $type = "erreur"; }
        } else { $message = "Le mot de passe ne respecte pas les critères."; $type = "erreur"; }
    } else { $message = "Format d'adresse email invalide."; $type = "erreur"; }
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Inscription - Saint vast en Chaussée</title>
    <link rel="stylesheet" href="../css/global.css">
    <style>
        .register-box { max-width: 650px; margin: 0 auto; background: white; border-radius: 25px; padding: 40px; box-shadow: 0 10px 30px rgba(0,0,0,0.08); }
        .form-row { display: flex; gap: 15px; margin-bottom: 10px; flex-wrap: wrap; }
        .form-col { flex: 1; min-width: 200px; }
        .register-box label { display: block; margin-bottom: 5px; font-size: 0.9em; font-weight: bold; color: #333; }
        .register-box input, .register-box select { width: 100%; padding: 12px; margin-bottom: 5px; border: 2px solid #f0f4f0; border-radius: 15px; box-sizing: border-box; transition: 0.3s; font-family: inherit; }
        .register-box input:focus, .register-box select:focus { border-color: #4a7c44; outline: none; }
        .register-box button { background: #4a7c44; color: white; border: none; padding: 12px; width: 100%; border-radius: 30px; font-weight: bold; cursor: pointer; margin-top: 15px; font-size: 1.1em; transition: opacity 0.2s;}
        .register-box button:disabled { background: #ccc; cursor: not-allowed; }
        .register-box button:hover:not(:disabled) { opacity: 0.9; }
        .msg { padding: 15px; border-radius: 15px; margin-bottom: 15px; text-align: center; font-weight: bold; }
        .erreur { background: #fee; color: #c33; border: 1px solid #fcc; }
        .succes { background: #e1ede0; color: #4a7c44; border: 1px solid #c8e6c9; }
        .feedback { font-size: 0.8em; margin-bottom: 10px; display: block; }
        .valid { color: #4a7c44; } .invalid { color: #c33; }
        .password-rules { font-size: 0.85em; background: #f0f4f0; padding: 10px; border-radius: 10px; margin-bottom: 15px; }
        .legal-notice-box { background: #fafafa; border: 1px solid #eee; padding: 15px; border-radius: 15px; margin-top: 20px; font-size: 0.9em; }
        .modal { display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); backdrop-filter: blur(3px); }
        .modal-content { background-color: white; margin: 5% auto; padding: 30px; border-radius: 25px; width: 90%; max-width: 700px; max-height: 80vh; overflow-y: auto; position: relative; }
        .close-modal { color: #aaa; position: absolute; right: 20px; top: 15px; font-size: 28px; font-weight: bold; cursor: pointer; }
    </style>
</head>
<body>
<div class="site-container">
    <img src="../images/banniere.png" alt="Bannière" class="banner-img">
    <nav><?php include '../includes/menu.php'; ?></nav>
    <main class="main-wrapper">
        <div class="register-box">
            <h2 style="text-align:center; color: #4a7c44; margin-top:0;">Demande d'inscription</h2>
            <?php if($message) echo "<div class='msg $type'>$message</div>"; ?>
            <?php if($type !== 'succes'): ?>
            <form method="POST" action="register.php" id="registerForm">
                <div class="form-row">
                    <div class="form-col"><label>Prénom</label><input type="text" name="prenom" id="prenom" required></div>
                    <div class="form-col"><label>Nom</label><input type="text" name="nom" id="nom" required></div>
                </div>
                <label>Adresse Email</label><input type="email" name="email" id="email" required><span id="emailFeedback" class="feedback"></span>
                <label>Votre adresse à Saint vast en Chaussée</label>
                <div class="form-row">
                    <div class="form-col" style="flex: 0.25; min-width: 80px;"><input type="text" name="numero" id="numero" placeholder="N°" required></div>
                    <div class="form-col" style="flex: 0.75;">
                        <select name="rue" id="rue" onchange="toggleAutre()" required>
                            <option value="">-- Choisir votre rue --</option>
                            <option value="Rue d'Amiens">Rue d'Amiens</option>
                            <option value="Rue de la Basse Cour">Rue de la Basse Cour</option>
                            <option value="Rue du Bois">Rue du Bois</option>
                            <option value="Rue des Champs">Rue des Champs</option>
                            <option value="Rue des Charmes">Rue des Charmes</option>
                            <option value="Rue des Coquelicots">Rue des Coquelicots</option>
                            <option value="Rue des Écoles">Rue des Écoles</option>
                            <option value="Rue les Grands Espaces">Rue les Grands Espaces</option>
                            <option value="Rue Montaval">Rue Montaval</option>
                            <option value="Rue du Stade">Rue du Stade</option>
                            <option value="Rue Verte">Rue Verte</option>
                            <option value="autre">Autre (Saisir manuellement)...</option>
                        </select>
                        <input type="text" name="rue_autre" id="rue_autre" style="display:none;" placeholder="Saisissez le nom de votre rue">
                    </div>
                </div>
                <div class="form-row" style="margin-top: 15px;">
                    <div class="form-col"><label>Mot de passe</label><input type="password" name="password" id="password" required></div>
                    <div class="form-col"><label>Confirmer mot de passe</label><input type="password" name="password_confirm" id="password_confirm" required></div>
                </div>
                <div class="password-rules">
                    <strong>Critères du mot de passe :</strong>
                    <ul style="margin:5px 0 0 20px; padding:0;">
                        <li id="rule-length" class="invalid">Au moins 8 caractères</li>
                        <li id="rule-upper" class="invalid">Au moins une majuscule</li>
                        <li id="rule-number" class="invalid">Au moins un chiffre</li>
                        <li id="rule-special" class="invalid">Au moins un caractère spécial</li>
                        <li id="rule-match" class="invalid">Les mots de passe correspondent</li>
                    </ul>
                </div>

                <div class="legal-notice-box">
                    <div style="display: flex; gap: 10px; align-items: flex-start;">
                        <input type="checkbox" name="accept_rgpd" id="accept_rgpd" style="width: auto; margin-top: 4px;" required>
                        <label for="accept_rgpd" style="font-weight: normal; line-height: 1.4;">
                            J'accepte que mes informations soient traitées par la Mairie de Saint vast en Chaussée pour la gestion de mon compte citoyen, conformément à la 
                            <a id="btn-policy" style="color:#4a7c44; text-decoration:underline; cursor:pointer; font-weight:bold;">Politique de confidentialité</a>.
                        </label>
                    </div>
                </div>

                <button type="submit" id="submitBtn" disabled>Envoyer ma demande</button>
            </form>
            <?php endif; ?>
        </div>
    </main>
</div>

<div id="policyModal" class="modal"><div class="modal-content"><span class="close-modal">&times;</span><h3>Politique de Confidentialité</h3><div style="margin-top: 20px;"><?= $politique_html ?></div></div></div>

<script>
const modal = document.getElementById("policyModal");
const btn = document.getElementById("btn-policy");
const span = document.querySelector(".close-modal");
const rgpdCheckbox = document.getElementById("accept_rgpd");
const submitBtn = document.getElementById('submitBtn');

btn.onclick = () => modal.style.display = "block";
span.onclick = () => modal.style.display = "none";
window.onclick = (e) => { if (e.target == modal) modal.style.display = "none"; }

function checkFormValidity() {
    const isEmailValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(document.getElementById('email').value);
    const p = document.getElementById('password').value;
    const isPswValid = p.length >= 8 && /[A-Z]/.test(p) && /[0-9]/.test(p) && /[\W_]/.test(p);
    const isMatch = (p === document.getElementById('password_confirm').value && p !== '');
    const isRueValid = document.getElementById('rue').value !== '';
    const isRgpdAccepted = rgpdCheckbox.checked;

    if (isEmailValid && isPswValid && isMatch && isRueValid && isRgpdAccepted) {
        submitBtn.disabled = false;
        submitBtn.style.background = '#4a7c44';
    } else {
        submitBtn.disabled = true;
        submitBtn.style.background = '#ccc';
    }
}

// Event listeners
rgpdCheckbox.addEventListener('change', checkFormValidity);
document.querySelectorAll('input, select').forEach(el => el.addEventListener('input', checkFormValidity));

function toggleAutre() {
    const s = document.getElementById('rue');
    const a = document.getElementById('rue_autre');
    if (s.value === 'autre') { a.style.display = 'block'; a.required = true; } 
    else { a.style.display = 'none'; a.required = false; a.value = ''; }
    checkFormValidity();
}

function setRuleState(id, isValid) {
    const el = document.getElementById(id);
    el.className = isValid ? 'valid' : 'invalid';
    el.innerHTML = el.innerHTML.replace(/[✓✗]/g, '') + (isValid ? ' ✓' : ' ✗');
}

document.getElementById('password').addEventListener('input', function() {
    const v = this.value;
    setRuleState('rule-length', v.length >= 8);
    setRuleState('rule-upper', /[A-Z]/.test(v));
    setRuleState('rule-number', /[0-9]/.test(v));
    setRuleState('rule-special', /[\W_]/.test(v));
    setRuleState('rule-match', (v === document.getElementById('password_confirm').value && v !== ''));
});
document.getElementById('password_confirm').addEventListener('input', () => {
    setRuleState('rule-match', (document.getElementById('password').value === document.getElementById('password_confirm').value && document.getElementById('password').value !== ''));
});
</script>
</body>
</html>