<?php
// Page de validation des nouvelles compagnies (non validées)
// Affiche les compagnies avec validation=0 et permet de :
//  - Saisir les infos de la base cible (nom base, user, pass)
//  - Vérifier que la base existe
//  - Créer les tables (schéma install.php)
//  - Insérer le compte utilisateur principal (role Super admin) dans users_table de la base cible
//  - Créer dossiers backup/REF et data/REF
//  - Mettre à jour compagnies_table (compagnie_db, compagnie_db_user, compagnie_db_pass, validation=1, active=1)

@session_start();
require_once __DIR__.'/config/connexion.php'; // $gc_pdo connecté à assurance_gestion
// Auth (aligner design / sécurité avec companies.php)
@require_once __DIR__.'/config/auth.php';
if(function_exists('gc_require_login')) gc_require_login();
$pdo = $gc_pdo;

$messages=[]; $errors=[]; // (Envoi de code de confirmation désactivé sur demande)

// Helper email (simple) pour notification rejet
function vc_sendEmail($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'; $auth=!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($auth){ $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; }
  }
  $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;
}

// Récupérer emails support (Super admin)
function vc_support_emails($pdo){
  static $cache=null; if($cache!==null) return $cache; $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){}
  if(!$emails){ try { $st=$pdo->query("SELECT from_email FROM email_settings_table WHERE id=1"); $cfg=$st?$st->fetch(PDO::FETCH_ASSOC):null; if($cfg && filter_var($cfg['from_email'],FILTER_VALIDATE_EMAIL)) $emails[]=$cfg['from_email']; } catch(Throwable $e){}
  }
  return $cache=array_values(array_unique($emails));
}

function vc_send_to_support($pdo,$subject,$html,$alt=null){ foreach(vc_support_emails($pdo) as $em){ vc_sendEmail($pdo,$em,$subject,$html,true); } }

// Récupération action
$action = $_POST['action'] ?? '';
// Capture brut
$rawRefPost = $_POST['compagnie_ref'] ?? '';
// Sanitize référence (alphanum + _ -)
function vc_sanitize_ref($r){ $r = trim($r); if($r==='') return ''; if(!preg_match('~^[A-Za-z0-9_-]{3,60}$~',$r)) return ''; return $r; }
$ref = vc_sanitize_ref($rawRefPost);
// Fallback sur session si vide ou incohérent lors d'une action autre que prepare
if(in_array($action,['reject','validate'])){
  if(!empty($_SESSION['vc_last_ref'])){
    $sessionRef = vc_sanitize_ref($_SESSION['vc_last_ref']);
    if($ref==='' || $ref !== $sessionRef){
      $ref = $sessionRef; // override silencieux
    }
  }
}

if ($action==='prepare' && $ref!=='') {
  // Mémoriser pour étape suivante (reject/validate) si formulaire perd la ref
  $_SESSION['vc_last_ref']=$ref;
  // Email support + client (notification démarrage traitement)
  try {
    $st=$pdo->prepare('SELECT c.*, u.user_email FROM compagnies_table c LEFT JOIN users_compagnie u ON c.compagnie_ref=u.compagnie_ref WHERE c.compagnie_ref=? LIMIT 1');
    $st->execute([$ref]);
    if($row=$st->fetch(PDO::FETCH_ASSOC)){
      $compName = htmlspecialchars($row['compagnie_name']??'',ENT_QUOTES,'UTF-8');
      $htmlClient = '<p>Bonjour,</p><p>Votre demande de création d\'agence <strong>'.htmlspecialchars($ref,ENT_QUOTES,'UTF-8').'</strong> ('. $compName .') est en cours de traitement par notre équipe.</p><p>Vous serez notifié lors de la validation ou en cas de rejet.</p><p>Cordialement.</p>';
      if(!empty($row['user_email'])) vc_sendEmail($pdo,$row['user_email'],'Traitement de votre agence ('.$ref.')',$htmlClient,true);
      $htmlSupport = '<p>Démarrage préparation validation de l\'agence <strong>'.htmlspecialchars($ref,ENT_QUOTES,'UTF-8').'</strong> ('. $compName .').</p>';
      vc_send_to_support($pdo,'Préparation validation agence '.$ref,$htmlSupport);
    }
  } catch(Throwable $e){}
  // Juste afficher le formulaire de saisie DB pour cette compagnie
}
elseif ($action==='reject' && $ref!=='') {
    $reason = trim($_POST['reason'] ?? '');
    if($reason==='') $errors[]='Raison requise';
    $user=null; $compagnie=null;
    if(!$errors){
      // Recherche tolérante (validation peut être NULL, '0', 0 ou colonne absente)
      $colValidationExists = true; $rawCompagnie = null; $validationValue = null; $canReject=false; $valNorm=null; $valNormRaw=null;
      try { $cv=$pdo->query("SHOW COLUMNS FROM compagnies_table LIKE 'validation'"); $colValidationExists=(bool)$cv->fetch(); } catch(Throwable $ie){ $colValidationExists=true; }
      try {
        $st=$pdo->prepare('SELECT * FROM compagnies_table WHERE compagnie_ref=? LIMIT 1');
        $st->execute([$ref]);
        $rawCompagnie=$st->fetch(PDO::FETCH_ASSOC);
        if($rawCompagnie){
          if($colValidationExists){
            $validationValue = $rawCompagnie['validation'];
            $valNormRaw = is_string($validationValue)?trim($validationValue):$validationValue;
            if($valNormRaw===''||$valNormRaw===false||$valNormRaw===null) $valNormRaw=0;
            if(is_numeric($valNormRaw)) $valNorm=(int)$valNormRaw; else { $vl=strtolower((string)$valNormRaw); $valNorm = in_array($vl,['false','no','non'])?0:1; }
            if($valNorm===0){ $canReject=true; $compagnie=$rawCompagnie; } else { $validationValue=$valNorm; }
          } else { // pas de colonne => considérer rejet possible
            $canReject=true; $compagnie=$rawCompagnie; $validationValue=null; $valNorm=0; $valNormRaw=0;
          }
        }
      } catch(Throwable $eSel){ $errors[]='Chargement compagnie: '.substr($eSel->getMessage(),0,120); }
      if(!$compagnie){
        if($rawCompagnie && isset($validationValue) && $validationValue!==0){
          $errors[]='Compagnie déjà validée (validation='.htmlspecialchars((string)$validationValue,ENT_QUOTES,'UTF-8').')';
        } else {
          $errors[]='Compagnie introuvable';
        }
      } else {
  // OK
      }
    }
    if(!$errors){
      try { $st=$pdo->prepare('SELECT * FROM users_compagnie WHERE compagnie_ref=? ORDER BY id ASC LIMIT 1'); $st->execute([$ref]); $user=$st->fetch(PDO::FETCH_ASSOC); if(!$user) $errors[]='Utilisateur introuvable'; } catch(Throwable $e){ $errors[]='Chargement utilisateur: '.$e->getMessage(); }
    }
    if(!$errors){
      try {
  // Supprimer la compagnie
  $pdo->prepare('DELETE FROM compagnies_table WHERE compagnie_ref=? LIMIT 1')->execute([$ref]);
  // Supprimer les utilisateurs pré-inscrits (users_compagnie)
  try { $pdo->prepare('DELETE FROM users_compagnie WHERE compagnie_ref=?')->execute([$ref]); } catch(Throwable $ie){ }
        $messages[]='Compagnie '.$ref.' rejetée et supprimée';
        if($user && !empty($user['user_email'])){
          $html = '<p>Bonjour,</p><p>Votre demande de création d\'agence <strong>'.htmlspecialchars($ref,ENT_QUOTES,'UTF-8').'</strong> a été <span style="color:#d9534f">refusée</span>.</p><p><strong>Raison :</strong><br>'.nl2br(htmlspecialchars($reason,ENT_QUOTES,'UTF-8')).'</p><p>Vous pouvez corriger les éléments nécessaires et soumettre une nouvelle demande.</p><p>Cordialement.</p>';
          vc_sendEmail($pdo,$user['user_email'],'Rejet de votre agence ('.$ref.')',$html,true);
        }
        // Email support
        vc_send_to_support($pdo,'Agence '.$ref.' rejetée','<p>L\'agence <strong>'.htmlspecialchars($ref,ENT_QUOTES,'UTF-8').'</strong> a été rejetée.<br><strong>Raison :</strong> '.nl2br(htmlspecialchars($reason,ENT_QUOTES,'UTF-8')).'</p>');
        try { $pdo->prepare('INSERT INTO logs_rejets(compagnie_ref, reason, created_at) VALUES(?,?,NOW())')->execute([$ref,$reason]); } catch(Throwable $ie){ }
      } catch(Throwable $e){ $errors[]='Rejet: '.$e->getMessage(); }
    }
}
elseif ($action==='validate' && $ref!=='') {
    $dbName = trim($_POST['db_name'] ?? '');
    $dbUser = trim($_POST['db_user'] ?? '');
    $dbPass = $_POST['db_pass'] ?? '';

    if($dbName==='') $errors[]='Nom de base requis';
    if($dbUser==='') $errors[]='Utilisateur DB requis';

    // Charger la compagnie + user associé
    if(!$errors){
        $st = $pdo->prepare('SELECT * FROM compagnies_table WHERE compagnie_ref=? AND validation=0');
        $st->execute([$ref]);
        $compagnie = $st->fetch(PDO::FETCH_ASSOC);
        if(!$compagnie){ $errors[]='Compagnie introuvable ou déjà validée'; }
    }
    if(!$errors){
        $st = $pdo->prepare('SELECT * FROM users_compagnie WHERE compagnie_ref=? ORDER BY id ASC LIMIT 1');
        $st->execute([$ref]);
        $user = $st->fetch(PDO::FETCH_ASSOC);
        if(!$user){ $errors[]='Utilisateur associé introuvable'; }
    }
    // Vérifier existence base
    if(!$errors){
        try {
            $rootDsn = 'mysql:host=localhost;charset=utf8';
            $rootPdo = new PDO($rootDsn,$dbUser,$dbPass,[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);
            $res = $rootPdo->query("SHOW DATABASES LIKE " . $rootPdo->quote($dbName));
            if(!$res->fetch()){
                $errors[] = "La base '$dbName' n'existe pas.";
            }
        } catch(Throwable $e){ $errors[]='Connexion root / check base: '.$e->getMessage(); }
    }
    // Création tables + insertion user
    if(!$errors){
        try {
            $rootPdo->exec("USE `".$dbName."`");
      // Importer le schéma complet depuis fichier SQL
  // Fichier se trouve dans le dossier parent /files/mybase.sql
  $importFile = realpath(__DIR__.'/../files/mybase.sql');
      if(!is_file($importFile) || !is_readable($importFile)){
        $errors[] = 'Fichier d\'import introuvable: files/mybase.sql';
      } else {
        $sqlContent = file_get_contents($importFile);
        if($sqlContent===false || trim($sqlContent)===''){
          $errors[]='Contenu du fichier mybase.sql vide ou illisible';
        } else {
          // Parser conscient du DELIMITER pour gérer procédures / events
          $lines = preg_split('/\r?\n/', $sqlContent);
          $delimiter = ';';
          $buffer = '';
          foreach($lines as $ln){
            // Ignorer commentaires ligne
            if(preg_match('/^\s*--/',$ln)) continue;
            if(preg_match('/^DELIMITER\s+(\S+)/i',$ln,$m)){
              // Changer le délimiteur
              $delimiter = $m[1];
              continue;
            }
            $buffer .= $ln."\n";
            // Vérifier fin d'instruction selon délimiteur courant
            if($delimiter !== ';'){
              if(str_ends_with(trim($buffer), $delimiter)){
                $stmt = substr(trim($buffer), 0, -strlen($delimiter));
                $buffer='';
              } else {
                continue; // accumuler
              }
            } else {
              // délimiteur standard ;
              if(!preg_match('/;\s*$/', trim($buffer))){
                continue; // pas encore terminé
              }
              $stmt = preg_replace('/;\s*$/','',trim($buffer));
              $buffer='';
            }
            $stmt = trim($stmt);
            if($stmt==='') continue;
            // Retirer commentaires bloc restants
            $stmt = preg_replace('/\/\*.*?\*\//s','',$stmt);
            $stmt = trim($stmt);
            if($stmt==='') continue;
            // Normaliser DEFINER pour éviter privilèges insuffisants
            $stmt = preg_replace('/CREATE\s+DEFINER=`[^`]+`@`[^`]+`\s+(PROCEDURE|EVENT)/i','CREATE $1',$stmt,1);
            try {
              $rootPdo->exec($stmt);
            } catch(Throwable $ie){
              $short = substr($ie->getMessage(),0,160);
              if(preg_match('/(PROCEDURE|EVENT)/i',$stmt)){
                // Traiter comme avertissement mais ne pas bloquer
                $messages[] = 'Avertissement import (objet spécial): '.$short;
              } else {
                $errors[]='Import SQL: '.$short.'\nSQL: '.substr($stmt,0,300);
                // Optionally log full statement for deeper debugging
                // file_put_contents(__DIR__.'/import_sql_error.log', $short."\nSQL: ".$stmt."\n", FILE_APPEND);
                if(count($errors)>10) break;
              }
            }
          }
          // Si reste du buffer sans délimiteur final
          if($buffer && !$errors){
            $stmt = trim($buffer);
            $stmt = preg_replace('/\/\*.*?\*\//s','',$stmt);
            $stmt = trim($stmt);
            if($stmt!==''){
              try { $rootPdo->exec($stmt); } catch(Throwable $ie){ $errors[]='Import SQL (final): '.substr($ie->getMessage(),0,160); }
            }
          }
        }
      }
            if(!$errors){
                // Insérer user si pas déjà présent
                $check = $rootPdo->prepare('SELECT COUNT(*) FROM users_table WHERE user_email=?');
                $check->execute([$user['user_email']]);
                if(!$check->fetchColumn()){
                    // Adapter à la structure réelle de users_table (pas de created_at, mais recup_pass, recup_expiry, must_change_password)
                    $ins = $rootPdo->prepare('INSERT INTO users_table(first_name,last_name,phone_num,user_email,user_pass,recup_pass,recup_expiry,user_role,status,must_change_password) VALUES(?,?,?,?,?,?,?,"Super admin",1,?)');
                    $ins->execute([
                      $user['first_name'],
                      $user['last_name'],
                      $user['phone_num'],
                      $user['user_email'],
                      $user['user_pass'],
                      '', // recup_pass vide
                      '1970-01-01 00:00:00', // recup_expiry placeholder
                      '' // must_change_password
                    ]);
                }
                // Seed de base (paiement_mode, policy_type) si vide
                try { if( (int)$rootPdo->query('SELECT COUNT(*) FROM paiement_mode_table')->fetchColumn()===0){ $rootPdo->exec("INSERT INTO paiement_mode_table(paiement_mode) VALUES ('ESPECE'),('CHEQUE'),('EFFET'),('VIREMENT BANCAIRE')"); } } catch(Throwable $e){ }
                try { if( (int)$rootPdo->query('SELECT COUNT(*) FROM policy_type')->fetchColumn()===0){ $rootPdo->exec("INSERT INTO policy_type(type,risque) VALUES ('TRANSPORT MARCHANDISES','V'),('TRANSPORT VOYAGEURS','V'),('AUTOMOBILE','V'),('MOTO','V'),('MAISON','RD'),('LOCAL COMMERCIAL','RD')"); } } catch(Throwable $e){ }
  // Import menu_items supprimé (inclus dans mybase.sql)
                // Copier infos principales (compagnie_name, adresse, tel1, tel2, fax, whatsapp, mails, footer) vers compagnie_table si vide
                try {
                    $cntComp = (int)$rootPdo->query('SELECT COUNT(*) FROM compagnie_table')->fetchColumn();
                    if($cntComp===0){
                        $compagnie_ref_local = $compagnie['compagnie_ref'] ?? $ref;
                        $fields = ['compagnie_name','adresse','tel1','tel2','fax','whatsapp','mail_1','mail_2','mail_3','footer'];
                        $data = [];
                        foreach($fields as $f){ $data[$f] = $compagnie[$f] ?? ''; }
                        $facture_ref = $compagnie_ref_local; // initialiser facture_ref
                        $stmtInsComp = $rootPdo->prepare('INSERT INTO compagnie_table( compagnie_name, adresse, tel1, tel2, fax, whatsapp, mail_1, mail_2, mail_3, footer, facture_ref, facture_prefixe, facture_suffixe, use_year_prefix, use_monthyear_prefix, use_year_suffix, use_monthyear_suffix, reset_number_yearly, logo, logo_format, compagnie_ref ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)');
                        $stmtInsComp->execute([
                          $data['compagnie_name'],
                          $data['adresse'],
                          $data['tel1'],
                          $data['tel2'],
                          $data['fax'],
                          $data['whatsapp'],
                          $data['mail_1'],
                          $data['mail_2'],
                          $data['mail_3'],
                          $data['footer'],
                          $facture_ref,
                          '', // facture_prefixe
                          '', // facture_suffixe
                          0,0,0,0,0, // flags reset
                          '', // logo
                          'wide', // logo_format
                          $compagnie_ref_local
                        ]);
                    }
                } catch(Throwable $e){ $errors[]='Copie compagnie_table: '.substr($e->getMessage(),0,120); }
                // Mettre à jour compagnies_table
                $up = $pdo->prepare('UPDATE compagnies_table SET compagnie_db=?, compagnie_db_user=?, compagnie_db_pass=?, validation=1, active=1 WHERE compagnie_ref=?');
                $up->execute([$dbName,$dbUser,$dbPass,$ref]);
                // Créer dossiers
                $baseRoot = realpath(__DIR__.'/..');
                if($baseRoot){
                    @mkdir($baseRoot.'/backup/'.$ref,0775,true);
                    @mkdir($baseRoot.'/data/'.$ref,0775,true);
                }
                if(!$errors){ $messages[]="Compagnie $ref validée et initialisée."; 
                  // Email client
                  if($user && !empty($user['user_email'])){
                    $html = '<p>Bonjour,</p><p>Votre agence <strong>'.htmlspecialchars($ref,ENT_QUOTES,'UTF-8').'</strong> a été <span style="color:#28a745">validée</span> et est maintenant active.</p><p>Vous pouvez vous connecter et commencer à l\'utiliser.</p><p>Cordialement.</p>';
                    vc_sendEmail($pdo,$user['user_email'],'Validation de votre agence ('.$ref.')',$html,true);
                  }
                  // Email support
                  vc_send_to_support($pdo,'Agence '.$ref.' validée','<p>L\'agence <strong>'.htmlspecialchars($ref,ENT_QUOTES,'UTF-8').'</strong> a été validée et initialisée.</p>');
                }
            }
        } catch(Throwable $e){ $errors[]='Initialisation: '.$e->getMessage(); }
    }
}

// Liste compagnies non validées
$pending=[];
try {
  $rs = $pdo->query('SELECT id, compagnie_ref, compagnie_name, created_at FROM compagnies_table WHERE validation=0');
  $pending = $rs->fetchAll(PDO::FETCH_ASSOC);
} catch(Throwable $e){ $errors[]='Lecture compagnies: '.$e->getMessage(); }

// Vérification cohérence ref lors de l'étape prepare
if($action==='prepare' && $ref!==''){
  $pendingRefs = array_map(function($r){ return $r['compagnie_ref']; }, $pending);
  if(!in_array($ref,$pendingRefs,true)){
    $errors[] = 'Référence sélectionnée invalide ou plus en attente.';
    $action='';
    $ref='';
    unset($_SESSION['vc_last_ref']);
  }
}

function h($s){ return htmlspecialchars($s??'',ENT_QUOTES,'UTF-8'); }
?><!DOCTYPE html><html lang="fr"><head><meta charset="utf-8"><title>Validation Compagnies</title><link rel="stylesheet" href="../vendor/bootstrap/css/bootstrap.min.css"><link rel="stylesheet" href="../vendor/fontawesome-free/css/all.min.css"><link rel="stylesheet" href="../css/ruang-admin.min.css"><style>.table td{vertical-align:middle}.card{box-shadow:0 2px 4px rgba(0,0,0,.05)}</style></head><body id="page-top"><div id="wrapper"><?php include __DIR__.'/sidebar.php'; ?><div id="content-wrapper" class="d-flex flex-column"><div id="content"><?php include __DIR__.'/topbar.php'; ?><div class="container-fluid">
  <div class="d-flex justify-content-between align-items-center mb-3"><h3 class="mb-0"><i class="fas fa-check text-success"></i> Validation Compagnies</h3></div>
  <?php foreach($messages as $m): ?><div class="alert alert-success py-2"><?=h($m)?></div><?php endforeach; ?>
  <?php foreach($errors as $er): ?><div class="alert alert-danger py-2"><?=h($er)?></div><?php endforeach; ?>
  <div class="row">
    <div class="col-lg-6 mb-4">
      <div class="card shadow-sm h-100"><div class="card-header py-2"><strong>En attente</strong></div><div class="card-body p-2">
        <table class="table table-sm table-bordered mb-0">
          <thead class="thead-light"><tr><th>#</th><th>Ref</th><th>Nom</th><th>Créée</th><th>Action</th></tr></thead>
          <tbody>
          <?php if(!$pending): ?>
            <tr><td colspan="5" class="text-center text-muted">Aucune compagnie en attente.</td></tr>
          <?php else: foreach($pending as $p): ?>
            <tr>
              <td><?=h($p['id'])?></td>
              <td><code><?=h($p['compagnie_ref'])?></code></td>
              <td><?=h($p['compagnie_name'])?></td>
              <td class="small text-nowrap"><?=h($p['created_at'])?></td>
              <td>
                <form method="post" class="d-inline">
                  <input type="hidden" name="action" value="prepare">
                  <input type="hidden" name="compagnie_ref" value="<?=h($p['compagnie_ref'])?>">
                  <button class="btn btn-primary btn-sm"><i class="fas fa-cog"></i></button>
                </form>
              </td>
            </tr>
          <?php endforeach; endif; ?>
          </tbody>
        </table>
      </div></div>
    </div>
    <div class="col-lg-6 mb-4">
      <div class="card shadow-sm h-100"><div class="card-header py-2"><strong>Configuration Validation</strong></div><div class="card-body">
        <?php if($action==='prepare' && $ref!==''): ?>
          <form method="post" class="mb-2">
            <input type="hidden" name="action" value="validate">
            <input type="hidden" name="compagnie_ref" value="<?=h($ref)?>">
            <div class="form-row">
              <div class="form-group col-md-6">
                <label>Nom Base</label>
                <input name="db_name" class="form-control form-control-sm" required>
              </div>
              <div class="form-group col-md-6">
                <label>Utilisateur DB</label>
                <input name="db_user" class="form-control form-control-sm" required>
              </div>
              <div class="form-group col-md-6">
                <label>Mot de passe DB</label>
                <input name="db_pass" type="password" class="form-control form-control-sm">
              </div>
            </div>
            <div class="d-flex align-items-center">
              <button class="btn btn-success btn-sm mr-2"><i class="fas fa-check"></i> Valider</button>
              <a href="valider_compagnies.php" class="btn btn-secondary btn-sm mr-2"><i class="fas fa-times"></i> Annuler</a>
              <button type="button" class="btn btn-danger btn-sm" data-toggle="collapse" data-target="#rejectBox"><i class="fas fa-ban"></i> Rejeter</button>
            </div>
            <small class="text-muted d-block mt-2">La validation créera les tables et activera la compagnie.</small>
          </form>
      <div id="rejectBox" class="collapse">
            <form method="post" class="border rounded p-2 bg-light">
              <input type="hidden" name="action" value="reject">
  <input type="hidden" name="compagnie_ref" value="<?=h($ref)?>">
        
              <div class="form-group mb-2">
                <label class="small mb-1">Raison du rejet</label>
                <textarea name="reason" class="form-control form-control-sm" rows="3" required placeholder="Expliquez la raison..."></textarea>
              </div>
              <div class="d-flex justify-content-between">
                <button class="btn btn-danger btn-sm" onclick="return confirm('Confirmer le rejet ? Cette action est définitive.');"><i class="fas fa-ban"></i> Confirmer Rejet</button>
                <button type="button" class="btn btn-outline-secondary btn-sm" data-toggle="collapse" data-target="#rejectBox"><i class="fas fa-chevron-up"></i></button>
              </div>
            </form>
          </div>
        <?php else: ?>
          <p class="text-muted mb-0">Sélectionnez une compagnie à gauche pour procéder à sa validation.</p>
        <?php endif; ?>
      </div></div>
    </div>
  </div>
  <p class="text-center text-muted small mt-4 mb-4">&copy; <?=date('Y')?> Validation Compagnies</p>
</div></div><footer class="sticky-footer bg-white"><div class="container my-auto"><div class="text-center my-auto small">&copy; <?=date('Y')?> Backups</div></div></footer></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>
