<?php
// Multi-step registration + agence configuration
session_start();
// Utilisation de la base assurance_gestion (tables cibles) au lieu de hb
// On charge la connexion dédiée gestion_compagnies puis on normalise sur $pdo pour réutiliser le code existant.
require_once __DIR__.'/gestion_compagnies/config/connexion.php'; // fournit $gc_pdo connecté à assurance_gestion
$pdo = $gc_pdo; // Alias pour rester compatible avec le reste du script

// Auto-create users_compagnie table if not exists (structure minimale: id, compagnie_ref, nom, contact, credentials)
try {
  $pdo->exec("CREATE TABLE IF NOT EXISTS users_compagnie (\n      id INT AUTO_INCREMENT PRIMARY KEY,\n      compagnie_ref VARCHAR(50) NOT NULL,\n      first_name VARCHAR(60) NOT NULL,\n      last_name VARCHAR(60) NOT NULL,\n      phone_num VARCHAR(20) NOT NULL,\n      user_email VARCHAR(190) NOT NULL,\n      user_pass VARCHAR(255) NOT NULL,\n      UNIQUE KEY uq_phone_email (phone_num,user_email),\n      KEY idx_compagnie_ref (compagnie_ref),\n      KEY idx_user_email (user_email)\n    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
  // S'assurer que la colonne user_role existe pour pouvoir stocker 'Super admin'
  try {
    $cols=[]; $rc=$pdo->query("SHOW COLUMNS FROM users_compagnie"); while($c=$rc->fetch(PDO::FETCH_ASSOC)){ $cols[$c['Field']]=true; }
    if(!isset($cols['user_role'])){ $pdo->exec("ALTER TABLE users_compagnie ADD COLUMN user_role VARCHAR(60) NULL"); }
  } catch(Throwable $ie) { }
} catch(Throwable $e){ }

// Expected new columns in compagnies_table (we attempt auto-add if missing)
$expectedCols = [
  'compagnie_name' => "VARCHAR(150) NULL",
  'adresse'        => "VARCHAR(250) NULL",
  'tel1'           => "VARCHAR(20) NULL",
  'tel2'           => "VARCHAR(20) NULL",
  'fax'            => "VARCHAR(20) NULL",
  'whatsapp'       => "VARCHAR(20) NULL",
  'mail_1'         => "VARCHAR(100) NULL",
  'mail_2'         => "VARCHAR(100) NULL",
  'mail_3'         => "VARCHAR(100) NULL",
  'footer'         => "TEXT NULL",
  'logo_format'    => "ENUM('wide','square') NOT NULL DEFAULT 'wide'",
  'logo'           => "VARCHAR(255) NULL",
  'expiration_date'=> "DATE NULL"
];

try {
    $cols = [];
    $res = $pdo->query("SHOW COLUMNS FROM compagnies_table");
    while($r = $res->fetch(PDO::FETCH_ASSOC)){ $cols[$r['Field']] = true; }
    foreach($expectedCols as $c=>$def){
        if(!isset($cols[$c])){
            try { $pdo->exec("ALTER TABLE compagnies_table ADD COLUMN `$c` $def"); } catch(Throwable $e) { /* ignore */ }
        }
    }
} catch(Throwable $e){ /* table peut ne pas exister encore */ }

$rawStep = $_POST['step'] ?? ($_GET['step'] ?? 1);
$step = $rawStep === 'verify' ? 'verify' : (int)$rawStep;
if($step !== 'verify' && ($step < 1 || $step > 2)) $step=1;

$errors = [];
$success = false;

// Récupération valeur champ (priorité au POST courant pour conserver les saisies en cas d'erreur)
function field($name){
  if($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST[$name])){
    return htmlspecialchars($_POST[$name], ENT_QUOTES, 'UTF-8');
  }
  return htmlspecialchars($_SESSION['reg_tmp'][$name] ?? '', ENT_QUOTES, 'UTF-8');
}

// Util: envoi email (SMTP config centrale si disponible sinon mail()) - support HTML
function sendAppEmail($pdo,$to,$subject,$body,$isHtml=false){
  if(!filter_var($to,FILTER_VALIDATE_EMAIL)) return false;
  $from='no-reply@example.test'; $fromName='Plateforme';
  try { $st=$pdo->query("SELECT * FROM email_settings_table WHERE id=1 LIMIT 1"); $cfg=$st?$st->fetch(PDO::FETCH_ASSOC):null; } catch(Throwable $e){ $cfg=null; }
  if($cfg && !empty($cfg['active'])){
    $from = $cfg['from_email'] ?: $from; $fromName = $cfg['from_name'] ?: $fromName;
    $host=$cfg['smtp_host']; $port=(int)$cfg['smtp_port']?:25; $enc=$cfg['encryption']??'tls'; $authEnabled=!empty($cfg['auth_enabled']); $user=$cfg['smtp_username']??''; $pass=$cfg['smtp_password']??'';
    $transportHost = ($enc==='ssl'?'ssl://'.$host:$host);
    $fp=@stream_socket_client($transportHost.':'.$port,$errno,$errstr,10,STREAM_CLIENT_CONNECT,stream_context_create(['ssl'=>['verify_peer'=>false,'verify_peer_name'=>false]]));
    if($fp){
      stream_set_timeout($fp,10);
      $read=function() use($fp){ $d=''; while(($l=fgets($fp,512))!==false){ $d.=$l; if(preg_match('~^[0-9]{3} ~',$l)) break; } return $d; };
      $cmd=function($c) use($fp,$read){ fwrite($fp,$c."\r\n"); return $read(); };
      $banner=$read(); if(!preg_match('~^220~',$banner)){ fclose($fp); return false; }
      $eh=$cmd('EHLO local'); if($enc==='tls' && stripos($eh,'STARTTLS')!==false){ $stls=$cmd('STARTTLS'); if(preg_match('~^220~',$stls)){ @stream_socket_enable_crypto($fp,true,STREAM_CRYPTO_METHOD_TLS_CLIENT); $eh=$cmd('EHLO local'); } }
      if($authEnabled){ $r=$cmd('AUTH LOGIN'); if(!preg_match('~^334~',$r)){ fclose($fp); return false; } $r=$cmd(base64_encode($user)); if(!preg_match('~^334~',$r)){ fclose($fp); return false; } $r=$cmd(base64_encode($pass)); if(!preg_match('~^235~',$r)){ fclose($fp); return false; }
      }
      $cmd('MAIL FROM:<'.$from.'>'); $cmd('RCPT TO:<'.$to.'>'); $d=$cmd('DATA'); if(!preg_match('~^354~',$d)){ fclose($fp); return false; }
      $headers=[]; $headers[]='From: '.(mb_encode_mimeheader($fromName,'UTF-8')).' <'.$from.'>'; $headers[]='To: <'.$to.'>'; $headers[]='Subject: '.mb_encode_mimeheader($subject,'UTF-8'); $headers[]='MIME-Version: 1.0'; $headers[]='Content-Type: '.($isHtml?'text/html':'text/plain').'; charset=UTF-8';
      $msg=implode("\r\n",$headers)."\r\n\r\n".$body."\r\n."; fwrite($fp,$msg."\r\n"); $read(); $cmd('QUIT'); fclose($fp); return true;
    }
  }
  // fallback mail
  $headers='From: '.(mb_encode_mimeheader($fromName,'UTF-8')).' <'.$from.'>' ."\r\n".'MIME-Version: 1.0' ."\r\n".'Content-Type: '.($isHtml?'text/html':'text/plain').'; charset=UTF-8';
  @mail($to,$subject,$body,$headers); return true;
}

// Emails support (Super admin)
function supportEmails($pdo){
  static $list=null; if($list!==null) return $list; $emails=[];
  // Priorité: colonne support_email (ligne unique id=1)
  try {
    $st=$pdo->query("SELECT support_email, from_email FROM email_settings_table WHERE id=1 LIMIT 1");
    if($cfg=$st->fetch(PDO::FETCH_ASSOC)){
      $raw = $cfg['support_email'] ?? '';
      if($raw){
        // Séparer par virgule, point-virgule ou espaces
        $parts=preg_split('/[;,\s]+/',$raw,-1,PREG_SPLIT_NO_EMPTY);
        foreach($parts as $p){ $p=trim($p); if(filter_var($p,FILTER_VALIDATE_EMAIL)) $emails[]=$p; }
      }
      // Fallback: from_email si liste vide
      if(!$emails && !empty($cfg['from_email']) && filter_var($cfg['from_email'],FILTER_VALIDATE_EMAIL)) $emails[]=$cfg['from_email'];
    }
  } catch(Throwable $e){}
  // Dernier fallback: super admin users si toujours vide
  if(!$emails){
    try { $st=$pdo->query("SELECT user_email FROM users_table WHERE user_role='Super admin' AND (status=1 OR status IS NULL)"); while($r=$st->fetch(PDO::FETCH_ASSOC)){ if(filter_var($r['user_email'],FILTER_VALIDATE_EMAIL)) $emails[]=$r['user_email']; } } catch(Throwable $e){}
  }
  return $list=array_values(array_unique($emails));
}
function notifySupport($pdo,$subject,$html){ foreach(supportEmails($pdo) as $em){ sendAppEmail($pdo,$em,$subject,$html,true); } }

if($step === 1 && $_SERVER['REQUEST_METHOD']==='POST'){
    // Collect user registration data
    $first_name = trim($_POST['first_name'] ?? '');
    $last_name  = trim($_POST['last_name'] ?? '');
    $phone_num  = trim($_POST['phone_num'] ?? '');
    $user_email = trim($_POST['user_email'] ?? '');
    $user_pass  = $_POST['user_pass'] ?? '';
    $confirm    = $_POST['confirm_pass'] ?? '';

  if($first_name==='') $errors['first_name'] = 'Prénom requis';
  if($last_name==='')  $errors['last_name']  = 'Nom requis';
  if($phone_num==='')  $errors['phone_num']  = 'Téléphone requis';
  elseif(!preg_match('~^[0-9]+$~',$phone_num)) $errors['phone_num']='Chiffres uniquement';
    if($user_email==='' || !filter_var($user_email,FILTER_VALIDATE_EMAIL)) $errors['user_email']='Email invalide';
    if(strlen($user_pass) < 6) $errors['user_pass'] = 'Mot de passe min 6 caractères';
    if($user_pass !== $confirm) $errors['confirm_pass']='Confirmation différente';

  // Unicité dans users_compagnie
  if(!$errors){
    try {
      $st = $pdo->prepare('SELECT COUNT(*) FROM users_compagnie WHERE phone_num=?');
      $st->execute([$phone_num]); if($st->fetchColumn()>0) $errors['phone_num']='Téléphone existe';
      $st = $pdo->prepare('SELECT COUNT(*) FROM users_compagnie WHERE user_email=?');
      $st->execute([$user_email]); if($st->fetchColumn()>0) $errors['user_email']='Email existe';
    } catch(Throwable $e){ $errors['global']='Erreur vérification utilisateur: '.$e->getMessage(); }
  }
  if(!$errors){
    // Si email non encore validé ou changé => envoyer code et aller à vérification
    $emailChanged = empty($_SESSION['reg_tmp']['user_email']) || $_SESSION['reg_tmp']['user_email'] !== $user_email;
    if(empty($_SESSION['reg_email_validated']) || $emailChanged){
      $_SESSION['reg_tmp'] = [
        'first_name'=>$first_name,
        'last_name'=>$last_name,
        'phone_num'=>$phone_num,
        'user_email'=>$user_email,
        'user_pass'=>$user_pass
      ];
      $code = random_int(100000,999999);
      $_SESSION['reg_email_code']=$code; $_SESSION['reg_email_code_expire']=time()+900; // 15 min
  $html = '<p>Bonjour '.htmlspecialchars($first_name,ENT_QUOTES,'UTF-8').',</p><p>Voici votre code de vérification :</p><p style="font-size:20px;font-weight:bold;letter-spacing:3px;">'.$code.'</p><p>Il est valable 15 minutes.</p><p>Cordialement.</p>';
  sendAppEmail($pdo,$user_email,'Code de vérification',$html,true);
      header('Location: register_new_agence.php?step=verify');
      exit;
    } else {
      // déjà validé
      header('Location: register_new_agence.php?step=2'); exit;
    }
  }
}

// Vérification code email
if($step === 'verify' && $_SERVER['REQUEST_METHOD']==='POST'){
  $inputCode = trim($_POST['verify_code'] ?? '');
  if($inputCode===''){ $errors['verify']='Code requis'; }
  elseif(empty($_SESSION['reg_email_code']) || time()>($_SESSION['reg_email_code_expire']??0)){ $errors['verify']='Code expiré, renvoyez un nouveau code.'; }
  elseif($inputCode != $_SESSION['reg_email_code']){ $errors['verify']='Code incorrect'; }
  if(!$errors){
    $_SESSION['reg_email_validated']=true;
    unset($_SESSION['reg_email_code'],$_SESSION['reg_email_code_expire']);
    header('Location: register_new_agence.php?step=2'); exit;
  }
}

// Renvoyer code (GET action)
if($step === 'verify' && isset($_GET['resend']) && empty($errors)){
  if(!empty($_SESSION['reg_tmp']['user_email'])){
    if(empty($_SESSION['reg_email_code_expire']) || time()+60 < $_SESSION['reg_email_code_expire']){ // rafraîchir si presque expiré
      $code = random_int(100000,999999);
      $_SESSION['reg_email_code']=$code; $_SESSION['reg_email_code_expire']=time()+900;
  $html = '<p>Bonjour,</p><p>Nouveau code de vérification :</p><p style="font-size:20px;font-weight:bold;letter-spacing:3px;">'.$code.'</p><p>Valable 15 minutes.</p>';
  sendAppEmail($pdo,$_SESSION['reg_tmp']['user_email'],'Nouveau code vérification',$html,true);
    }
  }
}

if($step === 2 && $_SERVER['REQUEST_METHOD']==='POST'){
    if(empty($_SESSION['reg_tmp'])){
        header('Location: register_new_agence.php'); exit;
    }
  if(empty($_SESSION['reg_email_validated'])){ header('Location: register_new_agence.php?step=1'); exit; }
    // Agency info
    $compagnie_name = trim($_POST['compagnie_name'] ?? '');
    $adresse = trim($_POST['adresse'] ?? '');
    $tel1 = trim($_POST['tel1'] ?? '');
    $tel2 = trim($_POST['tel2'] ?? '');
    $fax = trim($_POST['fax'] ?? '');
    $whatsapp = trim($_POST['whatsapp'] ?? '');
    $mail_1 = trim($_POST['mail_1'] ?? '');
    $mail_2 = trim($_POST['mail_2'] ?? '');
    $mail_3 = trim($_POST['mail_3'] ?? '');
  $footer = trim($_POST['footer'] ?? '');

  if($compagnie_name==='') $errors['compagnie_name']='Nom requis';
  if($adresse==='') $errors['adresse']='Adresse requise';
  if($tel1==='') $errors['tel1']='Téléphone requis';
  elseif(!preg_match('~^[0-9]+$~',$tel1)) $errors['tel1']='Chiffres uniquement';
  if($tel2!=='' && !preg_match('~^[0-9]+$~',$tel2)) $errors['tel2']='Chiffres uniquement';
  if($fax!=='' && !preg_match('~^[0-9]+$~',$fax)) $errors['fax']='Chiffres uniquement';
  if($whatsapp!=='' && !preg_match('~^[0-9]+$~',$whatsapp)) $errors['whatsapp']='Chiffres uniquement';
    if($mail_1==='' || !filter_var($mail_1,FILTER_VALIDATE_EMAIL)) $errors['mail_1']='Email principal invalide';

  $logo_path=''; // non utilisé (logo supprimé du formulaire)

    if(!$errors){
        try {
            $pdo->beginTransaction();
            // Generate unique compagnie_ref
            $tries=0; do {
                $compagnie_ref = 'AG'.date('Ymd').strtoupper(substr(bin2hex(random_bytes(4)),0,6));
                $st = $pdo->prepare('SELECT COUNT(*) FROM compagnies_table WHERE compagnie_ref=?');
                $st->execute([$compagnie_ref]);
                $exists = $st->fetchColumn()>0; $tries++;
            } while($exists && $tries<5);
            if($exists) throw new Exception('Impossible de générer une référence unique');

            // Insert compagnie (active = 0, validation = 0) + expiration_date (365 jours)
            // 11 colonnes variables + expiration_date calculée -> 11 placeholders transmis
            $expirationDate = date('Y-m-d', strtotime('+365 days'));
            $sqlComp = "INSERT INTO compagnies_table (compagnie_ref, compagnie_name, adresse, tel1, tel2, fax, whatsapp, mail_1, mail_2, mail_3, footer, active, validation, created_at, expiration_date) VALUES (?,?,?,?,?,?,?,?,?,?,?,0,0,NOW(),?)";
            $stc = $pdo->prepare($sqlComp);
            $stc->execute([$compagnie_ref,$compagnie_name,$adresse,$tel1,$tel2,$fax,$whatsapp,$mail_1,$mail_2,$mail_3,$footer,$expirationDate]);

            // Insert user in users_compagnie avec rôle Super admin si colonne disponible
            $u = $_SESSION['reg_tmp'];
            $hash = password_hash($u['user_pass'], PASSWORD_BCRYPT);
            $hasRole=false; try { $cc=$pdo->query("SHOW COLUMNS FROM users_compagnie LIKE 'user_role'"); if($cc && $cc->fetch(PDO::FETCH_ASSOC)) $hasRole=true; } catch(Throwable $tr) { }
            if($hasRole){
              $stu = $pdo->prepare('INSERT INTO users_compagnie(compagnie_ref,first_name,last_name,phone_num,user_email,user_pass,user_role) VALUES(?,?,?,?,?,?,?)');
              $stu->execute([$compagnie_ref,$u['first_name'],$u['last_name'],$u['phone_num'],$u['user_email'],$hash,'Super admin']);
            } else {
              $stu = $pdo->prepare('INSERT INTO users_compagnie(compagnie_ref,first_name,last_name,phone_num,user_email,user_pass) VALUES(?,?,?,?,?,?)');
              $stu->execute([$compagnie_ref,$u['first_name'],$u['last_name'],$u['phone_num'],$u['user_email'],$hash]);
            }

            $pdo->commit();
            $success = true;
            unset($_SESSION['reg_tmp']);
            unset($_SESSION['reg_email_validated']);
            // Email attente confirmation (client)
            $htmlClient = '<p>Bonjour '.htmlspecialchars($u['first_name'],ENT_QUOTES,'UTF-8').',</p>'
              .'<p>Votre agence <strong>'.htmlspecialchars($compagnie_name,ENT_QUOTES,'UTF-8').'</strong> (réf: <strong>'.htmlspecialchars($compagnie_ref,ENT_QUOTES,'UTF-8').'</strong>) a été créée et est en attente de validation par notre équipe.</p>'
              .'<p>Vous recevrez un email dès que la validation sera effectuée.</p><p>Cordialement.</p>';
            sendAppEmail($pdo,$u['user_email'],'Agence créée - En attente de validation',$htmlClient,true);
            // Email support
            $htmlSupport = '<p>Nouvelle demande d\'agence reçue.</p>'
              .'<ul style="padding-left:18px">'
              .'<li>Réf: <strong>'.htmlspecialchars($compagnie_ref,ENT_QUOTES,'UTF-8').'</strong></li>'
              .'<li>Nom: '.htmlspecialchars($compagnie_name,ENT_QUOTES,'UTF-8').'</li>'
              .'<li>Contact: '.htmlspecialchars($u['first_name'].' '.$u['last_name'],ENT_QUOTES,'UTF-8').' ('.htmlspecialchars($u['user_email'],ENT_QUOTES,'UTF-8').') Tel: '.htmlspecialchars($u['phone_num'],ENT_QUOTES,'UTF-8').'</li>'
              .'</ul>'
              .'<p><a href="'.htmlspecialchars((isset($_SERVER['HTTPS'])?'https://':'http://').$_SERVER['HTTP_HOST'].dirname($_SERVER['SCRIPT_NAME']).'/gestion_compagnies/valider_compagnies.php',ENT_QUOTES,'UTF-8').'" style="display:inline-block;padding:8px 14px;background:#007bff;color:#fff;text-decoration:none;border-radius:4px;">Valider maintenant</a></p>';
            notifySupport($pdo,'Nouvelle agence en attente: '.$compagnie_ref,$htmlSupport);
        } catch(Throwable $e){
            if($pdo->inTransaction()) $pdo->rollBack();
            $errors['global'] = 'Erreur enregistrement: '.$e->getMessage();
        }
    }
}

?>
<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="utf-8">
  <title>Créer une nouvelle Agence</title>
  <link rel="stylesheet" href="vendor/bootstrap/css/bootstrap.min.css">
  <link rel="stylesheet" href="vendor/fontawesome-free/css/all.min.css">
  <style>
    body{background:#f4f6f9}
    .card{box-shadow:0 2px 4px rgba(0,0,0,.05)}
    .step-indicator{display:flex;justify-content:space-between;margin-bottom:20px}
    .step-indicator .step{flex:1;text-align:center;padding:10px;border-bottom:4px solid #dee2e6;font-weight:600;color:#6c757d}
    .step.active{border-color:#007bff;color:#007bff}
  </style>
</head>
<body>
<div class="container py-4">
  <div class="row justify-content-center">
    <div class="col-lg-8">
      <div class="card">
        <div class="card-header bg-primary text-white"><strong><i class="fas fa-store"></i> Nouvelle Agence</strong></div>
        <div class="card-body">
          <div class="step-indicator">
            <div class="step <?php echo ($step===1 || $step==='verify') ? 'active' : ''; ?>">1. Utilisateur</div>
            <div class="step <?php echo $step===2?'active':''; ?>">2. Agence</div>
          </div>

          <?php if(!empty($errors['global'])): ?>
            <div class="alert alert-danger"><?php echo htmlspecialchars($errors['global']); ?></div>
          <?php endif; ?>

          <?php if($success): ?>
            <div class="alert alert-info mb-3">
              <i class="fas fa-hourglass-half"></i> Agence créée. Votre compte est en attente d'activation par un administrateur. Vous recevrez une notification après validation.
            </div>
            <div class="text-right">
              <a href="logout.php" class="btn btn-primary"><i class="fas fa-sign-in-alt"></i> Connexion</a>
            </div>
          <?php else: ?>
          <?php if($step==='verify'): ?>
            <form method="post" novalidate>
              <input type="hidden" name="step" value="verify">
              <div class="alert alert-info small">Un code a été envoyé à <strong><?php echo htmlspecialchars($_SESSION['reg_tmp']['user_email'] ?? ''); ?></strong>. Entrez-le ci-dessous. (Expire dans 15 min)</div>
              <div class="form-group">
                <label>Code de vérification</label>
                <input name="verify_code" class="form-control" maxlength="6" pattern="[0-9]{6}" required>
                <?php if(isset($errors['verify'])) echo '<small class="text-danger">'.htmlspecialchars($errors['verify']).'</small>'; ?>
              </div>
              <div class="d-flex justify-content-between">
                <a href="register_new_agence.php?step=1" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Modifier</a>
                <div>
                  <a class="btn btn-link btn-sm" href="register_new_agence.php?step=verify&resend=1">Renvoyer le code</a>
                  <button class="btn btn-primary"><i class="fas fa-check"></i> Valider</button>
                </div>
              </div>
            </form>
          <?php elseif($step===1): ?>
            <form method="post" novalidate>
              <input type="hidden" name="step" value="1">
              <div class="form-row">
                <div class="form-group col-md-6">
                  <label>Prénom</label>
                  <input name="first_name" class="form-control" value="<?php echo field('first_name'); ?>">
                  <?php if(isset($errors['first_name'])) echo '<small class="text-danger">'.htmlspecialchars($errors['first_name']).'</small>'; ?>
                </div>
                <div class="form-group col-md-6">
                  <label>Nom</label>
                  <input name="last_name" class="form-control" value="<?php echo field('last_name'); ?>">
                  <?php if(isset($errors['last_name'])) echo '<small class="text-danger">'.htmlspecialchars($errors['last_name']).'</small>'; ?>
                </div>
              </div>
              <div class="form-row">
                <div class="form-group col-md-6">
                  <label>Téléphone</label>
                  <input name="phone_num" class="form-control" value="<?php echo field('phone_num'); ?>" pattern="^[0-9]+$" inputmode="numeric" oninput="this.value=this.value.replace(/[^0-9]/g,'');">
                  <?php if(isset($errors['phone_num'])) echo '<small class="text-danger">'.htmlspecialchars($errors['phone_num']).'</small>'; ?>
                </div>
                <div class="form-group col-md-6">
                  <label>Email</label>
                  <input name="user_email" type="email" class="form-control" value="<?php echo field('user_email'); ?>">
                  <?php if(isset($errors['user_email'])) echo '<small class="text-danger">'.htmlspecialchars($errors['user_email']).'</small>'; ?>
                </div>
              </div>
              <div class="form-row">
                <div class="form-group col-md-6">
                  <label>Mot de passe</label>
                  <input name="user_pass" type="password" class="form-control">
                  <?php if(isset($errors['user_pass'])) echo '<small class="text-danger">'.htmlspecialchars($errors['user_pass']).'</small>'; ?>
                </div>
                <div class="form-group col-md-6">
                  <label>Confirmer</label>
                  <input name="confirm_pass" type="password" class="form-control">
                  <?php if(isset($errors['confirm_pass'])) echo '<small class="text-danger">'.htmlspecialchars($errors['confirm_pass']).'</small>'; ?>
                </div>
              </div>
              <button class="btn btn-primary"><i class="fas fa-arrow-right"></i> Continuer</button>
            </form>
          <?php else: ?>
            <form method="post" novalidate>
              <input type="hidden" name="step" value="2">
              <div class="form-group">
                <label>Nom de l'Agence</label>
                <input name="compagnie_name" class="form-control" value="<?php echo htmlspecialchars($_POST['compagnie_name'] ?? ''); ?>">
                <?php if(isset($errors['compagnie_name'])) echo '<small class="text-danger">'.htmlspecialchars($errors['compagnie_name']).'</small>'; ?>
              </div>
              <div class="form-group">
                <label>Adresse</label>
                <textarea name="adresse" class="form-control" rows="2"><?php echo htmlspecialchars($_POST['adresse'] ?? ''); ?></textarea>
                <?php if(isset($errors['adresse'])) echo '<small class="text-danger">'.htmlspecialchars($errors['adresse']).'</small>'; ?>
              </div>
              <div class="form-row">
                <div class="form-group col-md-4">
                  <label>Téléphone</label>
                  <input name="tel1" class="form-control" value="<?php echo htmlspecialchars($_POST['tel1'] ?? ''); ?>" pattern="^[0-9]+$" inputmode="numeric" oninput="this.value=this.value.replace(/[^0-9]/g,'');">
                  <?php if(isset($errors['tel1'])) echo '<small class="text-danger">'.htmlspecialchars($errors['tel1']).'</small>'; ?>
                </div>
                <div class="form-group col-md-4">
                  <label>Fax</label>
                  <input name="fax" class="form-control" value="<?php echo htmlspecialchars($_POST['fax'] ?? ''); ?>" pattern="^[0-9]+$" inputmode="numeric" oninput="this.value=this.value.replace(/[^0-9]/g,'');">
                </div>
                <div class="form-group col-md-4">
                  <label>WhatsApp</label>
                  <input name="whatsapp" class="form-control" value="<?php echo htmlspecialchars($_POST['whatsapp'] ?? ''); ?>" pattern="^[0-9]+$" inputmode="numeric" oninput="this.value=this.value.replace(/[^0-9]/g,'');">
                </div>
              </div>
              <div class="form-row">
                <div class="form-group col-md-4">
                  <label>Email Principal</label>
                  <input name="mail_1" type="email" class="form-control" value="<?php echo htmlspecialchars($_POST['mail_1'] ?? ''); ?>">
                  <?php if(isset($errors['mail_1'])) echo '<small class="text-danger">'.htmlspecialchars($errors['mail_1']).'</small>'; ?>
                </div>
                <div class="form-group col-md-4">
                  <label>Email Secondaire</label>
                  <input name="mail_2" type="email" class="form-control" value="<?php echo htmlspecialchars($_POST['mail_2'] ?? ''); ?>">
                </div>
                <div class="form-group col-md-4">
                  <label>Email 3</label>
                  <input name="mail_3" type="email" class="form-control" value="<?php echo htmlspecialchars($_POST['mail_3'] ?? ''); ?>">
                </div>
              </div>
              <div class="form-group">
                <label>Footer</label>
                <textarea name="footer" class="form-control" rows="4"><?php echo htmlspecialchars($_POST['footer'] ?? ''); ?></textarea>
              </div>
              <div class="d-flex justify-content-between">
                <a href="register_new_agence.php?step=1" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Retour</a>
                <button class="btn btn-success"><i class="fas fa-check"></i> Finaliser</button>
              </div>
            </form>
          <?php endif; ?>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div>
</div>
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>
