<?php
session_start();
// Connexion dédiée centrale
if (!isset($gc_pdo)) {
  $gc_host = 'localhost';
  $gc_db   = 'assurance_gestion';
  $gc_user = 'root';
  $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';

if (empty($_SESSION['gestion_reset_email'])) {
    header('Location: forgot_password.php');
    exit;
}

$email = $_SESSION['gestion_reset_email'];
$code_error = '';
$success_message = '';

// Renvoi code
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['resend_code'])) {
    $new_code = str_pad(random_int(0, 99999999), 8, '0', STR_PAD_LEFT);
    $expiry = date('Y-m-d H:i:s', time() + 600);
  $stmt = $gc_pdo->prepare("UPDATE users_table SET recup_pass = :code, recup_expiry = :exp WHERE user_email = :email");
  if ($stmt->execute([':code'=>$new_code, ':exp'=>$expiry, ':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 = 'Nouveau code de vérification';
            $mail->Body = "Votre nouveau code est : <b>$new_code</b> (valide 10 min)";
            $mail->AltBody = "Votre nouveau code est : $new_code (valide 10 min)";
            $mail->send();
            $success_message = 'Nouveau code envoyé.';
        } catch (Exception $e) {
            $code_error = "Erreur email: " . $mail->ErrorInfo;
        }
    } else {
        $code_error = 'Erreur de génération de code.';
    }
  $stmt = null;
}

// Vérification code
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['code']) && !isset($_POST['resend_code'])) {
    $input_code = implode('', array_map('trim', $_POST['code']));
    if ($input_code) {
    $stmt = $gc_pdo->prepare("SELECT recup_pass, recup_expiry FROM users_table WHERE user_email = :email LIMIT 1");
    $stmt->execute([':email'=>$email]);
    $row = $stmt->fetch();
    if ($row) {
      $recup_pass = $row['recup_pass'];
      $recup_expiry = $row['recup_expiry'];
            $now = date('Y-m-d H:i:s');
            if ($input_code === $recup_pass && $recup_expiry && $now <= $recup_expiry) {
                $_SESSION['gestion_code_verified'] = true;
        $stmt = null;
                header('Location: reset_password.php');
                exit;
            } elseif ($input_code !== $recup_pass) {
                $code_error = 'Code incorrect.';
            } else {
                $code_error = 'Code expiré.';
            }
        } else {
            $code_error = 'Erreur interne.';
        }
    $stmt = null;
    } else {
        $code_error = 'Veuillez saisir le code.';
    }
}
?>
<!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>Vérification code - Gestion Compagnies</title>
  <style>
    .code-input{width:45px;text-align:center;font-size:1.6rem;margin-right:5px;font-weight:bold;border:2px solid #ddd;border-radius:8px;transition:.3s}
    .code-input:focus{border-color:#1e40af;box-shadow:0 0 0 0.2rem rgba(30,64,175,.25);transform:scale(1.05)}
    .code-input.filled{background:#e3f2fd;border-color:#1e40af}
  </style>
</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">Vérification du code</h1>
              <p class="mb-3">Code envoyé à :</p>
              <div class="badge badge-light p-2" style="font-size:90%;"><?= htmlspecialchars($email) ?></div>
            </div>
            <?php if ($success_message): ?><div class="alert alert-success"><?= $success_message ?></div><?php endif; ?>
            <?php if ($code_error): ?><div class="alert alert-danger"><?= $code_error ?></div><?php endif; ?>
            <form method="POST" action="">
              <div class="form-group d-flex justify-content-center">
                <?php for($i=0;$i<8;$i++): ?>
                  <input type="text" maxlength="1" name="code[]" class="form-control code-input" required pattern="\d">
                <?php endfor; ?>
              </div>
              <div class="form-group"><button type="submit" class="btn btn-primary btn-block">Valider le code</button></div>
            </form>
            <div class="text-center mt-2">
              <form method="POST" class="d-inline">
                <button type="submit" name="resend_code" class="btn btn-outline-secondary btn-sm">Renvoyer le code</button>
              </form>
            </div>
            <hr>
            <div class="text-center"><a class="small" href="forgot_password.php">Changer d'email</a></div>
          </div></div></div>
        </div>
      </div>
    </div>
  </div>
</div>
<script src="../vendor/jquery/jquery.min.js"></script>
<script>
  document.querySelectorAll('.code-input').forEach((inp,idx,arr)=>{
    inp.addEventListener('input',function(){
      if(this.value){this.classList.add('filled'); if(idx < arr.length-1) arr[idx+1].focus();}
    });
    inp.addEventListener('keydown',function(e){if(e.key==='Backspace' && !this.value && idx>0){arr[idx-1].focus();}});
  });
  document.querySelector('.code-input').focus();
</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>
