<?php
// Page de réinitialisation du mot de passe admin par code
require_once 'config/config.php';
require_once 'config/db.php';
require_once 'admin/AdminUser.php';

$message = '';
$step = 1;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['email'])) {
        $email = trim($_POST['email']);
        $adminUser = new AdminUser($pdo);
        $user = $adminUser->getByEmail($email);
        if ($user) {
            $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']]);
            // Envoi du code par email
            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.";
        }
    } elseif (isset($_POST['reset_code'], $_POST['new_password'], $_POST['email'])) {
        $email = trim($_POST['email']);
        $code = trim($_POST['reset_code']);
        $new_password = $_POST['new_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);
        if ($user && $user['reset_code'] === $code && strtotime($user['reset_expires']) > time()) {
            $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']]);
            $message = "Votre mot de passe a été réinitialisé avec succès.";
            $step = 3;
        } else {
            $message = "Code invalide ou expiré.";
            $step = 2;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="utf-8">
    <title>Réinitialisation du mot de passe - 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>.reset-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);} .reset-title{color:#696cff;font-weight:bold;font-size:1.3em;margin-bottom:16px;} .reset-label{font-weight:500;margin-bottom:8px;}</style>
</head>
<body><div class="reset-box">
    <div class="reset-title">Réinitialisation du mot de passe</div>
    <?php if (!empty($message)): ?>
        <div class="alert alert-info" role="alert" style="margin-bottom:18px;"> <?php echo htmlspecialchars($message); ?> </div>
    <?php endif; ?>
    <?php if ($step === 1): ?>
    <form method="POST">
        <label class="reset-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 elseif ($step === 2): ?>
    <form method="POST">
        <input type="hidden" name="email" value="<?php echo htmlspecialchars($_POST['email']); ?>" />
        <label class="reset-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;" />
        <label class="reset-label" for="new_password">Nouveau mot de passe :</label>
        <input type="password" name="new_password" id="new_password" class="form-control" required style="margin-bottom:18px;" />
        <button type="submit" class="btn btn-primary w-100">Réinitialiser</button>
    </form>
    <?php elseif ($step === 3): ?>
    <a href="admin-login.php" class="btn btn-success w-100">Se connecter</a>
    <?php endif; ?>
</div></body></html>
