<?php
@session_start();
// Page configuration FTP (centrale)
// Accès restreint admin
require_once __DIR__.'/config/connexion.php'; // $gc_pdo
if(!isset($_SESSION['user_role']) || !in_array($_SESSION['user_role'], ['Super admin','admin'])){
  http_response_code(403); echo 'Accès refusé'; exit;
}
function h($s){return htmlspecialchars($s??'',ENT_QUOTES,'UTF-8');}
// CSRF token
if(empty($_SESSION['csrf_ftp_cfg'])){ $_SESSION['csrf_ftp_cfg']=bin2hex(random_bytes(16)); }
$csrf_token=$_SESSION['csrf_ftp_cfg'];
$msg=''; $msgType=''; $existing=null;
// Création table si absente
if($gc_pdo instanceof PDO){
  try{
    $gc_pdo->exec("CREATE TABLE IF NOT EXISTS ftp_settings_table (\n      id INT PRIMARY KEY,\n      ftp_host VARCHAR(255) NOT NULL,\n      ftp_port INT NOT NULL DEFAULT 21,\n      ftp_username VARCHAR(255) NULL,\n      ftp_password VARCHAR(255) NULL,\n      ftp_base_dir VARCHAR(255) NULL,\n      passive TINYINT(1) NOT NULL DEFAULT 1,\n      ssl_enabled TINYINT(1) NOT NULL DEFAULT 0,\n      active TINYINT(1) NOT NULL DEFAULT 1,\n      last_test_at DATETIME NULL,\n      last_test_status TINYINT(1) NULL,\n      last_error TEXT NULL,\n      created_at DATETIME NOT NULL,\n      updated_at DATETIME NOT NULL\n    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
  }catch(Throwable $e){ $msg='Erreur création table: '.$e->getMessage(); $msgType='danger'; }
  try{ $st=$gc_pdo->query('SELECT * FROM ftp_settings_table WHERE id=1 LIMIT 1'); $existing=$st->fetch(PDO::FETCH_ASSOC) ?: null; }catch(Throwable $e){ }
}
// Actions POST
if($_SERVER['REQUEST_METHOD']==='POST'){
  $action=$_POST['action'] ?? 'save';
  if(!hash_equals($csrf_token, $_POST['csrf_token'] ?? '')){ $msg='Token invalide'; $msgType='danger'; }
  else if($action==='test'){
    $host=trim($_POST['ftp_host'] ?? '');
    $port=(int)($_POST['ftp_port'] ?? 21);
    $user=trim($_POST['ftp_username'] ?? '');
    $pass=trim($_POST['ftp_password'] ?? '');
    $base=trim($_POST['ftp_base_dir'] ?? '');
    $passive=isset($_POST['passive'])?1:0;
    $ssl=isset($_POST['ssl_enabled'])?1:0;
    // Si des champs sont laissés vides lors d'un test, réutiliser ceux déjà enregistrés
    if($existing){
      if($user==='') $user = trim($existing['ftp_username'] ?? '');
      if($pass==='') $pass = trim($existing['ftp_password'] ?? '');
      if($base==='') $base = trim($existing['ftp_base_dir'] ?? '');
      if(!isset($_POST['passive'])) $passive = (int)($existing['passive'] ?? 1);
      if(!isset($_POST['ssl_enabled'])) $ssl = (int)($existing['ssl_enabled'] ?? 0);
    }
    if($port<=0) $port=21;
    if($host===''){ $msg='Hôte requis pour test.'; $msgType='danger'; }
    else {
      $ok=false; $err=''; $conn=false; $start=microtime(true);
      try{
        if($ssl && function_exists('ftp_ssl_connect')){ $conn=@ftp_ssl_connect($host,$port,8); if(!$conn) $err='ftp_ssl_connect échoué'; }
        if(!$conn){ $conn=@ftp_connect($host,$port,8); if(!$conn) $err='ftp_connect échoué'; }
        if($conn){
          if($user!=='' || $pass!==''){
            if(!@ftp_login($conn,$user,$pass)){
              $err='Authentification échouée';
            }
            else { $ok=true; }
          } else { // login anonyme
            if(!@ftp_login($conn,'anonymous','anonymous@domain.tld')){ $err='Login anonyme échoué'; } else { $ok=true; }
          }
          if($ok){
            if($passive){ @ftp_pasv($conn,true); }
            if($base!==''){
              if(!@ftp_chdir($conn,$base)){ $ok=false; $err='Base dir inaccessible'; }
            }
          }
          @ftp_close($conn);
        }
      }catch(Throwable $e){ $err=$e->getMessage(); }
      if($ok){ $msg='Test FTP OK en '.round((microtime(true)-$start)*1000,1).' ms'; $msgType='success'; }
      else { $msg='Test FTP ÉCHEC: '.$err.' (utilisateur='.($user!==''?h($user):'anonyme').')'; $msgType='danger'; }
      // Sauvegarder résultat test minimal si config existe
  try{ $gc_pdo->prepare('UPDATE ftp_settings_table SET last_test_at=NOW(), last_test_status=?, last_error=?, updated_at=updated_at WHERE id=1')->execute([$ok?1:0,$ok?null:$err]); }catch(Throwable $e){ }
    }
  } else { // save
    $ftp_host=trim($_POST['ftp_host'] ?? '');
    $ftp_port=(int)($_POST['ftp_port'] ?? 21);
    $ftp_username=trim($_POST['ftp_username'] ?? '');
    $ftp_password=trim($_POST['ftp_password'] ?? '');
    $ftp_base_dir=trim($_POST['ftp_base_dir'] ?? '');
    $passive=isset($_POST['passive'])?1:0;
    $ssl=isset($_POST['ssl_enabled'])?1:0;
    $active=isset($_POST['active'])?1:0;
    if($ftp_host===''){ $msg='Hôte FTP requis.'; $msgType='danger'; }
    else {
      try{
        if($existing){
          if($ftp_password==='') $ftp_password=$existing['ftp_password'];
          $gc_pdo->prepare('UPDATE ftp_settings_table SET ftp_host=?,ftp_port=?,ftp_username=?,ftp_password=?,ftp_base_dir=?,passive=?,ssl_enabled=?,active=?,updated_at=NOW() WHERE id=1')->execute([$ftp_host,$ftp_port,$ftp_username,$ftp_password,$ftp_base_dir,$passive,$ssl,$active]);
          $msg='Configuration mise à jour.'; $msgType='success';
        } else {
          $gc_pdo->prepare('INSERT INTO ftp_settings_table (id,ftp_host,ftp_port,ftp_username,ftp_password,ftp_base_dir,passive,ssl_enabled,active,created_at,updated_at) VALUES (1,?,?,?,?,?,?,?,?,NOW(),NOW())')->execute([$ftp_host,$ftp_port,$ftp_username,$ftp_password,$ftp_base_dir,$passive,$ssl,$active]);
          $msg='Configuration enregistrée.'; $msgType='success';
        }
        $st=$gc_pdo->query('SELECT * FROM ftp_settings_table WHERE id=1 LIMIT 1');
        $existing=$st->fetch(PDO::FETCH_ASSOC) ?: null;
        // Création du dossier de base sur le FTP si nécessaire
        if($ftp_base_dir!==''){
          $baseTrim = trim($ftp_base_dir, "/ ");
          if($baseTrim!==''){
            $createdInfo='';
            try{
              $conn=false; if($ssl && function_exists('ftp_ssl_connect')){ $conn=@ftp_ssl_connect($ftp_host,$ftp_port,8); }
              if(!$conn){ $conn=@ftp_connect($ftp_host,$ftp_port,8); }
              if($conn && (@ftp_login($conn,$ftp_username,$ftp_password) || @ftp_login($conn,'anonymous','anonymous@domain.tld'))){
                if($passive) @ftp_pasv($conn,true);
                // Tester existence
                if(!@ftp_chdir($conn,$baseTrim)){
                  // Création récursive
                  $parts = preg_split('~/+~',$baseTrim,-1,PREG_SPLIT_NO_EMPTY);
                  $pathAcc=''; $allOk=true; $made=0;
                  foreach($parts as $p){
                    $pathAcc .= ($pathAcc?'/':'').$p;
                    if(!@ftp_chdir($conn,$pathAcc)){
                      if(@ftp_mkdir($conn,$pathAcc)){
                        $made++; // mkdir OK
                      } else {
                        $allOk=false; $createdInfo='création échouée sur "'.$pathAcc.'"'; break;
                      }
                    }
                  }
                  // Vérifier final
                  if($allOk && @ftp_chdir($conn,$baseTrim)){
                    if($made>0) $createdInfo = 'dossier créé ('+$made+' niveau'+($made>1?'x':'')+')';
                    else $createdInfo = 'dossier prêt';
                  } elseif($createdInfo==='') { $createdInfo='impossible de valider le dossier'; }
                } else {
                  $createdInfo='dossier existant';
                }
                @ftp_close($conn);
              } else {
                if($conn) @ftp_close($conn);
                $createdInfo='connexion/identification FTP impossible';
              }
            }catch(Throwable $e){ $createdInfo='erreur: '.$e->getMessage(); }
            if($createdInfo!=='') $msg .= ' (Base dir: '.$createdInfo.')';
          }
        }
      }catch(Throwable $e){ $msg='Erreur enregistrement: '.$e->getMessage(); $msgType='danger'; }
    }
  }
}
$val=function($k,$d='') use($existing){ return h($existing[$k] ?? $d); };
$checked=function($k) use($existing){ return !empty($existing[$k])?'checked':''; };
?><!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<title>Configuration FTP</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-ftp{border-left:4px solid #4e73df;} .form-control[readonly]{background:#f8f9fc;}</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-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800"><i class="fas fa-file-upload text-primary"></i> FTP</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-10 col-xl-8 mb-4">
          <div class="card shadow card-ftp">
            <div class="card-header py-2"><strong>Configuration FTP (Globale)</strong></div>
            <div class="card-body">
              <?php if($msg): ?><div class="alert alert-<?=$msgType?> py-2"><?=h($msg)?></div><?php endif; ?>
              <form method="post" class="mb-3" autocomplete="off">
                <input type="hidden" name="csrf_token" value="<?=h($csrf_token)?>">
                <div class="form-row">
                  <div class="form-group col-md-6">
                    <label>Hôte FTP *</label>
                    <input type="text" name="ftp_host" class="form-control form-control-sm" required value="<?=$val('ftp_host')?>">
                  </div>
                  <div class="form-group col-md-3">
                    <label>Port *</label>
                    <input type="number" name="ftp_port" class="form-control form-control-sm" required value="<?=$val('ftp_port',21)?>">
                  </div>
                  <div class="form-group col-md-3">
                    <label>Dossier base</label>
                    <input type="text" name="ftp_base_dir" class="form-control form-control-sm" value="<?=$val('ftp_base_dir','backups_compagnies')?>" placeholder="ex: backups_compagnies">
                  </div>
                </div>
                <div class="form-row">
                  <div class="form-group col-md-6">
                    <label>Utilisateur</label>
                    <input type="text" name="ftp_username" class="form-control form-control-sm" value="<?=$val('ftp_username')?>">
                  </div>
                  <div class="form-group col-md-6">
                    <label>Mot de passe <?=$existing?'<small class=\"text-muted\">(laisser vide)</small>':'';?></label>
                    <input type="password" name="ftp_password" class="form-control form-control-sm" value="">
                  </div>
                </div>
                <div class="form-row">
                  <div class="form-group col-md-2">
                    <div class="form-check mt-4">
                      <input class="form-check-input" type="checkbox" name="passive" id="passive" <?=$checked('passive')?>>
                      <label class="form-check-label" for="passive">Passif</label>
                    </div>
                  </div>
                  <div class="form-group col-md-2">
                    <div class="form-check mt-4">
                      <input class="form-check-input" type="checkbox" name="ssl_enabled" id="ssl_enabled" <?=$checked('ssl_enabled')?>>
                      <label class="form-check-label" for="ssl_enabled">SSL</label>
                    </div>
                  </div>
                  <div class="form-group col-md-2">
                    <div class="form-check mt-4">
                      <input class="form-check-input" type="checkbox" name="active" id="active" <?=$checked('active')?>>
                      <label class="form-check-label" for="active">Activé</label>
                    </div>
                  </div>
                </div>
                <div class="mt-2 d-flex align-items-center gap-2">
                  <button class="btn btn-primary btn-sm"><i class="fas fa-save"></i> Enregistrer</button>
                  <button name="action" value="test" class="btn btn-outline-info btn-sm"><i class="fas fa-vial"></i> Tester connexion</button>
                </div>
              </form>
              <?php if($existing): ?>
                <div class="small text-muted">
                  Dernier test: <?= $existing['last_test_at']? h($existing['last_test_at']).' ('.($existing['last_test_status']?'OK':'ECHEC').')' : 'jamais'; ?>
                  <?php if(!empty($existing['last_error'])): ?><br>Dernière erreur: <code><?=h($existing['last_error'])?></code><?php endif; ?>
                </div>
              <?php endif; ?>
              <hr>
              <p class="small text-muted mb-0">Les identifiants FTP sont stockés en clair. Prévoir un chiffrement en production.</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; <?=date('Y')?> Backups</div></div></footer>
</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>
</body>
</html>
