<?php
// Page propre d'ajout utilisateur (remplacement des versions dupliquées précédentes)
@session_start();
require_once __DIR__.'/config/connexion.php'; // $pdo compagnie (doit être disponible après login multi-agence)

// Vérification login de base
if (empty($_SESSION['user_email'])) { header('Location: login.php'); exit; }
// Rôle courant
$rawRole = trim($_SESSION['user_role'] ?? '');
$roleLower = strtolower($rawRole);
// Autoriser Super admin / admin uniquement
if(!in_array($roleLower,['super admin','admin'],true)) { header('Location: access_denied.php'); exit; }

// Charger rôles depuis roles_table
$allRoles = [];
try {
  if(isset($conn) && $conn instanceof mysqli){
    if($rs = $conn->query("SELECT role_name FROM roles_table ORDER BY role_name")){
      while($r=$rs->fetch_assoc()){ $allRoles[] = $r['role_name']; }
      $rs->close();
    }
  } elseif(isset($pdo)) {
    $stR=$pdo->query("SELECT role_name FROM roles_table ORDER BY role_name");
    $allRoles = $stR->fetchAll(PDO::FETCH_COLUMN);
  }
} catch(Throwable $e){ /* silencieux */ }
if(!$allRoles){ $allRoles=['Super admin','admin','user']; }
// Déterminer rôles assignables suivant le rôle courant
if($roleLower==='super admin'){
  $assignableRoles = array_values(array_filter($allRoles,function($r){ return strtolower($r)!=='super admin'; }));
} elseif($roleLower==='admin') {
  $assignableRoles = array_values(array_filter($allRoles,function($r){ return strtolower($r)==='user' || strtolower($r)==='admin'; }));
  // Un admin ne doit pas créer d'admin supérieur? garder seulement 'user'
  $assignableRoles = array_values(array_filter($assignableRoles,function($r){ return strtolower($r)==='user'; }));
} else {
  $assignableRoles = ['user'];
}

// Charger liste d'utilisateurs existants pour éventuelle copie de permissions
$existingUsers=[];
try {
  if(isset($pdo)){
    $stU=$pdo->query("SELECT user_email, CONCAT(COALESCE(first_name,''),' ',COALESCE(last_name,'')) AS fullname FROM users_table ORDER BY first_name, last_name");
    $existingUsers=$stU->fetchAll(PDO::FETCH_ASSOC);
  } elseif(isset($conn) && $conn instanceof mysqli){
    if($rsU=$conn->query("SELECT user_email, CONCAT(IFNULL(first_name,''),' ',IFNULL(last_name,'')) AS fullname FROM users_table ORDER BY first_name, last_name")){
      while($rU=$rsU->fetch_assoc()){ $existingUsers[]=$rU; }
      $rsU->close();
    }
  }
} catch(Throwable $e){ /* silencieux */ }

$errors=[]; $success=false; $copiedPerms=false; $copyFrom='';
// status: 1=active, 0=disabled
$data=[
  'first_name'=>'',
  'last_name'=>'',
  'phone_num'=>'',
  'user_email'=>'',
  'user_role'=>'',
  'status'=>1
];

if($_SERVER['REQUEST_METHOD']==='POST'){
  foreach($data as $k=>$v){
    if(isset($_POST[$k])) {
      // Pour le champ user_role, ne pas trim (pour éviter de supprimer des espaces valides dans le nom du rôle)
      $data[$k]=($k==='user_role') ? $_POST[$k] : trim($_POST[$k]);
    }
  }
  $pass    = $_POST['user_pass'] ?? '';
  $confirm = $_POST['confirm_pass'] ?? '';
  $copyFrom = isset($_POST['copy_from_user']) ? trim($_POST['copy_from_user']) : '';
  // Sécuriser valeurs
  if(!in_array($data['user_role'],$allRoles,true)) $data['user_role']='';
  if(!in_array((string)$data['status'],['1','0'],true)) $data['status']=1;

  // Validation basique
  if($data['first_name']==='') $errors['first_name']='Prénom requis';
  if($data['last_name']==='') $errors['last_name']='Nom requis';
  if($data['phone_num']==='') $errors['phone_num']='Téléphone requis';
  elseif(!preg_match('/^[0-9]+$/',$data['phone_num'])) $errors['phone_num']='Chiffres uniquement';
  if(!filter_var($data['user_email'], FILTER_VALIDATE_EMAIL)) $errors['user_email']='Email invalide';
  if($data['user_role']==='') $errors['user_role']='Rôle requis';
  if(strlen($pass)<6) $errors['user_pass']='Mot de passe min 6 caractères';
  if($pass !== $confirm) $errors['confirm_pass']='Confirmation différente';

  if(!$errors){
    try {
      // Unicité email / téléphone
      $st=$pdo->prepare('SELECT COUNT(*) FROM users_table WHERE user_email=? OR phone_num=?');
      $st->execute([$data['user_email'],$data['phone_num']]);
      if($st->fetchColumn()>0){ $errors['exists']='Email ou téléphone déjà utilisé.'; }
      if(!$errors){
  $hash=password_hash($pass, PASSWORD_BCRYPT);
  $ins=$pdo->prepare('INSERT INTO users_table(first_name,last_name,phone_num,user_email,user_pass,user_role,status) VALUES(?,?,?,?,?,?,?)');
  $ins->execute([$data['first_name'],$data['last_name'],$data['phone_num'],$data['user_email'],$hash,$data['user_role'], (int)$data['status']]);
  // Tenter de marquer must_change_password=1 si la colonne existe
  try { $pdo->exec("UPDATE users_table SET must_change_password=1 WHERE user_email=".$pdo->quote($data['user_email'])." LIMIT 1"); } catch(Throwable $ie) { }

  // Si une source de permissions est sélectionnée, copier les permissions (facultatif)
  if($copyFrom && filter_var($copyFrom, FILTER_VALIDATE_EMAIL) && strcasecmp($copyFrom,$data['user_email'])!==0){
    try {
      // Supprimer éventuelles permissions résiduelles (devrait être vide pour un nouvel utilisateur)
      $pdo->prepare('DELETE FROM user_permissions WHERE user_email=?')->execute([$data['user_email']]);
      // Copier les permissions à partir de la source
      $stCopy=$pdo->prepare('INSERT INTO user_permissions(user_email,page) SELECT ?, page FROM user_permissions WHERE user_email=?');
      $stCopy->execute([$data['user_email'],$copyFrom]);
      $copiedPerms = ($stCopy->rowCount()>0);
    } catch(Throwable $eCopy){ /* ignorer en silence */ }
  }

  // Insertion aussi dans la base centrale (users_compagnie) avec la compagnie_ref (multi-agence)
  $compagnieRef = $_SESSION['compagnie_ref'] ?? null;
  if($compagnieRef){
    try {
      // Charger connexion centrale si pas déjà disponible
      if(!isset($gc_pdo)) { @require_once __DIR__.'/gestion_compagnies/config/connexion.php'; }
      if(isset($gc_pdo)){
        // Vérifier existence (email ou téléphone) pour cette compagnie
        $ck = $gc_pdo->prepare('SELECT COUNT(*) FROM users_compagnie WHERE (user_email=? OR phone_num=?) AND compagnie_ref=?');
        $ck->execute([$data['user_email'],$data['phone_num'],$compagnieRef]);
        if($ck->fetchColumn()==0){
          $insGc = $gc_pdo->prepare('INSERT INTO users_compagnie(compagnie_ref,first_name,last_name,phone_num,user_email,user_pass) VALUES(?,?,?,?,?,?)');
          $insGc->execute([$compagnieRef,$data['first_name'],$data['last_name'],$data['phone_num'],$data['user_email'],$hash]);
          try { $gc_pdo->exec("UPDATE users_compagnie SET must_change_password=1 WHERE compagnie_ref=".$gc_pdo->quote($compagnieRef)." AND user_email=".$gc_pdo->quote($data['user_email'])." LIMIT 1"); } catch(Throwable $ie2) { }
        }
        // Mise à jour des colonnes optionnelles (user_role, status) si elles existent
        try {
          $cols = [];
          $rsCols = $gc_pdo->query("SHOW COLUMNS FROM users_compagnie");
          while($c=$rsCols->fetch(PDO::FETCH_ASSOC)){ $cols[$c['Field']]=true; }
          $setParts=[]; $params=[];
          if(isset($cols['user_role'])){ $setParts[]='user_role=?'; $params[]=$data['user_role']; }
          if(isset($cols['status'])){ $setParts[]='status=?'; $params[]=(int)$data['status']; }
          if($setParts){
            $params[]=$compagnieRef; $params[]=$data['user_email'];
            $sqlUp="UPDATE users_compagnie SET ".implode(',', $setParts)." WHERE compagnie_ref=? AND user_email=? LIMIT 1";
            $upStmt=$gc_pdo->prepare($sqlUp); $upStmt->execute($params);
          }
        } catch(Throwable $eSync){ /* silencieux */ }
      }
    } catch(Throwable $ie){ /* Non bloquant : ignorer si central KO */ }
  }

  $success=true; $data=[ 'first_name'=>'','last_name'=>'','phone_num'=>'','user_email'=>'','user_role'=>'','status'=>1 ]; $copyFrom='';
      }
    } catch(Throwable $e){ $errors['general']='Erreur base: '.$e->getMessage(); }
  }
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="utf-8">
  <title>Ajouter Utilisateur</title>
  <?php include 'includes/head.php'; ?>
  <style>.error{color:#dc3545;font-size:.8rem}</style>
</head>
<body id="page-top">
<div id="wrapper">
  <?php include 'includes/sidebar.php'; ?>
  <div id="content-wrapper" class="d-flex flex-column">
    <div id="content">
      <?php include 'includes/topbar.php'; ?>
      <div class="container-fluid" style="max-width:960px;">
        <h3 class="mb-4"><i class="fas fa-user-plus text-primary"></i> Nouvel utilisateur</h3>
        <?php if(isset($errors['general'])): ?><div class="alert alert-danger py-2 mb-3"><?=htmlspecialchars($errors['general'])?></div><?php endif; ?>
        <?php if(isset($errors['exists'])): ?><div class="alert alert-warning py-2 mb-3"><?=htmlspecialchars($errors['exists'])?></div><?php endif; ?>
        <?php if($success): ?><div class="alert alert-success py-2 mb-3">Utilisateur créé avec succès.<?php if($copiedPerms): ?> Permissions copiées.<?php elseif($copyFrom && !$copiedPerms): ?> Aucune permission copiée (source sans permissions).<?php endif; ?></div><?php endif; ?>
        <div class="card shadow-sm mb-4"><div class="card-body">
          <form method="post" autocomplete="off">
            <div class="form-row">
              <div class="form-group col-md-4"><label>Prénom</label><input name="first_name" class="form-control form-control-sm" value="<?=htmlspecialchars($data['first_name'])?>"><?php if(isset($errors['first_name'])): ?><div class="error"><?=$errors['first_name']?></div><?php endif; ?></div>
              <div class="form-group col-md-4"><label>Nom</label><input name="last_name" class="form-control form-control-sm" value="<?=htmlspecialchars($data['last_name'])?>"><?php if(isset($errors['last_name'])): ?><div class="error"><?=$errors['last_name']?></div><?php endif; ?></div>
              <div class="form-group col-md-4"><label>Téléphone</label><input name="phone_num" class="form-control form-control-sm" value="<?=htmlspecialchars($data['phone_num'])?>"><?php if(isset($errors['phone_num'])): ?><div class="error"><?=$errors['phone_num']?></div><?php endif; ?></div>
            </div>
            <div class="form-row">
              <div class="form-group col-md-4"><label>Email</label><input name="user_email" type="email" class="form-control form-control-sm" value="<?=htmlspecialchars($data['user_email'])?>"><?php if(isset($errors['user_email'])): ?><div class="error"><?=$errors['user_email']?></div><?php endif; ?></div>
              <div class="form-group col-md-4"><label>Rôle</label><select name="user_role" class="form-control form-control-sm">
                <?php if(empty($allRoles)): ?>
                  <option value="" disabled selected>Aucun rôle disponible</option>
                <?php else: ?>
                  <option value="" disabled <?=empty($data['user_role'])?'selected':'';?>>Sélectionner un Rôle</option>
                  <?php foreach($allRoles as $r): $lbl=$r; $rl=strtolower($r); if($rl==='user') $lbl='Utilisateur'; elseif($rl==='admin') $lbl='Admin'; elseif($rl==='super admin') $lbl='Super admin'; ?>
                    <option value="<?=htmlspecialchars($r)?>" <?=$data['user_role']===$r?'selected':'';?>><?=htmlspecialchars($lbl)?></option>
                  <?php endforeach; ?>
                <?php endif; ?>
              </select><?php if(isset($errors['user_role'])): ?><div class="error"><?=$errors['user_role']?></div><?php endif; ?></div>
              <div class="form-group col-md-4"><label>Statut</label><select name="status" class="form-control form-control-sm"><option value="1" <?=((string)$data['status'])==='1'?'selected':'';?>>Actif</option><option value="0" <?=((string)$data['status'])==='0'?'selected':'';?>>Désactivé</option></select></div>
            </div>
            <div class="form-row">
              <div class="form-group col-md-6"><label>Copier les permissions de (facultatif)</label>
                <select name="copy_from_user" class="form-control form-control-sm">
                  <option value="">-- Aucun --</option>
                  <?php foreach($existingUsers as $u): if(strcasecmp($u['user_email'],$data['user_email'])===0) continue; ?>
                    <option value="<?=htmlspecialchars($u['user_email'])?>" <?=$copyFrom===$u['user_email']?'selected':'';?>><?=htmlspecialchars(trim($u['fullname'])?:$u['user_email'])?></option>
                  <?php endforeach; ?>
                </select>
              </div>
            </div>
            <div class="form-row">
              <div class="form-group col-md-4"><label>Mot de passe</label><input name="user_pass" type="password" class="form-control form-control-sm"><?php if(isset($errors['user_pass'])): ?><div class="error"><?=$errors['user_pass']?></div><?php endif; ?></div>
              <div class="form-group col-md-4"><label>Confirmer</label><input name="confirm_pass" type="password" class="form-control form-control-sm"><?php if(isset($errors['confirm_pass'])): ?><div class="error"><?=$errors['confirm_pass']?></div><?php endif; ?></div>
            </div>
            <button class="btn btn-primary btn-sm"><i class="fas fa-save"></i> Enregistrer</button>
            <a href="users_table.php" class="btn btn-secondary btn-sm">Liste</a>
          </form>
        </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')?> Utilisateurs</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>
