<?php
session_start();
require_once 'config.php';
require_once 'functions.php';

if (isset($_SESSION['user_id'])) { header("Location: index.php"); exit; }

$error = ''; $success = '';
$sslEnabled = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');

// Migration colonne birthdate
try { $pdo->exec("ALTER TABLE users ADD COLUMN IF NOT EXISTS birthdate DATE DEFAULT NULL"); } catch(Exception $e){}
try { $pdo->exec("ALTER TABLE users ADD COLUMN IF NOT EXISTS is_minor TINYINT(1) DEFAULT 0"); } catch(Exception $e){}
try { $pdo->exec("ALTER TABLE users ADD COLUMN IF NOT EXISTS is_private_user TINYINT(1) DEFAULT 0"); } catch(Exception $e){} // v1.7

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['register'])) {
    $username  = trim(htmlspecialchars($_POST['username'] ?? ''));
    $email     = trim(strtolower($_POST['email'] ?? ''));
    $password  = $_POST['password'] ?? '';
    $confirm   = $_POST['confirm'] ?? '';
    $birthdate      = $_POST['birthdate'] ?? '';
    \$isPrivateUser  = isset(\$_POST['is_private_user']) ? 1 : 0; // v1.7

    // Validations
    if (strlen($username) < 3 || strlen($username) > 50) $error = "Nom d'utilisateur : 3 à 50 caractères.";
    elseif (!filter_var($email, FILTER_VALIDATE_EMAIL))   $error = "Adresse courriel invalide.";
    elseif (strlen($password) < 6)                        $error = "Mot de passe : minimum 6 caractères.";
    elseif ($password !== $confirm)                        $error = "Les mots de passe ne correspondent pas.";
    elseif (empty($birthdate))                             $error = "La date de naissance est obligatoire.";
    else {
        // Vérifier l'âge
        $birth   = new DateTime($birthdate);
        $today   = new DateTime();
        $age     = $today->diff($birth)->y;
        $isMinor = ($age < 18);

        $detectedAge  = (int)($_POST['detected_age'] ?? 0);
        $faceCaptured = (int)($_POST['face_captured'] ?? 0);

        if ($age < 13) {
            $error = "Vous devez avoir au moins 13 ans pour créer un compte.";
        } elseif ($sslEnabled && $faceCaptured !== 1) {
            $error = "La vérification par caméra est obligatoire. Veuillez prendre une photo ou cliquer sur Passer.";
        } elseif ($sslEnabled && $faceCaptured === 1 && $detectedAge === 0) {
            $error = "Aucun visage détecté sur la photo. Veuillez réessayer en vous plaçant bien dans le cercle.";
        } elseif ($sslEnabled && $detectedAge > 0 && $detectedAge !== 99 && $detectedAge < 18) {
            $error = "Âge estimé par la caméra : {$detectedAge} ans. Vous devez avoir 18 ans ou plus.";
        } else {
            // Vérifier doublon
            $chk = $pdo->prepare("SELECT id FROM users WHERE email = ? OR username = ?");
            $chk->execute([$email, $username]);
            if ($chk->fetch()) {
                $error = "Ce nom d'utilisateur ou courriel est déjà utilisé.";
            } else {
                $hash = password_hash($password, PASSWORD_BCRYPT);
                try {
                    $stmt = $pdo->prepare("INSERT INTO users (username, email, password, tier, points, interaction_points, language, wallet_points, last_daily_bonus, birthdate, is_minor, is_private_user) VALUES (?, ?, ?, 'free', 0, 0, 'CA-FR', 0, NULL, ?, ?, ?)");
                    $stmt->execute([$username, $email, $hash, $birthdate, $isMinor ? 1 : 0, $isPrivateUser]); // v1.7
                } catch (Exception $e) {
                    $stmt = $pdo->prepare("INSERT INTO users (username, email, password, tier, points, interaction_points, language) VALUES (?, ?, ?, 'free', 0, 0, 'CA-FR')");
                    $stmt->execute([$username, $email, $hash]);
                }
                $newId = (int)$pdo->lastInsertId();

                // user_stats
                try { $pdo->prepare("INSERT IGNORE INTO user_stats (user_id) VALUES (?)")->execute([$newId]); } catch(Exception $e){}
                // Cercle par défaut
                try { $pdo->prepare("INSERT IGNORE INTO circle_members (circle_id, user_id) VALUES (1, ?)")->execute([$newId]); } catch(Exception $e){}
                // Notification bienvenue
                try { addNotification($pdo, $newId, "Bienvenue sur JeTeGageQue, {$username} ! Lance ton premier gage.", "index.php"); } catch(Exception $e){}
                // Bonus bienvenue (seulement si majeur — pas de jetons pour les mineurs)
                if (!$isMinor) {
                    try {
                        $pdo->prepare("UPDATE users SET wallet_points=50 WHERE id=?")->execute([$newId]);
                        $pdo->prepare("INSERT INTO wallet_transactions (user_id,amount,type,description) VALUES (?,50,'admin_grant','Bonus de bienvenue')")->execute([$newId]);
                    } catch(Exception $e){}
                }

                $_SESSION['user_id']     = $newId;
                $_SESSION['auth_method'] = 'password';
                $_SESSION['circle_id']   = 1;
                $_SESSION['is_minor']    = $isMinor;
                header("Location: index.php"); exit;
            }
        }
    }
}

include 'header.php';
?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<style>
#faceBox { position:relative; border-radius:8px; overflow:hidden; background:#0a0a14; }
#faceBox video { width:100%; border-radius:8px; display:block; }
#faceOverlay { position:absolute; inset:0; display:flex; align-items:center; justify-content:center; pointer-events:none; }
.face-ring { width:160px; height:160px; border:3px solid #0dcaf0; border-radius:50%; opacity:0.6; }
#faceStatus { font-size:0.68rem; text-align:center; margin-top:6px; min-height:18px; }
#captureCanvas { display:none; }
</style>

<div class="container mt-4 mb-5">
    <div class="row justify-content-center">
        <div class="col-md-6 col-lg-5">
            <div class="card bg-dark border-info shadow-lg">
                <div class="card-header text-center py-3" style="background:#050520;border-bottom:2px solid #0dcaf0;">
                    <h4 class="oracle-text text-info mb-0" style="font-size:1rem;letter-spacing:2px;">CRÉER UN PROFIL</h4>
                </div>
                <div class="card-body p-4">
                    <?php if ($error): ?>
                    <div class="alert alert-danger small py-2"><?= htmlspecialchars($error) ?></div>
                    <?php endif; ?>

                    <form method="POST" id="regForm">

                        <!-- Nom d'utilisateur -->
                        <div class="mb-3">
                            <label class="small text-white fw-bold d-block mb-1" style="font-size:0.68rem;">NOM D'UTILISATEUR</label>
                            <input type="text" name="username" class="form-control bg-dark text-white border-secondary"
                                   placeholder="Ex: Joueur_Elite" maxlength="50" required
                                   value="<?= htmlspecialchars($_POST['username'] ?? '') ?>">
                        </div>

                        <!-- Date de naissance -->
                        <div class="mb-3">
                            <label class="small text-white fw-bold d-block mb-1" style="font-size:0.68rem;">DATE DE NAISSANCE <span class="text-danger">*</span></label>
                            <input type="date" name="birthdate" id="birthdate" class="form-control bg-dark text-white border-secondary" required
                                   max="<?= date('Y-m-d', strtotime('-13 years')) ?>"
                                   value="<?= htmlspecialchars($_POST['birthdate'] ?? '') ?>"
                                   onchange="checkAge(this.value)">
                            <div id="ageMsg" class="mt-1" style="font-size:0.62rem;"></div>
                        </div>

                        <!-- Courriel -->
                        <div class="mb-3">
                            <label class="small text-white fw-bold d-block mb-1" style="font-size:0.68rem;">COURRIEL</label>
                            <input type="email" name="email" class="form-control bg-dark text-white border-secondary"
                                   placeholder="ton@email.com" required
                                   value="<?= htmlspecialchars($_POST['email'] ?? '') ?>">
                        </div>

                        <!-- Mots de passe -->
                        <div class="mb-3">
                            <label class="small text-white fw-bold d-block mb-1" style="font-size:0.68rem;">MOT DE PASSE</label>
                            <div class="input-group">
                                <input type="password" id="pwd1" name="password" class="form-control bg-dark text-white border-secondary"
                                       placeholder="Minimum 6 caractères" required>
                                <span class="input-group-text bg-dark border-secondary" style="cursor:pointer;" onclick="togglePwd('pwd1','eye1')">
                                    <i id="eye1" class="fa-solid fa-eye text-info" style="font-size:14px;"></i>
                                </span>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="small text-white fw-bold d-block mb-1" style="font-size:0.68rem;">CONFIRMER LE MOT DE PASSE</label>
                            <div class="input-group">
                                <input type="password" id="pwd2" name="confirm" class="form-control bg-dark text-white border-secondary"
                                       placeholder="Répète ton mot de passe" required>
                                <span class="input-group-text bg-dark border-secondary" style="cursor:pointer;" onclick="togglePwd('pwd2','eye2')">
                                    <i id="eye2" class="fa-solid fa-eye text-info" style="font-size:14px;"></i>
                                </span>
                            </div>
                        </div>

                        <?php if ($sslEnabled): ?>
                        <!-- ── Vérification visage (SSL requis) ──────────────── -->
                        <div class="mb-3" id="faceSection">
                            <label class="small text-white fw-bold d-block mb-2" style="font-size:0.68rem;">
                                VÉRIFICATION DE PRÉSENCE <span class="text-muted" style="font-weight:normal;">(optionnel)</span>
                            </label>
                            <div id="faceBox" style="max-height:220px;">
                                <video id="faceVideo" autoplay muted playsinline></video>
                                <div id="faceOverlay"><div class="face-ring" id="faceRing"></div></div>
                            </div>
                            <canvas id="captureCanvas" width="320" height="240"></canvas>
                            <div id="faceStatus" class="text-muted">Démarrage de la caméra...</div>
                            <input type="hidden" name="face_captured" id="faceCaptured" value="0">
                            <input type="hidden" name="detected_age" id="detectedAgeField" value="0">
                            <div class="d-flex gap-2 mt-2">
                                <button type="button" onclick="captureFace()" class="btn btn-outline-info btn-sm flex-grow-1" style="font-size:0.65rem;">
                                    <i class="fa-solid fa-camera me-1"></i>Prendre une photo
                                </button>
                                <button type="button" onclick="skipFace()" class="btn btn-outline-secondary btn-sm" style="font-size:0.65rem;">Passer</button>
                            </div>
                        </div>
                        <?php else: ?>
                        <!-- SSL non actif — vérification désactivée -->
                        <div class="alert py-2 mb-3" style="background:rgba(255,193,7,0.08);border:1px solid #ffc107;font-size:0.65rem;color:#ffc107;">
                            <i class="fa-solid fa-triangle-exclamation me-1"></i>
                            Vérification de présence désactivée — SSL non actif sur ce serveur.
                        </div>
                        <?php endif; ?>

                        <!-- v1.7 — Compte privé (famille/école/entreprise) -->
                        <div class="mb-3 p-2 rounded" style="background:rgba(167,139,250,0.07);border:1px solid rgba(167,139,250,0.25);">
                            <div class="form-check">
                                <input type="checkbox" name="is_private_user" id="isPrivateUser" class="form-check-input" value="1"
                                       onchange="togglePrivateInfo(this.checked)">
                                <label class="form-check-label text-white small fw-bold" for="isPrivateUser" style="font-size:0.68rem;">
                                    🏠 Compte Famille / École / Entreprise
                                </label>
                            </div>
                            <div id="privateUserInfo" style="display:none;margin-top:6px;font-size:0.6rem;color:#a78bfa;line-height:1.5;">
                                Ce type de compte donne accès à une interface simplifiée — engagements en groupe privé, classements internes, récompenses texte. Pas de gages publics ni de jetons.
                            </div>
                        </div>

                        <div class="d-grid mt-2">
                            <button type="submit" name="register" class="btn btn-info fw-bold" style="letter-spacing:1px;">
                                <i class="fa-solid fa-user-plus me-1"></i>CRÉER MON COMPTE
                            </button>
                        </div>
                    </form>
                </div>
                <div class="card-footer text-center border-top border-secondary" style="background:#040410;">
                    <a href="index.php" class="text-muted small">Déjà membre ? Se connecter</a>
                    &nbsp;·&nbsp;
                    <a href="forgot_password.php" class="text-muted small">Mot de passe oublié</a>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// v1.7 — Compte privé
function togglePrivateInfo(checked) {
    document.getElementById('privateUserInfo').style.display = checked ? 'block' : 'none';
}

function togglePwd(f, i) {
    el.type = el.type === 'password' ? 'text' : 'password';
    ic.classList.toggle('fa-eye'); ic.classList.toggle('fa-eye-slash');
}

function checkAge(val) {
    if (!val) return;
    const birth = new Date(val), today = new Date();
    let age = today.getFullYear() - birth.getFullYear();
    const m = today.getMonth() - birth.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birth.getDate())) age--;
    const msg = document.getElementById('ageMsg');
    if (age < 13) {
        msg.innerHTML = '<span style="color:#dc3545;"><i class="fa-solid fa-ban me-1"></i>Vous devez avoir 13 ans minimum.</span>';
        document.querySelector('[name=register]').disabled = true;
    } else if (age < 18) {
        msg.innerHTML = '<span style="color:#ffc107;"><i class="fa-solid fa-triangle-exclamation me-1"></i>Mineur ('+age+' ans) — Jetons et mises désactivés.</span>';
        document.querySelector('[name=register]').disabled = false;
    } else {
        msg.innerHTML = '<span style="color:#28a745;"><i class="fa-solid fa-circle-check me-1"></i>'+age+' ans — Accès complet.</span>';
        document.querySelector('[name=register]').disabled = false;
    }
}

<?php if ($sslEnabled): ?>
// Bloquer la soumission si visage non vérifié
document.querySelector('form').addEventListener('submit', function(e) {
    const captured = document.getElementById('faceCaptured')?.value;
    const age      = document.getElementById('detectedAgeField')?.value;
    if (captured !== '1') {
        e.preventDefault();
        document.getElementById('faceStatus').innerHTML = '<span style="color:#dc3545;">❌ Vous devez prendre une photo avant de vous inscrire.</span>';
        document.getElementById('faceSection').scrollIntoView({behavior:'smooth'});
        return false;
    }
    if (parseInt(age) === 0) {
        e.preventDefault();
        document.getElementById('faceStatus').innerHTML = '<span style="color:#dc3545;">❌ Aucun visage détecté — repositionnez-vous et réessayez.</span>';
        document.getElementById('faceSection').scrollIntoView({behavior:'smooth'});
        return false;
    }
});
<?php endif; ?>

<?php if ($sslEnabled): ?>
// ── Vérification visage + âge via face-api.js ──────────────────
let stream     = null;
let faceOk     = false;
let modelsReady = false;
let detectedAge = null;

// Chemin vers les modèles (relatif au fichier register.php)
const MODEL_PATH = 'models';

async function loadFaceModels() {
    const status = document.getElementById('faceStatus');
    status.innerHTML = '<span style="color:#888;">Chargement des modèles IA...</span>';
    try {
        await Promise.all([
            faceapi.nets.tinyFaceDetector.loadFromUri(MODEL_PATH),
            faceapi.nets.ageGenderNet.loadFromUri(MODEL_PATH),
        ]);
        modelsReady = true;
        status.innerHTML = '<span style="color:#0dcaf0;">Caméra active — Placez votre visage dans le cercle</span>';
    } catch(e) {
        console.error('Modèles face-api non chargés:', e);
        console.error('MODEL_PATH utilisé:', MODEL_PATH);
        // Fallback: vérification basique sans IA
        modelsReady = false;
        status.innerHTML = '<span style="color:#ffc107;">⚠ Modèles IA indisponibles — cliquez <strong>Passer</strong> pour continuer.</span>';
    }
}

async function startCamera() {
    try {
        stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user', width:320, height:240 }, audio: false });
        document.getElementById('faceVideo').srcObject = stream;
        await loadFaceModels();
        // Détection en temps réel
        if (modelsReady) startLiveDetection();
    } catch(e) {
        document.getElementById('faceSection').style.display = 'none';
        console.warn('Caméra non disponible:', e.message);
    }
}

let liveDetectInterval = null;
function startLiveDetection() {
    const video  = document.getElementById('faceVideo');
    const ring   = document.getElementById('faceRing');
    const status = document.getElementById('faceStatus');
    liveDetectInterval = setInterval(async () => {
        if (!modelsReady || video.paused || video.ended) return;
        try {
            const det = await faceapi.detectSingleFace(video, new faceapi.TinyFaceDetectorOptions())
                                      .withAgeAndGender();
            if (det) {
                detectedAge = Math.round(det.age);
                const gender = det.gender === 'male' ? 'homme' : 'femme';
                ring.style.borderColor = '#0dcaf0';
                status.innerHTML = `<span style="color:#0dcaf0;">✓ Visage détecté — Âge estimé: <strong>${detectedAge} ans</strong> (${gender})</span>`;
            } else {
                ring.style.borderColor = '#ffc107';
                detectedAge = null;
                status.innerHTML = '<span style="color:#ffc107;">⚠ Aucun visage détecté — centrez votre visage</span>';
            }
        } catch(e) {}
    }, 800);
}

async function captureFace() {
    const video  = document.getElementById('faceVideo');
    const canvas = document.getElementById('captureCanvas');
    const ctx    = canvas.getContext('2d');
    const status = document.getElementById('faceStatus');
    ctx.drawImage(video, 0, 0, 320, 240);

    if (modelsReady) {
        // Vérification avec face-api.js
        status.innerHTML = '<span style="color:#888;">Analyse en cours...</span>';
        try {
            const det = await faceapi.detectSingleFace(canvas, new faceapi.TinyFaceDetectorOptions())
                                      .withAgeAndGender();
            if (!det) {
                status.innerHTML = '<span style="color:#dc3545;">❌ Aucun visage détecté. Réessayez.</span>';
                return;
            }
            detectedAge = Math.round(det.age);
            const gender = det.gender === 'male' ? 'homme' : 'femme';

            if (detectedAge < 18) {
                // Âge estimé < 18 ans → bloquer
                status.innerHTML = `<span style="color:#dc3545;">❌ Âge estimé: ${detectedAge} ans — Vous devez avoir 18 ans ou plus.</span>`;
                document.getElementById('faceCaptured').value = '0';
                return;
            }

            // OK — âge estimé ≥ 18
            document.getElementById('faceCaptured').value = '1';
            document.getElementById('detectedAgeField').value = detectedAge;
            faceOk = true;
            status.innerHTML = `<span style="color:#28a745;">✅ Vérification réussie — Âge estimé: ${detectedAge} ans (${gender})</span>`;
            document.getElementById('faceRing').style.borderColor = '#28a745';

        } catch(e) {
            status.innerHTML = '<span style="color:#dc3545;">Erreur analyse. Réessayez.</span>';
            return;
        }
    } else {
        // Modèles IA non chargés — impossible de valider sans IA
        status.innerHTML = '<span style="color:#dc3545;">❌ Modèles IA non chargés. Cliquez sur <strong>Passer</strong> pour continuer sans vérification.</span>';
        return;
    }

    if (liveDetectInterval) clearInterval(liveDetectInterval);
    if (stream) stream.getTracks().forEach(t => t.stop());
    const imgData = canvas.toDataURL('image/jpeg', 0.7);
    const img = document.createElement('img');
    img.src = imgData;
    img.style.cssText = 'width:100%;border-radius:8px;';
    const box = document.getElementById('faceBox');
    box.innerHTML = '';
    box.appendChild(img);
}

function skipFace() {
    // Permettre l'inscription même sans vérification caméra
    document.getElementById('faceSection').style.display = 'none';
    document.getElementById('faceCaptured').value = '1';
    document.getElementById('detectedAgeField').value = '99'; // valeur neutre pour bypass
    if (liveDetectInterval) clearInterval(liveDetectInterval);
    if (stream) stream.getTracks().forEach(t => t.stop());
}

// Charger face-api.js depuis CDN
const faceScript = document.createElement('script');
faceScript.src = 'https://cdn.jsdelivr.net/npm/face-api.js@0.22.2/dist/face-api.min.js';
faceScript.onload = () => startCamera();
faceScript.onerror = () => {
    // Si CDN indisponible, démarrer sans IA
    window.faceapi = null;
    modelsReady = false;
    startCamera();
};
document.head.appendChild(faceScript);
<?php endif; ?>
</script>

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