<?php
session_start();
// Connexion dédiée espace gestion_compagnies (ne dépend pas de la session multi-agence)
// On utilise la même logique que login.php pour cet espace: PDO nommé $gc_pdo
if (!isset($gc_pdo)) {
  $gc_host = 'localhost';
  $gc_db   = 'assurance_gestion'; // base centrale de gestion
  $gc_user = 'root'; // adapter si besoin
  $gc_pass = '';
  try {
    $gc_pdo = new PDO("mysql:host=$gc_host;dbname=$gc_db;charset=utf8", $gc_user, $gc_pass, [
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]);
  } catch (Exception $e) {
    die('Erreur connexion centrale: '.$e->getMessage());
  }
}

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require '../PHPMailer/src/Exception.php';
require '../PHPMailer/src/PHPMailer.php';
require '../PHPMailer/src/SMTP.php';

$success = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email'] ?? '');
    if (empty($email)) {
        $error = "Veuillez saisir votre adresse email.";
    } else {
    $stmt = $gc_pdo->prepare("SELECT id FROM users_table WHERE user_email = :email LIMIT 1");
    $stmt->execute([':email'=>$email]);
    $user = $stmt->fetch();
    if ($user) {
      $user_id = $user['id'];
      $code = str_pad(random_int(0, 99999999), 8, '0', STR_PAD_LEFT);
      $expiry = date('Y-m-d H:i:s', time() + 600); // 10 min
      $update = $gc_pdo->prepare("UPDATE users_table SET recup_pass = :code, recup_expiry = :exp WHERE id = :id");
      $update->execute([':code'=>$code, ':exp'=>$expiry, ':id'=>$user_id]);
            $_SESSION['gestion_reset_email'] = $email;
            $mail = new PHPMailer(true);
            try {
                $mail->isSMTP();
                $mail->Host = 'mail.services-ae.net';
                $mail->SMTPAuth = true;
                $mail->Username = 'manager@hebergood.com';
                $mail->Password = 'X!P0}h=HwhA*';
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
                $mail->Port = 465;
                $mail->CharSet = 'UTF-8';
                $mail->setFrom('manager@hebergood.com', 'Support Gestion Compagnies');
                $mail->addAddress($email);
                $mail->isHTML(true);
                $mail->Subject = 'Code de réinitialisation (Gestion Compagnies)';
                $mail->Body = "Votre code de réinitialisation est : <b>$code</b> (valide 10 min)";
                $mail->AltBody = "Votre code de réinitialisation est : $code (valide 10 min)";
                $mail->send();
                header('Location: verify_code.php');
                exit;
            } catch (Exception $e) {
                $error = "Erreur lors de l'envoi du mail: " . $mail->ErrorInfo;
            }
        } else {
            $error = "Aucun utilisateur trouvé avec cette adresse email.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <link href="./data/123456/logo.png" rel="icon">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/qrious/4.0.2/qrious.min.js"></script>
    <link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="../css/ruang-admin.min.css" rel="stylesheet">
    <link href="../vendor/datatables/dataTables.bootstrap4.min.css" rel="stylesheet">
  <title>Mot de passe oublié - Gestion Compagnies</title>
</head>
<body class="bg-gradient-login">
<div class="container-login">
  <div class="row justify-content-center">
    <div class="col-xl-6 col-lg-6 col-md-9">
      <div class="card shadow-sm my-5">
        <div class="card-body p-0">
          <div class="row">
            <div class="col-lg-12">
              <div class="login-form">
                <div class="text-center">
                  <h1 class="h4 text-gray-900 mb-4">Mot de passe oublié</h1>
                </div>
                <?php if ($error): ?><div class="alert alert-danger"><?= $error ?></div><?php endif; ?>
                <?php if ($success): ?><div class="alert alert-success"><?= $success ?></div><?php endif; ?>
                <form method="POST" action="">
                  <div class="form-group">
                    <label>Email</label>
                    <input type="email" class="form-control" name="email" required placeholder="Entrez votre adresse email">
                  </div>
                  <div class="form-group">
                    <button type="submit" class="btn btn-primary btn-block">Envoyer le code</button>
                  </div>
                </form>
                <hr>
                <div class="text-center">
                  <a class="font-weight-bold small" href="login.php">Retour à la connexion</a>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<script src="../vendor/jquery/jquery.min.js"></script>
<script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../vendor/jquery-easing/jquery.easing.min.js"></script>
<script src="../js/ruang-admin.min.js"></script>
</body>
</html>
