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

$ref = isset($_GET['ref']) ? trim($_GET['ref']) : '';
if($ref===''){ echo 'Référence manquante'; exit; }
$cleanRef = preg_replace('~[^a-zA-Z0-9_-]+~','_', $ref);
$dir = __DIR__.'/files/uploads/'.$cleanRef;
$files=[];
if(is_dir($dir)){
  foreach(scandir($dir) as $f){ if($f==='.'||$f==='..') continue; $p=$dir.'/'.$f; if(is_file($p)) $files[]=['name'=>$f,'size'=>filesize($p),'mtime'=>filemtime($p)]; }
  usort($files,function($a,$b){return $b['mtime']<=>$a['mtime'];});
}
$message=''; $msgType='';
// Simple logging helper
if(!is_dir(__DIR__.'/../logs')) @mkdir(__DIR__.'/../logs',0775,true);
function rj_log($ref,$phase,$msg){ try { @file_put_contents(__DIR__.'/../logs/review_justifs_mail.log',date('Y-m-d H:i:s')."\t$ref\t$phase\t$msg\n",FILE_APPEND); } catch(Throwable $e){} }
// Vérifier/ajouter colonne observation_support si absente
$hasObsCol=false;
try {
  $colObs=$gc_pdo->query("SHOW COLUMNS FROM compagnies_table LIKE 'observation_support'")->fetch();
  if($colObs){ $hasObsCol=true; } else { $gc_pdo->exec("ALTER TABLE compagnies_table ADD observation_support TEXT NULL AFTER $expCol"); $hasObsCol=true; }
} catch(Throwable $e) { /* silent */ }

// Déterminer colonne expiration (expiartion_date vs expiration_date)
$expCol = 'expiration_date';
try{ $c=$gc_pdo->query("SHOW COLUMNS FROM compagnies_table LIKE 'expiartion_date'")->fetch(); if($c){ $expCol='expiartion_date'; } }catch(Throwable $e){}

if($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['action'])){
  $redirectUrl = $_SERVER['PHP_SELF'].'?ref='.urlencode($ref);
  if($_POST['action']==='valider'){
    try{
    // Lire date actuelle
    $st=$gc_pdo->prepare("SELECT $expCol FROM compagnies_table WHERE compagnie_ref=? LIMIT 1");
    $st->execute([$ref]);
    $cur = $st->fetchColumn();
    $baseDate = ($cur && strtotime($cur) > time()) ? new DateTime($cur) : new DateTime();
    $baseDate->modify('+365 days');
    $newDate = $baseDate->format('Y-m-d');
    $up=$gc_pdo->prepare("UPDATE compagnies_table SET $expCol=? WHERE compagnie_ref=? LIMIT 1");
    $up->execute([$newDate,$ref]);
    // Activer notification validation (validation_note=1) si colonne existe ou la créer
    try {
      $colVal = $gc_pdo->query("SHOW COLUMNS FROM compagnies_table LIKE 'validation_note'")->fetch();
      if(!$colVal){
        $gc_pdo->exec("ALTER TABLE compagnies_table ADD validation_note TINYINT(1) NOT NULL DEFAULT 0 AFTER observation_support");
      }
      $gc_pdo->prepare("UPDATE compagnies_table SET validation_note=1 WHERE compagnie_ref=? LIMIT 1")->execute([$ref]);
    } catch(Throwable $eVal){ /* silent */ }
    // Effacer éventuel message de refus précédent
    if(isset($hasObsCol) && $hasObsCol){
      try { $gc_pdo->prepare("UPDATE compagnies_table SET observation_support=NULL WHERE compagnie_ref=? LIMIT 1")->execute([$ref]); } catch(Throwable $eClr) { /* silent */ }
    }
    // Vider dossier
    if(is_dir($dir)){
      foreach(scandir($dir) as $f){ if($f==='.'||$f==='..') continue; $p=$dir.'/'.$f; if(is_file($p)) @unlink($p); }
    }
    @rmdir($dir); // remove empty dir
    // Notification email validation (support + super admins directs)
    try {
      // Table email_settings_table ne contient qu'une seule ligne (config globale) => id=1
      $stCfg=$gc_pdo->query('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');
      $cfg=$stCfg? $stCfg->fetch(PDO::FETCH_ASSOC):null;
      $superAdmins=[];
      try { $stSA=$gc_pdo->prepare("SELECT user_email FROM users_compagnie WHERE compagnie_ref=? AND (user_role='Super admin' OR user_role IS NULL) LIMIT 20"); $stSA->execute([$ref]); while($r=$stSA->fetch(PDO::FETCH_ASSOC)){ $em=trim($r['user_email']??''); if($em) $superAdmins[$em]=true; } }catch(Throwable $eSA){}
      try { $stSU=$gc_pdo->prepare("SELECT user_email FROM users_table WHERE compagnie_ref=? AND user_role='Super admin' AND status=1"); $stSU->execute([$ref]); while($r=$stSU->fetch(PDO::FETCH_ASSOC)){ $em=trim($r['user_email']??''); if($em) $superAdmins[$em]=true; } }catch(Throwable $eSU){}
      if(isset($pdo) && $pdo instanceof PDO){ try { $stLoc=$pdo->query("SELECT user_email FROM users_compagnie WHERE user_role='Super admin' AND (status=1 OR status IS NULL) LIMIT 10"); while($r=$stLoc->fetch(PDO::FETCH_ASSOC)){ $em=trim($r['user_email']??''); if($em) $superAdmins[$em]=true; } }catch(Throwable $eLoc){} }
      if($cfg && !empty($cfg['active']) && (!empty($cfg['support_email']) || $superAdmins)){
        require_once dirname(__DIR__).'/PHPMailer/src/Exception.php';
        require_once dirname(__DIR__).'/PHPMailer/src/PHPMailer.php';
        require_once dirname(__DIR__).'/PHPMailer/src/SMTP.php';
        $m=new PHPMailer\PHPMailer\PHPMailer(true);
        try {
          $m->isSMTP(); $m->Host=$cfg['smtp_host']; $m->Port=(int)$cfg['smtp_port'];
          if(!empty($cfg['auth_enabled'])){ $m->SMTPAuth=true; $m->Username=$cfg['smtp_username']; $m->Password=$cfg['smtp_password']; }
          $enc=strtolower($cfg['encryption']); if($enc==='ssl') $m->SMTPSecure=PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS; elseif($enc==='tls') $m->SMTPSecure=PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS; else $m->SMTPSecure=false;
          $m->CharSet='UTF-8'; $m->setFrom($cfg['from_email']?:'no-reply@local',$cfg['from_name']?:'Notification');
          if(!empty($cfg['support_email'])) $m->addAddress($cfg['support_email']);
          foreach(array_keys($superAdmins) as $em){ if(strcasecmp($em,$cfg['support_email']??'')!==0) $m->addAddress($em); }
          $agencyName=''; try { $stNm=$gc_pdo->prepare("SELECT compagnie_name FROM compagnies_table WHERE compagnie_ref=? LIMIT 1"); $stNm->execute([$ref]); $rNm=$stNm->fetch(PDO::FETCH_ASSOC); if($rNm && !empty($rNm['compagnie_name'])) $agencyName=$rNm['compagnie_name']; }catch(Throwable $eName){}
          $labelAgence = $agencyName ? htmlspecialchars($agencyName).' (Ref: '.htmlspecialchars($ref).')' : htmlspecialchars($ref);
          $m->Subject='Paiement validé - '.$ref;
          $core="<p style='margin:0 0 12px'>Le paiement pour l'Agence <strong>".$labelAgence."</strong> a été validé.</p><p style='margin:0'>Nouvelle expiration : <strong>".htmlspecialchars(date('d/m/Y',strtotime($newDate)))."</strong></p>";
          $m->isHTML(true);
          $m->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:#16a34a;padding:16px 20px'><h1 style='margin:0;font-size:18px;color:#fff;font-weight:600;'>Paiement Validé</h1></td></tr></thead><tbody><tr><td style='padding:20px'>".$core."</td></tr><tr><td style='background:#f8fafc;padding:14px 20px;text-align:center;font-size:12px;color:#64748b'>Notification automatique • Merci de ne pas répondre</td></tr></tbody></table></div>";
          $m->AltBody='Paiement validé pour '.$ref.' - Nouvelle expiration: '.$newDate;
          $m->send(); rj_log($ref,'VALIDATION','OK dest='.(count($superAdmins)+(empty($cfg['support_email'])?0:1)));
        } catch(Throwable $eSend){ rj_log($ref,'VALIDATION','ERREUR_ENVOI '.$eSend->getMessage()); }
      } else { rj_log($ref,'VALIDATION','CONFIG_ABSENTE'); }
    } catch(Throwable $eCfg){ rj_log($ref,'VALIDATION','ERREUR_CFG '.$eCfg->getMessage()); }
  // Redirect to avoid resubmission
  header('Location: '.$redirectUrl.'&success=1');
  exit;
  }catch(Throwable $e){ $message='Erreur validation: '.$e->getMessage(); $msgType='danger'; }
  } elseif($_POST['action']==='refuser'){
    $obs = trim($_POST['observation_support'] ?? '');
    if($obs===''){ $message='Motif de refus requis.'; $msgType='danger'; }
    else {
      try {
       if($hasObsCol){
         $stU=$gc_pdo->prepare("UPDATE compagnies_table SET observation_support=? WHERE compagnie_ref=? LIMIT 1");
         $stU->execute([$obs,$ref]);
       }
       // Purger fichiers (refusés mais archivage possible plus tard si besoin)
       if(is_dir($dir)){
         foreach(scandir($dir) as $f){ if($f==='.'||$f==='..') continue; $p=$dir.'/'.$f; if(is_file($p)) @unlink($p); }
       }
       @rmdir($dir);
       // Notification email refus (support + super admins directs)
       try {
         // Config globale unique (pas de colonne compagnie_ref)
         $stCfg=$gc_pdo->query('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');
         $cfg=$stCfg? $stCfg->fetch(PDO::FETCH_ASSOC):null;
         $superAdmins=[];
         try { $stSA=$gc_pdo->prepare("SELECT user_email FROM users_compagnie WHERE compagnie_ref=? AND (user_role='Super admin' OR user_role IS NULL) LIMIT 20"); $stSA->execute([$ref]); while($r=$stSA->fetch(PDO::FETCH_ASSOC)){ $em=trim($r['user_email']??''); if($em) $superAdmins[$em]=true; } }catch(Throwable $eSA){}
         try { $stSU=$gc_pdo->prepare("SELECT user_email FROM users_table WHERE compagnie_ref=? AND user_role='Super admin' AND status=1"); $stSU->execute([$ref]); while($r=$stSU->fetch(PDO::FETCH_ASSOC)){ $em=trim($r['user_email']??''); if($em) $superAdmins[$em]=true; } }catch(Throwable $eSU){}
         if(isset($pdo) && $pdo instanceof PDO){ try { $stLoc=$pdo->query("SELECT user_email FROM users_compagnie WHERE user_role='Super admin' AND (status=1 OR status IS NULL) LIMIT 10"); while($r=$stLoc->fetch(PDO::FETCH_ASSOC)){ $em=trim($r['user_email']??''); if($em) $superAdmins[$em]=true; } }catch(Throwable $eLoc){} }
         if($cfg && !empty($cfg['active']) && (!empty($cfg['support_email']) || $superAdmins)){
           require_once dirname(__DIR__).'/PHPMailer/src/Exception.php';
           require_once dirname(__DIR__).'/PHPMailer/src/PHPMailer.php';
           require_once dirname(__DIR__).'/PHPMailer/src/SMTP.php';
           $m=new PHPMailer\PHPMailer\PHPMailer(true);
           try {
             $m->isSMTP(); $m->Host=$cfg['smtp_host']; $m->Port=(int)$cfg['smtp_port'];
             if(!empty($cfg['auth_enabled'])){ $m->SMTPAuth=true; $m->Username=$cfg['smtp_username']; $m->Password=$cfg['smtp_password']; }
             $enc=strtolower($cfg['encryption']); if($enc==='ssl') $m->SMTPSecure=PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS; elseif($enc==='tls') $m->SMTPSecure=PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS; else $m->SMTPSecure=false;
             $m->CharSet='UTF-8'; $m->setFrom($cfg['from_email']?:'no-reply@local',$cfg['from_name']?:'Notification');
             if(!empty($cfg['support_email'])) $m->addAddress($cfg['support_email']);
             foreach(array_keys($superAdmins) as $em){ if(strcasecmp($em,$cfg['support_email']??'')!==0) $m->addAddress($em); }
             $agencyName=''; try { $stNm=$gc_pdo->prepare("SELECT compagnie_name FROM compagnies_table WHERE compagnie_ref=? LIMIT 1"); $stNm->execute([$ref]); $rNm=$stNm->fetch(PDO::FETCH_ASSOC); if($rNm && !empty($rNm['compagnie_name'])) $agencyName=$rNm['compagnie_name']; }catch(Throwable $eName){}
             $labelAgence = $agencyName ? htmlspecialchars($agencyName).' (Ref: '.htmlspecialchars($ref).')' : htmlspecialchars($ref);
             $m->Subject='Paiement refusé - '.$ref;
             $coreR="<p style='margin:0 0 12px'>Le paiement pour l'Agence <strong>".$labelAgence."</strong> a été <strong style='color:#dc2626'>refusé</strong>.</p><p style='margin:0 0 12px'>Motif :</p><div style='background:#fef2f2;border:1px solid #fecaca;padding:12px;border-radius:6px;color:#991b1b;font-size:13px;line-height:1.4'>".nl2br(htmlspecialchars($obs))."</div><p style='margin:16px 0 0'>Merci de soumettre un justificatif corrigé.</p>";
             $m->isHTML(true);
             $m->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:#dc2626;padding:16px 20px'><h1 style='margin:0;font-size:18px;color:#fff;font-weight:600;'>Paiement Refusé</h1></td></tr></thead><tbody><tr><td style='padding:20px'>".$coreR."</td></tr><tr><td style='background:#fef2f2;padding:14px 20px;text-align:center;font-size:12px;color:#991b1b'>Notification automatique • Merci de ne pas répondre</td></tr></tbody></table></div>";
             $m->AltBody='Paiement refusé pour '.$ref.' Motif: '.$obs;
             $m->send(); rj_log($ref,'REFUS','OK dest='.(count($superAdmins)+(empty($cfg['support_email'])?0:1)));
           } catch(Throwable $eSend){ rj_log($ref,'REFUS','ERREUR_ENVOI '.$eSend->getMessage()); }
         } else { rj_log($ref,'REFUS','CONFIG_ABSENTE'); }
       } catch(Throwable $eCfg){ rj_log($ref,'REFUS','ERREUR_CFG '.$eCfg->getMessage()); }
        // Redirect to avoid resubmission
        header('Location: '.$redirectUrl.'&refused=1');
        exit;
      }catch(Throwable $e){ $message='Erreur refus: '.$e->getMessage(); $msgType='danger'; }
    }
  }
}
?><!DOCTYPE html><html lang="fr"><head><meta charset="utf-8"><title>Justificatifs - <?php echo htmlspecialchars($ref); ?></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>.file-box{border:1px solid #e3e6f0;padding:8px;border-radius:4px;margin-bottom:8px}</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"><h4 class="mb-0"><i class="fas fa-file-upload text-secondary"></i> Justificatifs (<?php echo htmlspecialchars($ref); ?>)</h4><a href="companies.php" class="btn btn-sm btn-secondary"><i class="fas fa-arrow-left"></i> Retour</a></div>
  <?php if($message): ?><div class="alert alert-<?php echo htmlspecialchars($msgType); ?> py-2"><?php echo htmlspecialchars($message); ?></div><?php endif; ?>
  <div class="row">
    <div class="col-lg-8">
      <div class="card shadow-sm mb-3"><div class="card-header py-2"><strong>Fichiers Reçus</strong></div><div class="card-body p-2">
        <?php if(!$files): ?><p class="text-muted small mb-0">Aucun fichier.</p><?php else: ?>
          <ul class="list-unstyled mb-0 small">
            <?php foreach($files as $f): $ext=strtolower(pathinfo($f['name'],PATHINFO_EXTENSION)); ?>
              <li class="file-box">
                <i class="fas fa-file-<?php echo ($ext==='pdf'?'pdf':'image'); ?> text-secondary"></i>
                <a href="<?='files/uploads/'.rawurlencode($cleanRef).'/'.rawurlencode($f['name']);?>" target="_blank"><?php echo htmlspecialchars($f['name']); ?></a>
                <span class="text-muted">(<?php echo number_format($f['size']/1024,1,'.',''); ?> KB - <?php echo date('d/m/Y H:i',$f['mtime']); ?>)</span>
              </li>
            <?php endforeach; ?>
          </ul>
        <?php endif; ?>
      </div></div>
    </div>
    <div class="col-lg-4">
      <div class="card shadow-sm"><div class="card-header py-2"><strong>Action</strong></div><div class="card-body">
        <p class="small">Valider le paiement ajoute 365 jours à l'expiration courante (ou à aujourd'hui si déjà expiré), puis purge les fichiers.</p>
        <div class="mb-3">
          <button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#modalValider" <?php if(!$files) echo 'disabled'; ?>>
            <i class="fas fa-check"></i> Valider paiement
          </button>
          <button type="button" class="btn btn-danger btn-sm ml-2" data-toggle="modal" data-target="#modalRefuser" <?php if(!$files) echo 'disabled'; ?>>
            <i class="fas fa-times"></i> Refuser paiement
          </button>
        </div>
        <p class="small mb-0 text-muted">Utilisez ces actions pour traiter les justificatifs envoyés par l'agence.</p>
      </div></div>
    </div>
  </div>
</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></body></html>
<!-- Modal Validation -->
<div class="modal fade" id="modalValider" tabindex="-1" role="dialog" aria-labelledby="modalValiderLabel" 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" id="modalValiderLabel"><i class="fas fa-check"></i> Confirmation Validation</h6>
        <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      </div>
      <form method="post">
        <div class="modal-body">
          <p class="mb-2">Confirmer la validation de ce paiement ?</p>
          <p class="small text-muted mb-0">Cela ajoutera 365 jours à la date d'expiration actuelle (ou à partir d'aujourd'hui si expiré) puis supprimera les fichiers envoyés.</p>
          <input type="hidden" name="action" value="valider">
        </div>
        <div class="modal-footer py-2">
          <button type="button" class="btn btn-light btn-sm" data-dismiss="modal">Annuler</button>
            <button type="submit" class="btn btn-success btn-sm"><i class="fas fa-check"></i> Confirmer</button>
        </div>
      </form>
    </div>
  </div>
</div>
<!-- Modal Refus -->
<div class="modal fade" id="modalRefuser" tabindex="-1" role="dialog" aria-labelledby="modalRefuserLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header bg-danger text-white py-2">
        <h6 class="modal-title" id="modalRefuserLabel"><i class="fas fa-times"></i> Refuser le Paiement</h6>
        <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      </div>
      <form method="post" id="formRefuser">
        <div class="modal-body">
          <div class="form-group mb-2">
            <label class="small font-weight-bold">Motif de refus <span class="text-danger">*</span></label>
            <textarea name="observation_support" class="form-control form-control-sm" rows="4" required placeholder="Détaillez la raison du refus (obligatoire)"></textarea>
          </div>
          <p class="small text-muted mb-0">Les fichiers seront supprimés et l'agence verra ce motif.</p>
          <input type="hidden" name="action" value="refuser">
        </div>
        <div class="modal-footer py-2">
          <button type="button" class="btn btn-light btn-sm" data-dismiss="modal">Annuler</button>
          <button type="submit" class="btn btn-danger btn-sm"><i class="fas fa-times"></i> Confirmer Refus</button>
        </div>
      </form>
    </div>
  </div>
</div>
<script>
// Auto-focus textarea in refusal modal
$('#modalRefuser').on('shown.bs.modal', function(){
  $(this).find('textarea[name="observation_support"]').trigger('focus');
});
</script>
