<?php
@session_start();
@date_default_timezone_set('Africa/Casablanca');

// Connexions (locale + centrale) pour récupérer infos agence identiques à infos.php
@include __DIR__.'/config/connexion.php';            // local: $pdo
@include __DIR__.'/gestion_compagnies/config/connexion.php'; // central: $gc_pdo

function h($s){return htmlspecialchars($s??'',ENT_QUOTES,'UTF-8');}

// Récupération ref agence depuis session ou base locale
$agencyRef = isset($_SESSION['compagnie_ref']) ? $_SESSION['compagnie_ref'] : '';
$agencyName = 'Agence';
$expirationDate = null; $daysRemaining = null; $statusLabel='';

if(isset($pdo) && $pdo instanceof PDO){
  try {
    $row = $pdo->query('SELECT compagnie_name, compagnie_ref FROM compagnie_table LIMIT 1')->fetch();
    if($row){
      if(!empty($row['compagnie_name'])) $agencyName = $row['compagnie_name'];
      if($agencyRef==='') $agencyRef = $row['compagnie_ref'];
    }
  }catch(Throwable $e){/*silent*/}
}
// Expiration (reprise logique infos.php)
if($gc_pdo instanceof PDO && !empty($agencyRef)){
  try {
    $stCols = $gc_pdo->query("SHOW COLUMNS FROM compagnies_table LIKE 'expiartion_date'");
    $colExists = (bool)$stCols->fetch();
    $colName = $colExists ? 'expiartion_date' : 'expiration_date';
    $st = $gc_pdo->prepare("SELECT $colName AS exp_date FROM compagnies_table WHERE compagnie_ref=? LIMIT 1");
    $st->execute([$agencyRef]);
    $expRow = $st->fetch();
    if($expRow && !empty($expRow['exp_date'])){
      $expirationDate = $expRow['exp_date'];
      $today = new DateTime('today');
      try { $expDT = new DateTime($expirationDate); } catch(Throwable $e){ $expDT=null; }
      if($expDT){
        $interval = (int)$today->diff($expDT)->format('%r%a');
        $daysRemaining = $interval;
        if($interval < 0) $statusLabel='Expiré';
        elseif($interval === 0) $statusLabel="Expire aujourd'hui";
        elseif($interval <= 7){ $d=max(0,$interval); $statusLabel='Bientôt ('.$d.' jour'.($d>1?'s':'').' restants)'; }
        else $statusLabel='Actif';
      }
    }
  }catch(Throwable $e){/*silent*/}
}

// Accès restreint : uniquement si abonnement dans son dernier mois (0 <= jours restants < 30)
if(!isset($daysRemaining) || $daysRemaining === null || $daysRemaining >= 30 || $daysRemaining < 0){
  header('Location: infos.php');
  exit;
}

// Marquer la notification de paiement validé comme vue (si affichée avant)
if(!isset($_POST['action'])){ // simple consultation
  if(isset($_SESSION['payment_validated_seen']) === false){
    // Ne rien faire ici; le flag sera créé si la notification a été montrée.
  }
  // On pose le flag de lecture de la validation si jours restants élevés et pas de fichiers / refus
  try {
    if($gc_pdo instanceof PDO){
      $colCheck = $gc_pdo->query("SHOW COLUMNS FROM compagnies_table LIKE 'observation_support'")->fetch();
      $hasObs = (bool)$colCheck;
      $hasRefus=false;
      if($hasObs){
        $stObs=$gc_pdo->prepare('SELECT observation_support FROM compagnies_table WHERE compagnie_ref=? LIMIT 1');
        $stObs->execute([$agencyRef]);
        $hasRefus = (bool)($stObs->fetchColumn());
      }
      $pendingDir = __DIR__.'/gestion_compagnies/files/uploads/'.preg_replace('~[^A-Za-z0-9_-]+~','_',$agencyRef);
      $hasPending=false;
      if(is_dir($pendingDir)){
        foreach(scandir($pendingDir) as $ff){ if($ff==='.'||$ff==='..') continue; if(is_file($pendingDir.'/'.$ff)){ $hasPending=true; break; } }
      }
      if(!$hasRefus && !$hasPending && isset($daysRemaining) && $daysRemaining !== null && $daysRemaining >= 330){
        $_SESSION['payment_validated_seen']=true;
      }
    }
  } catch(Throwable $e){ /* silent */ }
}

// Gestion upload
$uploadMessage=''; $uploadType='';
$allowedExt = ['jpg','jpeg','png','pdf'];
$maxSize = 5*1024*1024; // 5MB
$targetBaseDir = __DIR__.'/gestion_compagnies/files/uploads';
$targetAgencyDir = $targetBaseDir.'/'.preg_replace('~[^a-zA-Z0-9_-]+~','_', (string)$agencyRef);
if(!is_dir($targetAgencyDir)) @mkdir($targetAgencyDir, 0775, true);

// Vérifier si des fichiers existent déjà (attente validation)
$hasExistingPending = false;
if(is_dir($targetAgencyDir)){
  foreach(scandir($targetAgencyDir) as $f){
    if($f==='.'||$f==='..') continue; $p=$targetAgencyDir.'/'.$f; if(is_file($p)){ $hasExistingPending = true; break; }
  }
}

// Récupérer configuration WhatsApp (message + téléphone support)
$supportTel=''; $whatssapMsg=''; $whatsappLink='';
$observationSupport='';
if($gc_pdo instanceof PDO && !empty($agencyRef)){
  try {
  // Récup support tel + msg whatsapp
  // Config globale unique (email_settings_table id=1)
  $stWa = $gc_pdo->query('SELECT support_tel, whatssap_msg FROM email_settings_table WHERE id=1 LIMIT 1');
    if($stWa && ($cfgWa = $stWa->fetch(PDO::FETCH_ASSOC))){
      $supportTel = (string)($cfgWa['support_tel'] ?? '');
      $whatssapMsg = trim((string)($cfgWa['whatssap_msg'] ?? ''));
      if($supportTel !== '' && $whatssapMsg !== ''){
        $waNumber = preg_replace('~[^0-9]+~','', $supportTel); // format international sans +
        if($waNumber !== ''){
          $infoParts = [];
          if(!empty($agencyName)) $infoParts[] = 'Agence: '.$agencyName;
          if(!empty($agencyRef)) $infoParts[] = 'Ref: '.$agencyRef;
          if(!empty($expirationDate)) $infoParts[] = 'Expiration: '.date('d/m/Y', strtotime($expirationDate));
          if(isset($daysRemaining)) $infoParts[] = 'Jours restants: '.$daysRemaining;
          $append = implode(" | ", $infoParts);
          $finalWaMsg = trim($whatssapMsg);
          if($append!=='') $finalWaMsg .= "\n\n".$append;
          $whatsappLink = 'https://wa.me/'.$waNumber.'?text='.rawurlencode($finalWaMsg);
        }
      }
    }
    // Observation de refus éventuelle (si colonne existe)
    try {
      $colObs = $gc_pdo->query("SHOW COLUMNS FROM compagnies_table LIKE 'observation_support'")->fetch();
      if($colObs){
        $stObs = $gc_pdo->prepare('SELECT observation_support FROM compagnies_table WHERE compagnie_ref=? LIMIT 1');
        $stObs->execute([$agencyRef]);
        $observationSupport = trim((string)$stObs->fetchColumn());
      }
    }catch(Throwable $e){/*silent*/}
  }catch(Throwable $e){ /* silent */ }
}

// Variables pour réponse AJAX
$saved = 0; $errorsList = [];
if($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['action']) && $_POST['action']==='upload_justif'){
  if($hasExistingPending){
    $uploadMessage = "Des fichiers sont déjà en attente de validation."; $uploadType='warning';
  } else {
  if(empty($agencyRef)){
    $uploadMessage = "Référence agence introuvable."; $uploadType='danger';
  } elseif(!isset($_FILES['justif_files'])){
    $uploadMessage = "Aucun fichier reçu."; $uploadType='warning';
  } else {
    $files = $_FILES['justif_files'];
    $count = is_array($files['name']) ? count($files['name']) : 0;
    if($count>3){
      $uploadMessage = "Maximum 3 fichiers autorisés par envoi."; $uploadType='danger';
    } else {
  $saved=0; $errorsList=[];
  // Nouveau téléversement => réinitialiser le flag de validation vue pour laisser place aux nouveaux statuts
  unset($_SESSION['payment_validated_seen']);
  for($i=0;$i<$count;$i++){
      if($files['error'][$i]!==UPLOAD_ERR_OK){ $errorsList[]='Erreur fichier '.($files['name'][$i]??'#'); continue; }
      $origName = $files['name'][$i];
      $size = (int)$files['size'][$i];
      $tmp = $files['tmp_name'][$i];
      $ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
      if(!in_array($ext,$allowedExt,true)){ $errorsList[]='Extension non autorisée: '.h($origName); continue; }
      if($size > $maxSize){ $errorsList[]='Fichier trop volumineux (>5MB): '.h($origName); continue; }
      $safeBase = preg_replace('~[^a-zA-Z0-9._-]+~','_', pathinfo($origName, PATHINFO_FILENAME));
      if($safeBase==='') $safeBase='justif';
      $finalName = $safeBase.'_'.date('Ymd_His').'_' . substr(bin2hex(random_bytes(4)),0,8).'.'.$ext;
      $dest = $targetAgencyDir.'/'.$finalName;
      if(@move_uploaded_file($tmp,$dest)){
        @chmod($dest,0644);
        $saved++;
      } else {
        $errorsList[]='Échec déplacement: '.h($origName);
      }
    }
    if(isset($uploadType) && $uploadType==='danger'){
      // skip
    } elseif($saved>0){
      $uploadMessage = $saved.' fichier'.($saved>1?'s':'').' envoyé'.($saved>1?'s':'').' avec succès.'; $uploadType='success';
      if($errorsList) $uploadMessage .= ' (Avec erreurs partielles)';
      // Effacer éventuelle observation de refus précédente et réinitialiser validation_note à 0 pour prochaine validation
      if($gc_pdo instanceof PDO){
        try {
          $colCheckVal = $gc_pdo->query("SHOW COLUMNS FROM compagnies_table LIKE 'validation_note'")->fetch();
          if(!$colCheckVal){
            try { $gc_pdo->exec("ALTER TABLE compagnies_table ADD validation_note TINYINT(1) NOT NULL DEFAULT 0"); } catch(Throwable $a){ }
          }
          $gc_pdo->prepare("UPDATE compagnies_table SET observation_support=NULL, validation_note=0 WHERE compagnie_ref=? LIMIT 1")->execute([$agencyRef]);
        } catch(Throwable $e){ /* silent */ }
      }
      $observationSupport='';
      // Notification email support et super admins (pas client)
      if($gc_pdo instanceof PDO){
        try {
          $cfg = null; $stCfg = $gc_pdo->prepare('SELECT smtp_host,smtp_port,smtp_username,smtp_password,encryption,from_email,from_name,support_email,auth_enabled,active FROM email_settings_table WHERE id=1 LIMIT 1');
          $stCfg->execute(); $cfg=$stCfg->fetch(PDO::FETCH_ASSOC);
          if($cfg && !empty($cfg['active']) && !empty($cfg['support_email'])){
            require_once __DIR__.'/PHPMailer/src/Exception.php';
            require_once __DIR__.'/PHPMailer/src/PHPMailer.php';
            require_once __DIR__.'/PHPMailer/src/SMTP.php';
            $mailer = new PHPMailer\PHPMailer\PHPMailer(true);
            try {
              $mailer->isSMTP();
              $mailer->Host = $cfg['smtp_host'];
              $mailer->Port = (int)$cfg['smtp_port'];
              if(!empty($cfg['auth_enabled'])){
                $mailer->SMTPAuth = true;
                $mailer->Username = $cfg['smtp_username'];
                $mailer->Password = $cfg['smtp_password'];
              } else { $mailer->SMTPAuth = false; }
              $enc = strtolower($cfg['encryption']);
              if($enc==='ssl'){ $mailer->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS; }
              elseif($enc==='tls'){ $mailer->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS; }
              else { $mailer->SMTPSecure = false; }
              $mailer->CharSet='UTF-8';
              $fromEmail = $cfg['from_email'] ?: 'no-reply@local';
              $fromName  = $cfg['from_name'] ?: 'Notification';
              $mailer->setFrom($fromEmail,$fromName);
              // Support email(s)
              $supportEmails = preg_split('/[;,\s]+/',$cfg['support_email'],-1,PREG_SPLIT_NO_EMPTY);
              foreach($supportEmails as $em){ $em=trim($em); if(filter_var($em,FILTER_VALIDATE_EMAIL)) $mailer->addAddress($em); }
              // Récupération emails Super admin (centrale)
              $superAdmins = [];
              try {
                if($gc_pdo instanceof PDO){
                  // users_compagnie central
                  try { $stS=$gc_pdo->prepare("SELECT user_email FROM users_compagnie WHERE compagnie_ref=? AND (user_role='Super admin' OR user_role IS NULL) LIMIT 15"); $stS->execute([$agencyRef]); while($rS=$stS->fetch(PDO::FETCH_ASSOC)){ $em=trim($rS['user_email']??''); if($em!=='') $superAdmins[$em]=true; } } catch(Throwable $eUC){}
                  // users_table central (si rôle stocké là aussi)
                  try { $stT=$gc_pdo->prepare("SELECT user_email FROM users_table WHERE compagnie_ref=? AND user_role='Super admin' AND status=1 LIMIT 15"); $stT->execute([$agencyRef]); while($rT=$stT->fetch(PDO::FETCH_ASSOC)){ $em=trim($rT['user_email']??''); if($em!=='') $superAdmins[$em]=true; } } catch(Throwable $eUT){}
                }
              } catch(Throwable $eList){ }
              // Ajouter chaque super admin (éviter doublons et support déjà ajouté)
              foreach(array_keys($superAdmins) as $sa){ $already=false; foreach($supportEmails as $sem){ if(strcasecmp($sa,$sem)===0) { $already=true; break; } } if(!$already) $mailer->addAddress($sa); }
              $mailer->Subject = 'Nouveaux justificatifs de paiement - '.$agencyRef;
              $mailer->isHTML(true);
              $listItems='';
              $scanList = scandir($targetAgencyDir);
              foreach($scanList as $sf){ if($sf==='.'||$sf==='..') continue; $p=$targetAgencyDir.'/'.$sf; if(is_file($p)) $listItems.='- '.htmlspecialchars($sf)." (".number_format(filesize($p)/1024,1,'.','')." KB)\n"; }
              $bodyCore = "<p style='margin:0 0 12px'>Des justificatifs de paiement ont été déposés pour l'Agence <strong>".htmlspecialchars($agencyName)." (Ref: ".htmlspecialchars($agencyRef).")</strong>.</p>".
                "<div style='background:#f8f9fa;border:1px solid #e2e6ea;border-radius:6px;padding:10px;font-family:monospace;font-size:12px;white-space:pre-line;line-height:1.3'>".nl2br($listItems)."</div>".
                "<p style='margin:16px 0 0'>Connectez-vous à l'espace support pour valider.</p>";
              $mailer->Body = "<div style='background:#f1f5f9;padding:24px;font-family:Arial,Helvetica,sans-serif;color:#1e293b'><table role='presentation' width='100%' cellpadding='0' cellspacing='0' style='max-width:640px;margin:0 auto;background:#ffffff;border-radius:10px;overflow:hidden;border:1px solid #e2e8f0'><thead><tr><td style='background:#2563eb;padding:16px 20px'><h1 style='margin:0;font-size:18px;color:#fff;font-weight:600;'>Nouveaux justificatifs reçus</h1></td></tr></thead><tbody><tr><td style='padding:20px'>".$bodyCore."</td></tr><tr><td style='background:#f8fafc;padding:14px 20px;text-align:center;font-size:12px;color:#64748b'>Cet email est généré automatiquement • Merci de ne pas répondre</td></tr></tbody></table></div>";
              $mailer->AltBody = "Nouveaux justificatifs reçus\nAgence: $agencyName ($agencyRef)\n".preg_replace('~<[^>]+>~','',$listItems);
              try {
                $mailer->send();
              } catch(Throwable $eSend){
                try { @file_put_contents(__DIR__.'/logs_email_upload.txt', date('Y-m-d H:i:s')."\t".$agencyRef."\t".'ENVOI_ECHEC: '.$eSend->getMessage()."\n", FILE_APPEND); } catch(Throwable $eLog){}
              }
            } catch(Throwable $eMail){
              try { @file_put_contents(__DIR__.'/logs_email_upload.txt', date('Y-m-d H:i:s')."\t".$agencyRef."\t".'ERREUR_INIT: '.$eMail->getMessage()."\n", FILE_APPEND); } catch(Throwable $eLog2){}
            }
          }
        } catch(Throwable $eCfg){ /* silent */ }
      }
    } else {
      $uploadMessage = 'Aucun fichier sauvegardé. '.implode(' | ',$errorsList); $uploadType='danger';
  }
  }
  }
  }
}

// Lister fichiers existants (après éventuel upload pour avoir la liste à jour)
$existingFiles = [];
if(is_dir($targetAgencyDir)){
  $scan = scandir($targetAgencyDir);
  foreach($scan as $f){
    if($f==='.'||$f==='..') continue;
    $path=$targetAgencyDir.'/'.$f;
    if(is_file($path)){
      $existingFiles[]=[ 'name'=>$f, 'size'=>filesize($path), 'mtime'=>filemtime($path) ];
    }
  }
  usort($existingFiles,function($a,$b){ return $b['mtime']<=>$a['mtime']; });
}

// Réponse AJAX JSON si demandé
if(isset($_POST['ajax']) && $_POST['ajax']=='1'){
  header('Content-Type: application/json; charset=utf-8');
  echo json_encode([
    'status'=>$uploadType,
    'message'=>$uploadMessage,
    'saved'=>$saved,
    'errors'=>$errorsList,
    'files'=>array_map(function($f){return $f['name'];}, $existingFiles),
  ]);
  exit;
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<title>Justificatif Paiement</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>
  .card-upload{border-left:4px solid #4e73df;}
  .file-list small{display:block;line-height:1.1}
</style>
</head>
<body id="page-top">
<div id="wrapper">
  <?php include __DIR__.'/includes/sidebar.php'; ?>
  <div id="content-wrapper" class="d-flex flex-column">
    <div id="content">
      <?php include __DIR__.'/includes/topbar.php'; ?>
      <div class="container-fluid">
        <div class="d-flex align-items-center justify-content-between mb-4">
          <h1 class="h5 mb-0 text-gray-800"><i class="fas fa-file-upload text-primary"></i> Envoi Justificatif Paiement</h1>
          <a href="dashboard.php" class="btn btn-sm btn-secondary"><i class="fas fa-home"></i> Dashboard</a>
        </div>
        <div class="row">
          <div class="col-lg-8 mb-4">
            <div class="card shadow card-upload mb-3">
              <div class="card-header py-2"><strong>Informations Agence</strong></div>
              <div class="card-body py-2">
                <dl class="row mb-0">
                  <dt class="col-sm-4">Nom</dt><dd class="col-sm-8 mb-1"><?=h($agencyName)?></dd>
                  <dt class="col-sm-4">Référence</dt><dd class="col-sm-8 mb-1"><?=h($agencyRef?:'-')?></dd>
                  <dt class="col-sm-4">Expiration</dt><dd class="col-sm-8 mb-1"><?php echo $expirationDate? h(date('d/m/Y',strtotime($expirationDate))) : '<span class="text-muted">-</span>'; ?></dd>
                  <dt class="col-sm-4">Statut</dt><dd class="col-sm-8 mb-1"><?php echo $statusLabel? h($statusLabel):'<span class="text-muted">-</span>'; ?></dd>
                </dl>
              </div>
            </div>
            <div class="card shadow card-upload">
              <div class="card-header py-2"><strong>Transmettre un justificatif</strong></div>
              <div class="card-body">
                <?php if($uploadMessage): ?>
                  <div class="alert alert-<?=$uploadType?> py-2"><?=h($uploadMessage)?></div>
                <?php endif; ?>
                <?php if(!empty($observationSupport)): ?>
                  <div class="alert alert-danger py-2 mb-2">
                    <strong><i class="fas fa-times-circle"></i> Paiement refusé</strong><br>
                    <?=h($observationSupport)?><br>
                    <span class="small d-block mt-1">Veuillez renvoyer un justificatif correct (JPG, PNG ou PDF &lt; 5MB).</span>
                  </div>
                <?php endif; ?>
                <?php if(empty($agencyRef)): ?>
                  <div class="alert alert-danger py-2">Référence agence introuvable. Impossible d'envoyer un fichier.</div>
                <?php elseif($hasExistingPending): ?>
                  <div class="alert alert-info py-2 mb-0"><i class="fas fa-info-circle"></i> Des fichiers ont déjà été envoyés et sont en attente de vérification. Vous ne pouvez pas en envoyer d'autres pour le moment.</div>
                <?php else: ?>
        <form id="justifUploadForm" method="post" enctype="multipart/form-data" novalidate>
                  <input type="hidden" name="action" value="upload_justif">
                  <div class="form-group mb-2">
                    <label>Fichiers (JPG, PNG, PDF) - max 5MB chacun</label>
          <input type="file" name="justif_files[]" id="justif_files" class="form-control-file" multiple accept=".jpg,.jpeg,.png,.pdf" required>
          <small class="form-text text-muted" id="fileHelpMsg">Sélectionnez jusqu'à 3 fichiers.</small>
          <div class="small text-danger d-none" id="fileLimitError">Maximum 3 fichiers autorisés.</div>
                  </div>
                  <div class="progress mb-2 d-none" id="uploadProgressWrapper" style="height:14px;">
                    <div class="progress-bar progress-bar-striped progress-bar-animated" id="uploadProgressBar" style="width:0%">0%</div>
                  </div>
                  <button id="btnSubmitJustif" class="btn btn-primary btn-sm"><i class="fas fa-upload"></i> Envoyer</button>
                  <span id="uploadStatus" class="small ml-2 text-muted"></span>
                </form>
                <?php endif; ?>
              </div>
            </div>
          </div>
          <div class="col-lg-4 mb-4">
            <div class="card shadow card-upload h-100">
              <div class="card-header py-2"><strong>Fichiers Envoyés</strong></div>
              <div class="card-body file-list" style="max-height:420px;overflow:auto;">
                <?php if(!$existingFiles): ?>
                  <p class="text-muted small mb-0">Aucun fichier pour le moment.</p>
                <?php else: ?>
                  <ul class="list-unstyled mb-0 small">
                    <?php foreach($existingFiles as $f): $ext=strtolower(pathinfo($f['name'],PATHINFO_EXTENSION)); ?>
                      <li class="mb-2">
                        <i class="fas fa-file-<?php echo ($ext==='pdf'?'pdf':'image'); ?> text-secondary"></i>
                        <a href="<?='gestion_compagnies/files/uploads/'.h($agencyRef).'/'.rawurlencode($f['name']);?>" target="_blank"><?=h($f['name'])?></a>
                        <small class="text-muted">(<?php echo number_format($f['size']/1024,1,'.','');?> KB, <?php echo date('d/m H:i',$f['mtime']); ?>)</small>
                      </li>
                    <?php endforeach; ?>
                  </ul>
                <?php endif; ?>
                <div id="postSuccessMessage" class="mt-3 <?php echo ($hasExistingPending||$observationSupport)?'' : 'd-none';?>">
                  <?php if($observationSupport): ?>
                    <div class="alert alert-danger mb-2 py-2">
                      <strong><i class="fas fa-times-circle"></i> Paiement refusé</strong><br>
                      <?=h($observationSupport)?><br>
                      <span class="small d-block mt-1">Veuillez renvoyer un justificatif correct (formats: JPG, PNG, PDF, taille max 5MB par fichier).</span>
                    </div>
                  <?php else: ?>
                    <div class="alert alert-info mb-2 py-2"><i class="fas fa-info-circle"></i> Votre période d'abonnement sera prolongée après la vérification (moins de 24h).</div>
                  <?php endif; ?>
                  <?php if($whatsappLink): ?>
                    <a href="<?=h($whatsappLink)?>" target="_blank" class="btn btn-success btn-sm"><i class="fab fa-whatsapp"></i> Contacter le support sur WhatsApp</a>
                  <?php endif; ?>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="alert alert-info small py-2"><i class="fas fa-info-circle"></i> Le support examinera votre justificatif et mettra à jour votre abonnement si nécessaire.</div>
      </div>
    </div>
    <?php include __DIR__.'/includes/footer.php'; ?>
  </div>
</div>
<!-- Modal succès -->
<div class="modal fade" id="uploadSuccessModal" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header bg-success text-white py-2">
        <h6 class="modal-title"><i class="fas fa-check-circle"></i> Envoi réussi</h6>
        <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      </div>
      <div class="modal-body py-3">
        <p class="mb-2" id="successModalMsg">Vos fichiers ont été transmis.</p>
  <div class="alert alert-info py-2 mb-2"><i class="fas fa-clock"></i> Votre période d'abonnement sera prolongée après la vérification (moins de 24h).</div>
        <p class="small text-muted mb-0">Vous pouvez fermer cette fenêtre et revenir plus tard.</p>
      </div>
      <div class="modal-footer py-2">
        <button type="button" class="btn btn-sm btn-secondary" data-dismiss="modal">Fermer</button>
      </div>
    </div>
  </div>
</div>
<a class="scroll-to-top rounded" href="#page-top"><i class="fas fa-angle-up"></i></a>
<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>
var HAS_EXISTING_PENDING = <?php echo $hasExistingPending?'true':'false'; ?>;
(function(){
  const form = document.getElementById('justifUploadForm');
  if(!form){
    // Ajouter listener de reload modal même si pas de formulaire
    $('#uploadSuccessModal').on('hidden.bs.modal', function(){ if(window.__justifSuccess) location.reload(); });
    return;
  }
  const input = document.getElementById('justif_files');
  const progressWrapper = document.getElementById('uploadProgressWrapper');
  const progressBar = document.getElementById('uploadProgressBar');
  const statusSpan = document.getElementById('uploadStatus');
  const btn = document.getElementById('btnSubmitJustif');
  let stagedFiles = [];// File objects
  // Créer zone liste
  const fileHelp = document.getElementById('fileHelpMsg');
  const listWrap = document.createElement('ul');
  listWrap.className='list-unstyled small mt-2 mb-2';
  fileHelp.parentNode.insertBefore(listWrap, fileHelp.nextSibling);
  function refreshList(){
    listWrap.innerHTML='';
    stagedFiles.forEach((f,i)=>{
      const li=document.createElement('li');
      li.innerHTML='<i class="fas fa-paperclip text-secondary"></i> '+f.name+' <span class="text-muted">('+(Math.round(f.size/102.4)/10)+' KB)</span> <button type="button" class="btn btn-link btn-sm p-0 ml-1 text-danger remove-file" data-idx="'+i+'" title="Retirer"><i class="fas fa-times"></i></button>';
      listWrap.appendChild(li);
    });
    if(stagedFiles.length){
      fileHelp.textContent='Fichiers sélectionnés ('+stagedFiles.length+'/3).';
    } else {
      fileHelp.textContent='Sélectionnez jusqu\'à 3 fichiers.';
    }
  }
  listWrap.addEventListener('click', function(e){
    if(e.target.closest('.remove-file')){
      const idx=parseInt(e.target.closest('.remove-file').getAttribute('data-idx'));
      stagedFiles.splice(idx,1);
      refreshList();
      document.getElementById('fileLimitError').classList.add('d-none');
      btn.disabled=false;
    }
  });
  form.addEventListener('submit', function(e){
    e.preventDefault();
    if(!stagedFiles.length){ input.focus(); return; }
    const fd = new FormData();
    fd.append('action','upload_justif');
    stagedFiles.forEach(f=> fd.append('justif_files[]', f, f.name));
    fd.append('ajax','1');
    progressWrapper.classList.remove('d-none');
    progressBar.style.width='0%'; progressBar.textContent='0%';
    statusSpan.textContent='Envoi en cours...';
    btn.disabled = true;
    const xhr = new XMLHttpRequest();
    xhr.open('POST', window.location.href, true);
    xhr.upload.onprogress = function(ev){ if(ev.lengthComputable){ const p = Math.round((ev.loaded/ev.total)*100); progressBar.style.width=p+'%'; progressBar.textContent=p+'%'; }};
    xhr.onreadystatechange = function(){ if(xhr.readyState===4){ btn.disabled=false; if(xhr.status===200){ try{ const res=JSON.parse(xhr.responseText); if(res.status==='success'){ statusSpan.textContent='Terminé.'; window.__justifSuccess=true; $('#uploadSuccessModal').modal('show'); document.getElementById('postSuccessMessage').classList.remove('d-none'); // bloquer nouvelle soumission
            input.disabled=true; btn.disabled=true; form.classList.add('position-relative');
          } else { statusSpan.textContent='Erreur: '+res.message; progressBar.classList.add('bg-danger'); } }catch(err){ statusSpan.textContent='Réponse invalide.'; progressBar.classList.add('bg-danger'); } } else if(xhr.readyState===4){ statusSpan.textContent='Erreur réseau.'; progressBar.classList.add('bg-danger'); } }};
    xhr.send(fd);
  });
  // Limite de 3 fichiers côté client
  input.addEventListener('change', function(){
    const limitError = document.getElementById('fileLimitError');
    // Ajouter nouveaux fichiers tout en respectant max 3
    for(let i=0;i<this.files.length;i++){
      if(stagedFiles.length>=3) break;
      stagedFiles.push(this.files[i]);
    }
    if(stagedFiles.length>3){
      stagedFiles = stagedFiles.slice(0,3);
    }
    if(stagedFiles.length>=3){ btn.disabled=false; }
    if(stagedFiles.length>3){ limitError.classList.remove('d-none'); btn.disabled=true; } else { limitError.classList.add('d-none'); }
    refreshList();
    // Reset input pour permettre re-sélection même nom
    this.value='';
  });
  refreshList();
  // Si des fichiers existent déjà (cas reload rapide): désactiver
  if(HAS_EXISTING_PENDING){ if(input){ input.disabled=true; } if(btn){ btn.disabled=true; } }
  $('#uploadSuccessModal').on('hidden.bs.modal', function(){ if(window.__justifSuccess) location.reload(); });
})();
</script>
</body>
</html>
