<?php
// Page de récupération du mot de passe admin
require_once 'config/config.php';
require_once 'config/db.php';
require_once 'admin/AdminUser.php';

$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['reset_code'], $_POST['new_password'], $_POST['confirm_password'], $_POST['email'])) {
        $email = trim($_POST['email']);
        $code = trim($_POST['reset_code']);
        $new_password = $_POST['new_password'];
        $confirm_password = $_POST['confirm_password'];
        $adminUser = new AdminUser($pdo);
        $stmt = $pdo->prepare("SELECT id, reset_code, reset_expires FROM admin_users WHERE email = ?");
        $stmt->execute([$email]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        // Vérification du code
        if (!$user || $user['reset_code'] !== $code || strtotime($user['reset_expires']) < time()) {
            $message = "Code invalide ou expiré.";
            $step = 2;
        } elseif ($new_password !== $confirm_password) {
            $message = "Les mots de passe ne correspondent pas.";
            $step = 2;
        } elseif (!preg_match('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\w\d]).{8,}$/', $new_password)) {
            $message = "Le mot de passe doit contenir au moins 8 caractères, une majuscule, une minuscule, un chiffre et un caractère spécial.";
            $step = 2;
        } else {
            $hashed = password_hash($new_password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("UPDATE admin_users SET password = ?, reset_code = NULL, reset_expires = NULL WHERE id = ?");
            $stmt->execute([$hashed, $user['id']]);
            // Redirection vers la page de login
            header('Location: admin-login.php?msg=reset_success');
            exit();
        }
    } else {
        $email = trim($_POST['email'] ?? '');
        if (empty($email)) {
            $message = "Veuillez saisir votre adresse email.";
        } else {
            $adminUser = new AdminUser($pdo);
            $user = $adminUser->getByEmail($email);
            if ($user) {
                // Générer un code de vérification
                $code = random_int(100000, 999999);
                $expires = date('Y-m-d H:i:s', time() + 600); // 10 min
                $stmt = $pdo->prepare("UPDATE admin_users SET reset_code = ?, reset_expires = ? WHERE id = ?");
                $stmt->execute([$code, $expires, $user['id']]);
                // Envoyer le mail
                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 réinitialisation - Panel Admin';
                    $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;">Réinitialisation du mot de passe</h2>'
                        . '<p>Bonjour <b>' . htmlspecialchars($user['username']) . '</b>,</p>'
                        . '<p>Voici votre code de réinitialisation :</p>'
                        . '<div style="font-size:2em;font-weight:bold;letter-spacing:6px;background:#fff;border:2px dashed #696cff;padding:16px;margin:16px 0;">'
                        . $code . '</div>'
                        . '<p>Ce code est valable 10 minutes.</p>'
                        . '</div>';
                    $mail->send();
                    $message = "Un code de réinitialisation a été envoyé à votre adresse email.";
                    $step = 2;
                } catch (Exception $e) {
                    $message = "Erreur lors de l'envoi du mail. Contactez l'administrateur.";
                }
            } else {
                $message = "Aucun compte admin trouvé avec cette adresse email.";
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="utf-8">
    <title>Mot de passe oublié - Panel Admin</title>
    <link rel="stylesheet" href="admin/pages/assets/vendor/css/core.css" />
    <link rel="stylesheet" href="admin/pages/assets/css/demo.css" />
    <style>.forgot-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);} .forgot-title{color:#696cff;font-weight:bold;font-size:1.3em;margin-bottom:16px;} .forgot-label{font-weight:500;margin-bottom:8px;}</style>
</head>
<body><div class="forgot-box">
    <div class="forgot-title">Mot de passe oublié</div>
    <?php if (!empty($message)): ?>
        <?php
        $isError = false;
        if (
            strpos($message, 'erreur') !== false ||
            strpos($message, 'invalide') !== false ||
            strpos($message, 'expiré') !== false ||
            strpos($message, 'correspondent pas') !== false ||
            strpos($message, 'aucun compte') !== false
        ) {
            $isError = true;
        }
        ?>
        <div class="alert <?php echo $isError ? 'alert-danger' : 'alert-info'; ?>" role="alert" style="margin-bottom:18px;"> <?php echo htmlspecialchars($message); ?> </div>
    <?php endif; ?>
    <?php if (!isset($step) || $step !== 2): ?>
    <form method="POST">
        <label class="forgot-label" for="email">Adresse email admin :</label>
        <input type="email" name="email" id="email" class="form-control" required autocomplete="off" style="margin-bottom:18px;" />
        <button type="submit" class="btn btn-primary w-100">Envoyer le code</button>
    </form>
    <?php else: ?>
    <form method="POST">
        <input type="hidden" name="email" value="<?php echo htmlspecialchars($_POST['email']); ?>" />
        <label class="forgot-label" for="reset_code">Code reçu par email :</label>
        <input type="text" name="reset_code" id="reset_code" class="form-control" maxlength="6" pattern="[0-9]{6}" required autocomplete="off" style="margin-bottom:18px;"
            value="<?php echo isset($_POST['reset_code']) ? htmlspecialchars($_POST['reset_code']) : ''; ?>" />
        <label class="forgot-label" for="new_password">Nouveau mot de passe :</label>
        <div style="position:relative;margin-bottom:18px;">
            <input type="password" name="new_password" id="new_password" class="form-control" required />
            <span onclick="togglePassword('new_password')" style="position:absolute;top:50%;right:12px;transform:translateY(-50%);cursor:pointer;">
                <svg id="eye_new_password" xmlns="http://www.w3.org/2000/svg" width="22" height="22" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.477 0 8.268 2.943 9.542 7-1.274 4.057-5.065 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>
            </span>
        </div>
        <label class="forgot-label" for="confirm_password">Confirmer le mot de passe :</label>
        <div style="position:relative;margin-bottom:18px;">
            <input type="password" name="confirm_password" id="confirm_password" class="form-control" required />
            <span onclick="togglePassword('confirm_password')" style="position:absolute;top:50%;right:12px;transform:translateY(-50%);cursor:pointer;">
                <svg id="eye_confirm_password" xmlns="http://www.w3.org/2000/svg" width="22" height="22" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.477 0 8.268 2.943 9.542 7-1.274 4.057-5.065 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>
            </span>
        </div>
        <button type="submit" class="btn btn-primary w-100">Réinitialiser</button>
    </form>
    <?php endif; ?>
<script>
function togglePassword(fieldId) {
    var input = document.getElementById(fieldId);
    if (input.type === "password") {
        input.type = "text";
    } else {
        input.type = "password";
    }
}
</script>
</div></body></html>
