<?php
session_start();
@date_default_timezone_set('Africa/Casablanca');
require_once __DIR__.'/config/connexion.php';
require_once __DIR__.'/config/auth.php';
gc_require_login();

$messages=[]; $action=$_POST['action']??'';
if(isset($_GET['justif_validated'])){
  $messages[]=['type'=>'success','text'=>'Justificatif validé et expiration prolongée.'];
}

// CREATE / UPDATE / TOGGLE
if($_SERVER['REQUEST_METHOD']==='POST'){
  try{
    if($action==='create'){
      $ref=trim($_POST['compagnie_ref']??'');
      $name=trim($_POST['compagnie_name']??'');
      $db=trim($_POST['compagnie_db']??'');
      $dbu=trim($_POST['compagnie_db_user']??'');
      $dbp=trim($_POST['compagnie_db_pass']??'');
      if($ref===''||$db==='') throw new Exception('Référence et base requis');
      $st=$gc_pdo->prepare('SELECT COUNT(*) FROM compagnies_table WHERE compagnie_ref=?'); $st->execute([$ref]);
      if($st->fetchColumn()>0) throw new Exception('Référence déjà existante');
      if($hasNameCol){
        $ins=$gc_pdo->prepare('INSERT INTO compagnies_table(compagnie_ref, compagnie_name, compagnie_db, compagnie_db_user, compagnie_db_pass, active, created_at) VALUES(?,?,?,?,?,1,NOW())');
        $ins->execute([$ref,$name,$db,$dbu,$dbp]);
      } else {
        $ins=$gc_pdo->prepare('INSERT INTO compagnies_table(compagnie_ref,compagnie_db,compagnie_db_user,compagnie_db_pass,active,created_at) VALUES(?,?,?,?,1,NOW())');
        $ins->execute([$ref,$db,$dbu,$dbp]);
      }
      $messages[]=['type'=>'success','text'=>'Compagnie ajoutée'];
    } elseif($action==='update') {
      $id=(int)($_POST['id']??0);
      $name=trim($_POST['compagnie_name']??'');
      $db=trim($_POST['compagnie_db']??'');
      $dbu=trim($_POST['compagnie_db_user']??'');
      $dbp=trim($_POST['compagnie_db_pass']??'');
      if($hasNameCol){
        $up=$gc_pdo->prepare('UPDATE compagnies_table SET compagnie_name=?, compagnie_db=?, compagnie_db_user=?, compagnie_db_pass=? WHERE id=? LIMIT 1');
        $up->execute([$name,$db,$dbu,$dbp,$id]);
      } else {
        $up=$gc_pdo->prepare('UPDATE compagnies_table SET compagnie_db=?, compagnie_db_user=?, compagnie_db_pass=? WHERE id=? LIMIT 1');
        $up->execute([$db,$dbu,$dbp,$id]);
      }
      $messages[]=['type'=>'success','text'=>'Compagnie mise à jour'];
    } elseif($action==='toggle') {
      $id=(int)($_POST['id']??0);
      $gc_pdo->exec("UPDATE compagnies_table SET active = CASE WHEN active=1 THEN 0 ELSE 1 END WHERE id=$id LIMIT 1");
      $messages[]=['type'=>'success','text'=>'Statut basculé'];
    } elseif($action==='delete') {
      $id=(int)($_POST['id']??0);
      // Récupérer la référence avant suppression
      $refToDelete=null;
      try {
        $stRef=$gc_pdo->prepare('SELECT compagnie_ref FROM compagnies_table WHERE id=? LIMIT 1');
        $stRef->execute([$id]);
        $refToDelete=$stRef->fetchColumn();
      } catch(Throwable $e) { }
      // Supprimer utilisateurs associés dans users_table (base centrale)
      if($refToDelete){
        try {
          $stDelUsers=$gc_pdo->prepare('DELETE FROM users_table WHERE compagnie_ref=?');
          $stDelUsers->execute([$refToDelete]);
        } catch(Throwable $e){ /* silent */ }
        // Supprimer utilisateurs en attente / pré-inscrits dans users_compagnie
        try {
          $gc_pdo->prepare('DELETE FROM users_compagnie WHERE compagnie_ref=?')->execute([$refToDelete]);
        } catch(Throwable $e){ /* silent */ }
      }
      // Supprimer enregistrements de config email éventuels
      if($refToDelete){
        try { $gc_pdo->prepare('DELETE FROM email_settings_table WHERE compagnie_ref=?')->execute([$refToDelete]); } catch(Throwable $e) { }
      }
      // Supprimer dossier justificatifs éventuel
      if($refToDelete){
        $dir = __DIR__.'/files/uploads/'.preg_replace('~[^a-zA-Z0-9_-]+~','_',$refToDelete);
        if(is_dir($dir)){
          foreach(scandir($dir) as $f){ if($f==='.'||$f==='..') continue; $p=$dir.'/'.$f; if(is_file($p)) @unlink($p); }
          @rmdir($dir);
        }
      }
      // Supprimer la compagnie
      $gc_pdo->prepare('DELETE FROM compagnies_table WHERE id=? LIMIT 1')->execute([$id]);
      $messages[]=['type'=>'success','text'=>'Compagnie et utilisateurs associés supprimés'];
    }
  } catch(Throwable $e){ $messages[]=['type'=>'danger','text'=>$e->getMessage()]; }
}

// Fetch list
// Vérifier si colonne compagnie_name existe
$hasNameCol = false;
try {
  $cols = $gc_pdo->query("SHOW COLUMNS FROM compagnies_table LIKE 'compagnie_name'")->fetchAll();
  $hasNameCol = !empty($cols);
} catch(Throwable $e) { }
// Déterminer colonne expiration (expiration_date ou expiartion_date)
$expCol='';
try { if($gc_pdo->query("SHOW COLUMNS FROM compagnies_table LIKE 'expiartion_date'")->fetch()){ $expCol='expiartion_date'; } elseif($gc_pdo->query("SHOW COLUMNS FROM compagnies_table LIKE 'expiration_date'")->fetch()){ $expCol='expiration_date'; } } catch(Throwable $e) { }
// Construction SELECT
$select = 'SELECT id, '.($hasNameCol?'compagnie_name, ':'').'compagnie_ref, compagnie_db, compagnie_db_user, compagnie_db_pass, active, created_at';
if($expCol) $select .= ', '.$expCol.' AS exp_date';
$select .= ' FROM compagnies_table ORDER BY compagnie_ref';
try { $companies=$gc_pdo->query($select)->fetchAll(PDO::FETCH_ASSOC); }
catch(Throwable $e){ $companies=[]; $messages[]=['type'=>'danger','text'=>'Lecture impossible: '.$e->getMessage()]; }

?><!DOCTYPE html><html lang="fr"><head><meta charset="utf-8"><title>Gestion 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}.small-pass{font-size:11px;color:#666}</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-building text-primary"></i> Compagnies</h3><button class="btn btn-sm btn-primary" data-toggle="collapse" data-target="#formAdd"><i class="fas fa-plus"></i> Nouvelle</button></div>
  <?php foreach($messages as $m): ?><div class="alert alert-<?php echo htmlspecialchars($m['type']); ?> py-2"><?php echo htmlspecialchars($m['text']); ?></div><?php endforeach; ?>
  <div id="formAdd" class="collapse mb-4"><div class="card shadow-sm"><div class="card-header py-2"><strong>Ajouter Compagnie</strong></div><div class="card-body">
    <form method="post" class="row">
      <input type="hidden" name="action" value="create">
  <div class="form-group col-md-3"><label>Référence</label><input name="compagnie_ref" class="form-control" required></div>
  <?php if($hasNameCol): ?>
  <div class="form-group col-md-3"><label>Nom</label><input name="compagnie_name" class="form-control"></div>
  <?php endif; ?>
      <div class="form-group col-md-3"><label>Base</label><input name="compagnie_db" class="form-control" required></div>
      <div class="form-group col-md-3"><label>Utilisateur DB</label><input name="compagnie_db_user" class="form-control"></div>
      <div class="form-group col-md-3"><label>Mot de passe DB</label><input name="compagnie_db_pass" class="form-control"></div>
      <div class="col-12 mt-2"><button class="btn btn-success"><i class="fas fa-save"></i> Enregistrer</button></div>
    </form>
  </div></div></div>
  <div class="card shadow-sm"><div class="card-header py-2 d-flex justify-content-between align-items-center"><strong>Liste</strong>
    <div class="input-group input-group-sm" style="max-width:260px;">
      <div class="input-group-prepend"><span class="input-group-text"><i class="fas fa-search"></i></span></div>
      <input type="text" id="filterCompanies" class="form-control" placeholder="Filtrer...">
    </div>
  </div><div class="card-body p-2">
  <div class="table-responsive"><table class="table table-sm table-bordered mb-0" id="companiesTable"><thead class="thead-light"><tr><?php if($hasNameCol): ?><th>Nom</th><?php endif; ?><th>Ref</th><th>Active</th><th>Expiration</th><th>Jours Restants</th><th>Créé</th><th style="width:200px">Actions <span class="badge badge-light" id="resultCount"></span></th></tr></thead><tbody>
      <?php if(!$companies): ?><tr><td colspan="<?php echo $hasNameCol?7:6; ?>" class="text-center text-muted">Aucune compagnie</td></tr><?php else: foreach($companies as $c): ?>
      <?php
        $justifDir = __DIR__.'/files/uploads/'.preg_replace('~[^a-zA-Z0-9_-]+~','_', $c['compagnie_ref']);
        $justifCount = 0;
        if(is_dir($justifDir)){
          foreach(scandir($justifDir) as $jf){ if($jf==='.'||$jf==='..') continue; if(is_file($justifDir.'/'.$jf)) $justifCount++; }
        }
        // Calcul jours restants
        $expDisplay='-'; $daysDisplay='-';
        if(isset($c['exp_date']) && !empty($c['exp_date'])){
          $expDisplay = htmlspecialchars($c['exp_date']);
          try {
            $todayY = new DateTime('today');
            $expDT = new DateTime($c['exp_date']);
            $diff = (int)$todayY->diff($expDT)->format('%r%a');
            $daysDisplay = $diff;
          } catch(Throwable $e) { }
        }
      ?>
 <tr class="company-row <?php echo $c['active']?'' :'table-secondary'; ?>">
        <?php if($hasNameCol): ?><td><?php echo htmlspecialchars($c['compagnie_name']); ?></td><?php endif; ?>
        <td><strong><?php echo htmlspecialchars($c['compagnie_ref']); ?></strong></td>
        <td><?php echo $c['active']?'<span class="badge badge-success">Oui</span>':'<span class="badge badge-danger">Non</span>'; ?></td>
        <td class="small text-nowrap"><?php echo $expDisplay; ?></td>
        <td class="small text-center"><?php echo $daysDisplay; ?></td>
        <td class="small text-nowrap"><?php echo htmlspecialchars($c['created_at']); ?></td>
        <td>
          <button class="btn btn-sm btn-info" data-toggle="collapse" data-target="#edit<?php echo $c['id']; ?>"><i class="fas fa-edit"></i></button>
          <form method="post" class="d-inline" onsubmit="return confirm('Basculer statut ?');"><input type="hidden" name="action" value="toggle"><input type="hidden" name="id" value="<?php echo $c['id']; ?>"><button class="btn btn-sm btn-warning"><i class="fas fa-power-off"></i></button></form>
          <form method="post" class="d-inline" onsubmit="return confirm('Supprimer définitivement ?');"><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?php echo $c['id']; ?>"><button class="btn btn-sm btn-danger"><i class="fas fa-trash"></i></button></form>
          <?php if($justifCount>0): ?>
            <a class="btn btn-sm btn-outline-info ml-1" title="Justificatifs à vérifier" href="review_justifs.php?ref=<?php echo urlencode($c['compagnie_ref']); ?>">
              <i class="fas fa-file-upload"></i>
            </a>
          <?php endif; ?>
        </td>
      </tr>
 <tr id="edit<?php echo $c['id']; ?>" class="collapse bg-light company-edit-row"><td colspan="<?php echo $hasNameCol?7:6; ?>">
        <form method="post" class="form-row align-items-end">
          <input type="hidden" name="action" value="update"><input type="hidden" name="id" value="<?php echo $c['id']; ?>">
      <?php if($hasNameCol): ?><div class="form-group col-md-3"><label>Nom</label><input name="compagnie_name" class="form-control" value="<?php echo htmlspecialchars($c['compagnie_name']); ?>"></div><?php endif; ?>
          <div class="form-group col-md-3"><label>Base</label><input name="compagnie_db" class="form-control" value="<?php echo htmlspecialchars($c['compagnie_db']); ?>"></div>
          <div class="form-group col-md-3"><label>Utilisateur DB</label><input name="compagnie_db_user" class="form-control" value="<?php echo htmlspecialchars($c['compagnie_db_user']); ?>"></div>
          <div class="form-group col-md-3"><label>Mot de passe DB</label><input name="compagnie_db_pass" class="form-control" value="<?php echo htmlspecialchars($c['compagnie_db_pass']); ?>"></div>
          <div class="form-group col-md-3"><button class="btn btn-primary"><i class="fas fa-save"></i> Sauvegarder</button></div>
        </form>
      </td></tr>
      <?php endforeach; endif; ?>
    </tbody></table></div>
  </div></div>
  <p class="text-center text-muted small mt-4 mb-4">&copy; <?php echo date('Y'); ?> Gestion Compagnies</p>
</div></div><footer class="sticky-footer bg-white"><div class="container my-auto"><div class="text-center my-auto small">&copy; <?php echo 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><script>
(function($){
  function applyFilter(){
    var q = $('#filterCompanies').val().toLowerCase().trim();
    var visible = 0;
    $('.company-row').each(function(){
      var row = $(this);
      var txt = row.text().toLowerCase();
      if(!q || txt.indexOf(q) !== -1){
        row.show();
        // show edit row only if was expanded previously
        var editRow = row.next('.company-edit-row');
        if(editRow.length && editRow.hasClass('show')) editRow.show();
        visible++;
      } else {
        row.hide();
        row.next('.company-edit-row').hide();
      }
    });
    $('#resultCount').text(visible);
  }
  $('#filterCompanies').on('input', applyFilter);
  applyFilter();
})(jQuery);
</script></body></html>
