<?php
/**
 * Page de connexion Admin - SERVICES-AE
 */

// Configuration et démarrage de la session
require_once __DIR__ . '/admin/session-config.php';
session_start();

// Si déjà connecté, rediriger vers l'admin
if (isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true) {
    header("Location: admin/index.php");
    exit();
}

// Gestion des messages d'URL
$message = '';
$message_type = 'info';

if (isset($_GET['msg'])) {
    switch ($_GET['msg']) {
        case 'auth_required':
            $message = 'Vous devez vous connecter pour accéder à cette page.';
            $message_type = 'warning';
            break;
        case 'session_expired':
            $message = 'Votre session a expiré. Veuillez vous reconnecter.';
            $message_type = 'info';
            break;
        case 'logged_out':
            $message = 'Vous avez été déconnecté avec succès.';
            $message_type = 'success';
            break;
        case 'access_denied':
            $message = 'Accès refusé. Connexion requise.';
            $message_type = 'danger';
            break;
    }
}

// Récupérer l'URL de redirection après connexion
$redirect_url = $_GET['redirect'] ?? 'admin/index.php';

// Traitement du formulaire de connexion
$error_message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Bloc de validation du code de vérification
    if (isset($_POST['verify_code']) && isset($_SESSION['admin_pending_code'])) {
        $code_saisi = trim($_POST['verify_code']);
        $code_attendu = $_SESSION['admin_pending_code'];
        if ($code_saisi === (string)$code_attendu) {
            // Connexion réussie
            $_SESSION['admin_logged_in'] = true;
            $_SESSION['admin_user_id'] = $_SESSION['admin_pending_id'];
            $_SESSION['admin_username'] = $_SESSION['admin_pending_username'];
            $_SESSION['admin_email'] = $_SESSION['admin_pending_email'];
            // Optionnel : rôle, avatar, support_name (à récupérer si besoin)
            $_SESSION['admin_login_time'] = time();
            $_SESSION['admin_last_activity'] = time();
            // Nettoyer les variables de vérification
            unset($_SESSION['admin_pending_id'], $_SESSION['admin_pending_code'], $_SESSION['admin_pending_email'], $_SESSION['admin_pending_username']);
            // Redirection vers le panel admin
            header('Location: admin/index.php');
            exit();
        } else {
            // Code incorrect
            echo '<!DOCTYPE html><html lang="fr"><head><meta charset="utf-8"><title>Vérification Email Admin</title>'
                . '<link rel="stylesheet" href="admin/pages/assets/vendor/css/core.css" />'
                . '<link rel="stylesheet" href="admin/pages/assets/css/demo.css" />'
                . '<style>.verify-box{max-width:400px;margin:40px auto;padding:32px;background:#fff;border-radius:12px;box-shadow:0 4px 16px rgba(0,0,0,0.08);} .verify-title{color:#696cff;font-weight:bold;font-size:1.3em;margin-bottom:16px;} .verify-label{font-weight:500;margin-bottom:8px;} .verify-input{font-size:1.5em;letter-spacing:8px;text-align:center;}</style>'
                . '</head><body><div class="verify-box">'
                . '<div class="verify-title">Vérification Email</div>'
                . '<div class="alert alert-danger" role="alert" style="margin-bottom:18px;">Code incorrect. Veuillez réessayer.</div>'
                . '<form method="POST"><label class="verify-label" for="verify_code">Code reçu par email :</label>'
                . '<input type="text" name="verify_code" id="verify_code" class="form-control verify-input" maxlength="6" pattern="[0-9]{6}" required autocomplete="off" style="margin-bottom:18px;" />'
                . '<button type="submit" class="btn btn-primary w-100">Valider</button>'
                . '<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">'
                . '</form>'
                . '<script src="https://www.google.com/recaptcha/api.js?render=6LcFBfIrAAAAAIKKEsTvoxV0TOqBzIUeJrUOP-4s"></script>'
                . '<script>grecaptcha.ready(function() { grecaptcha.execute("6LcFBfIrAAAAAIKKEsTvoxV0TOqBzIUeJrUOP-4s", {action: "submit"}).then(function(token) { document.getElementById("g-recaptcha-response").value = token; }); });</script>'
                . '</div></body></html>';
            exit();
        }
    }
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $redirect_after_login = $_POST['redirect_url'] ?? 'admin/index.php';
    
    try {
        // Inclure les classes nécessaires
        require_once 'config/config.php';
        require_once 'config/db.php';
        require_once 'admin/AdminUser.php';
        
        // Initialiser la classe AdminUser
        $adminUser = new AdminUser($pdo);
        
        // Vérifier et créer la table si nécessaire
        if (!$adminUser->tableExists()) {
            $adminUser->createTable();
        }
        
        // Authentifier l'utilisateur
        $user = $adminUser->authenticate($username, $password);
        
        if ($user) {
            // Vérification par email : générer un code à 6 chiffres
            $verification_code = random_int(100000, 999999);
            $_SESSION['admin_pending_id'] = $user['id'];
            $_SESSION['admin_pending_code'] = $verification_code;
            $_SESSION['admin_pending_email'] = $user['email'];
            $_SESSION['admin_pending_username'] = $user['username'];

            // Envoi du mail HTML
            require_once __DIR__ . '/PHPMailer/src/PHPMailer.php';
            require_once __DIR__ . '/PHPMailer/src/SMTP.php';
            require_once __DIR__ . '/PHPMailer/src/Exception.php';
            $db = getDbConnection();
            $row = $db->query('SELECT * FROM smtp_config WHERE id=1')->fetch(PDO::FETCH_ASSOC);
            $mail = new \PHPMailer\PHPMailer\PHPMailer(true);
            try {
                $mail->isSMTP();
                $mail->Host = $row['smtp_host'];
                $mail->Port = (int)$row['smtp_port'];
                $mail->SMTPAuth = true;
                $mail->Username = $row['smtp_user'];
                $mail->Password = $row['smtp_pass'];
                $mail->CharSet = 'UTF-8';
                $mail->setFrom($row['smtp_from'], 'Panel Admin');
                $mail->addAddress($user['email']);
                $mail->Subject = 'Code de vérification - Connexion Admin SERVICES-AE';
                $mail->isHTML(true);
                if ($row['smtp_ssl'] === 'ssl') $mail->SMTPSecure = \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS;
                elseif ($row['smtp_ssl'] === 'tls') $mail->SMTPSecure = \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
                else $mail->SMTPSecure = false;
                $mail->SMTPOptions = [
                    'ssl' => [
                        'verify_peer' => false,
                        'verify_peer_name' => false,
                        'allow_self_signed' => true
                    ]
                ];
                $mail->Body = '<div style="font-family:Arial,sans-serif;font-size:1.1em;padding:24px;background:#f8f9fa;border-radius:8px;border:1px solid #e0e0e0;color:#333;text-align:center;max-width:400px;margin:auto;">'
                    . '<h2 style="color:#696cff;">Connexion Admin - Vérification</h2>'
                    . '<p>Bonjour <b>' . htmlspecialchars($user['username']) . '</b>,</p>'
                    . '<p>Voici votre code de vérification :</p>'
                    . '<div style="font-size:2em;font-weight:bold;letter-spacing:6px;background:#fff;border:2px dashed #696cff;padding:16px;margin:16px 0;">'
                    . $verification_code . '</div>'
                    . '<p>Veuillez saisir ce code pour finaliser votre connexion.</p>'
                    . '<p style="font-size:0.9em;color:#888;">Ce code est valable 10 minutes.</p>'
                    . '</div>';
                $mail->send();
            } catch (Exception $e) {
                error_log('Erreur envoi mail vérification admin: ' . $mail->ErrorInfo);
                $error_message = "Erreur lors de l'envoi du mail de vérification. Contactez l'administrateur.";
                goto end_login_form;
            }

            // Afficher le formulaire de saisie du code
            echo '<!DOCTYPE html><html lang="fr"><head><meta charset="utf-8"><title>Vérification Email Admin</title>';
            echo '<link rel="stylesheet" href="admin/pages/assets/vendor/css/core.css" />';
            echo '<link rel="stylesheet" href="admin/pages/assets/css/demo.css" />';
            echo '<style>.verify-box{max-width:400px;margin:40px auto;padding:32px;background:#fff;border-radius:12px;box-shadow:0 4px 16px rgba(0,0,0,0.08);} .verify-title{color:#696cff;font-weight:bold;font-size:1.3em;margin-bottom:16px;} .verify-label{font-weight:500;margin-bottom:8px;} .verify-input{font-size:1.5em;letter-spacing:8px;text-align:center;}</style>';
            echo '</head><body><div class="verify-box">';
            echo '<div class="verify-title">Vérification Email</div>';
            echo '<form method="POST"><label class="verify-label" for="verify_code">Code reçu par email :</label>';
            echo '<input type="text" name="verify_code" id="verify_code" class="form-control verify-input" maxlength="6" pattern="[0-9]{6}" required autocomplete="off" style="margin-bottom:18px;" />';
            echo '<button type="submit" class="btn btn-primary w-100">Valider</button>';
            echo '<script src="https://www.google.com/recaptcha/api.js?render=6LcFBfIrAAAAAIKKEsTvoxV0TOqBzIUeJrUOP-4s"></script>';
            echo '<script>grecaptcha.ready(function() { grecaptcha.execute("6LcFBfIrAAAAAIKKEsTvoxV0TOqBzIUeJrUOP-4s", {action: "submit"}).then(function(token) { document.getElementById("g-recaptcha-response").value = token; }); });</script>';
            echo '<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">';
            echo '</form></div></body></html>';
            exit();
            end_login_form:
        } else {
            $error_message = 'Nom d\'utilisateur ou mot de passe incorrect.';
            
            // Log de sécurité
            error_log("Admin login failed at " . date('Y-m-d H:i:s') . " from IP: " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown') . " - Username: " . $username);
        }
    } catch (Exception $e) {
        $error_message = 'Erreur de connexion à la base de données.';
        error_log("Admin login error: " . $e->getMessage());
    }
}
?>
<!DOCTYPE html>
<html lang="fr" class="layout-menu-fixed layout-compact" data-theme="theme-default" data-assets-path="admin/pages/assets/" data-template="vertical-menu-template-free">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0" />
    <meta name="robots" content="noindex, nofollow" />

    <title>Connexion Admin - SERVICES-AE</title>

    <!-- Favicon -->
    <link rel="icon" type="image/x-icon" href="images/fevicon/fevicon.png" />

    <!-- Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet" />

    <link rel="stylesheet" href="admin/pages/assets/vendor/fonts/iconify-icons.css" />

    <!-- Core CSS -->
    <link rel="stylesheet" href="admin/pages/assets/vendor/css/core.css" />
    <link rel="stylesheet" href="admin/pages/assets/css/demo.css" />

    <!-- Vendors CSS -->
    <link rel="stylesheet" href="admin/pages/assets/vendor/libs/perfect-scrollbar/perfect-scrollbar.css" />

    <!-- Page CSS -->
    <link rel="stylesheet" href="admin/pages/assets/vendor/css/pages/page-auth.css" />

    <!-- Custom CSS -->
    <style>
        .auth-wrapper {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }
        
        .auth-card {
            border: 3px solid #696cff;
            border-radius: 15px;
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
        }
        
        .services-brand {
            color: #696cff;
            font-weight: bold;
        }
        
        .btn-primary {
            background: #696cff;
            border-color: #696cff;
        }
        
        .btn-primary:hover {
            background: #5a5fe7;
            border-color: #5a5fe7;
        }
    </style>

    <!-- Helpers -->
    <script src="admin/pages/assets/vendor/js/helpers.js"></script>
    <script src="admin/pages/assets/js/config.js"></script>
</head>

<body>
    <!-- Content -->
    <div class="container-xxl">
        <div class="authentication-wrapper authentication-basic container-p-y">
            <div class="authentication-inner">
                
                <!-- Login Card -->
                <div class="card auth-card">
                    <div class="card-body">
                        <!-- Logo -->
                        <div class="app-brand justify-content-center mb-4">
                            <div class="app-brand-link gap-2">
                                <span class="app-brand-logo demo">
                                    <i class="ri-admin-line" style="font-size: 2rem; color: #696cff;"></i>
                                </span>
                                <span class="app-brand-text demo text-body fw-bold services-brand">SERVICES-AE</span>
                            </div>
                        </div>
                        
                        <!-- Titre -->
                        <h4 class="mb-1">Bienvenue Admin! 👋</h4>
                        <p class="mb-4">Connectez-vous à votre compte pour accéder au panel d'administration</p>

                        <!-- Messages système -->
                        <?php if (!empty($message)): ?>
                        <div class="alert alert-<?php echo $message_type; ?>" role="alert">
                            <i class="ri ri-information-line me-2"></i>
                            <?php echo htmlspecialchars($message); ?>
                        </div>
                        <?php endif; ?>

                        <!-- Message d'erreur -->
                        <?php if (!empty($error_message)): ?>
                        <div class="alert alert-danger" role="alert">
                            <i class="ri ri-error-warning-line me-2"></i>
                            <?php echo htmlspecialchars($error_message); ?>
                        </div>
                        <?php endif; ?>

                        <!-- Formulaire de connexion -->
                        <form id="formAuthentication" class="mb-3" method="POST">
                            <!-- Champ caché pour la redirection -->
                            <input type="hidden" name="redirect_url" value="<?php echo htmlspecialchars($redirect_url); ?>" />
                            
                            <div class="mb-3">
                                <label for="username" class="form-label">Nom d'utilisateur ou adresse email</label>
                                <input
                                    type="text"
                                    class="form-control"
                                    id="username"
                                    name="username"
                                    placeholder="Entrez votre nom d'utilisateur ou email"
                                    value="<?php echo htmlspecialchars($_POST['username'] ?? ''); ?>"
                                    required
                                    autofocus />
                            </div>
                            <div class="mb-3 form-password-toggle">
                                <div class="d-flex justify-content-between">
                                    <label class="form-label" for="password">Mot de passe</label>
                                </div>
                                <div class="input-group input-group-merge">
                                    <input
                                        type="password"
                                        id="password"
                                        class="form-control"
                                        name="password"
                                        placeholder="············"
                                        required />
                                    <span class="input-group-text cursor-pointer">
                                        <i class="ri ri-eye-off-line"></i>
                                    </span>
                                </div>
                            </div>
                            <div class="mb-3">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="remember-me" />
                                    <label class="form-check-label" for="remember-me">Se souvenir de moi</label>
                                </div>
                            </div>
                            <div class="mb-3">
                                <button class="btn btn-primary d-grid w-100" type="submit">
                                    <i class="ri ri-login-box-line me-2"></i>
                                    Se connecter
                                </button>
                            </div>
                            <div class="mb-3 text-center">
                                <a href="admin-forgot-password.php" class="text-primary" style="font-size:1em;">Mot de passe oublié&nbsp;?</a>
                            </div>
                        
                        <script src='https://www.google.com/recaptcha/api.js?render=6LcFBfIrAAAAAIKKEsTvoxV0TOqBzIUeJrUOP-4s'></script>
<script>grecaptcha.ready(function() { grecaptcha.execute('6LcFBfIrAAAAAIKKEsTvoxV0TOqBzIUeJrUOP-4s', {action: 'submit'}).then(function(token) { document.getElementById('g-recaptcha-response').value = token; }); });</script>
<input type='hidden' id='g-recaptcha-response' name='g-recaptcha-response'>
</form>
                    </div>
                </div>
                <!-- / Login Card -->
            </div>
        </div>
    </div>

    <!-- Core JS -->
    <script src="admin/pages/assets/vendor/libs/jquery/jquery.js"></script>
    <script src="admin/pages/assets/vendor/libs/popper/popper.js"></script>
    <script src="admin/pages/assets/vendor/js/bootstrap.js"></script>
    <script src="admin/pages/assets/vendor/libs/perfect-scrollbar/perfect-scrollbar.js"></script>
    <script src="admin/pages/assets/vendor/js/menu.js"></script>

    <!-- Page JS -->
    <script>
        // Toggle password visibility
        document.querySelector('.input-group-text').addEventListener('click', function() {
            const passwordInput = document.getElementById('password');
            const icon = this.querySelector('i');
            
            if (passwordInput.type === 'password') {
                passwordInput.type = 'text';
                icon.className = 'ri ri-eye-line';
            } else {
                passwordInput.type = 'password';
                icon.className = 'ri ri-eye-off-line';
            }
        });
        
        // Focus sur le premier champ
        document.addEventListener('DOMContentLoaded', function() {
            document.getElementById('username').focus();
        });
    </script>
</body>

</html>