<?php
session_start();
require_once __DIR__.'/config/connexion.php';
require_once __DIR__.'/config/auth.php';
// Protection: login obligatoire
gc_require_login();

// Vérifier rôle si besoin (seulement admin peut créer) - décommentez si vous voulez restreindre
$me = gc_current_user($gc_pdo);
// if($me && $me['user_role']!=='admin'){ header('Location: index.php'); exit; }

$errors=[]; $data=[
 'first_name'=>'','last_name'=>'','phone_num'=>'','user_email'=>'','user_role'=>'user','status'=>'active'
];

if($_SERVER['REQUEST_METHOD']==='POST'){
  foreach($data as $k=>$_) if(isset($_POST[$k])) $data[$k]=trim($_POST[$k]);
  $pass = $_POST['user_pass'] ?? '';
  $confirm = $_POST['user_pass_confirm'] ?? '';
  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';
  if(!filter_var($data['user_email'], FILTER_VALIDATE_EMAIL)) $errors['user_email']='Email invalide';
  if(strlen($pass)<6) $errors['user_pass']='Min 6 caractères';
  if($pass!==$confirm) $errors['user_pass_confirm']='Confirmation différente';
  if(!in_array($data['user_role'],['admin','user'],true)) $data['user_role']='user';
  if(!in_array($data['status'],['active','disabled'],true)) $data['status']='active';

  if(!$errors){
    $stmt=$gc_pdo->prepare('SELECT COUNT(*) FROM users_table WHERE user_email=:em OR phone_num=:ph');
    $stmt->execute([':em'=>$data['user_email'],':ph'=>$data['phone_num']]);
    if($stmt->fetchColumn()>0){ $errors['exists']='Email ou téléphone déjà utilisé.'; }
  }
  if(!$errors){
    $hash=password_hash($pass, PASSWORD_BCRYPT);
    $stmt=$gc_pdo->prepare('INSERT INTO users_table(first_name,last_name,phone_num,user_email,user_pass,user_role,status,created_at) VALUES(:fn,:ln,:ph,:em,:pw,:role,:st,NOW())');
    $stmt->execute([
      ':fn'=>$data['first_name'],':ln'=>$data['last_name'],':ph'=>$data['phone_num'],':em'=>$data['user_email'],':pw'=>$hash,':role'=>$data['user_role'],':st'=>$data['status']
    ]);
    $_SESSION['gc_flash_success']='Utilisateur ajouté.';
    header('Location: index.php');
    exit;
  }
}
?><!DOCTYPE html><html lang="fr"><head>
<meta charset="utf-8"><title>Ajouter Utilisateur - Backups</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">
</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" style="max-width:960px;">
        <div class="d-flex justify-content-between align-items-center mb-3">
          <h4 class="mb-0"><i class="fas fa-user-plus text-primary"></i> Nouvel Utilisateur</h4>
          <a href="index.php" class="btn btn-sm btn-secondary"><i class="fas fa-arrow-left"></i> Retour</a>
        </div>
        <?php if($errors): ?><div class="alert alert-danger py-2 mb-3"><strong>Erreurs:</strong> <?php echo implode(' | ', array_map('htmlspecialchars',$errors)); ?></div><?php endif; ?>
        <div class="card shadow-sm mb-4"><div class="card-body">
          <form method="post" novalidate>
            <div class="form-row">
              <div class="form-group col-md-6"><label>Prénom</label><input name="first_name" class="form-control" value="<?php echo htmlspecialchars($data['first_name']); ?>"></div>
              <div class="form-group col-md-6"><label>Nom</label><input name="last_name" class="form-control" value="<?php echo htmlspecialchars($data['last_name']); ?>"></div>
            </div>
            <div class="form-row">
              <div class="form-group col-md-6"><label>Téléphone</label><input name="phone_num" class="form-control" value="<?php echo htmlspecialchars($data['phone_num']); ?>"></div>
              <div class="form-group col-md-6"><label>Email</label><input name="user_email" type="email" class="form-control" value="<?php echo htmlspecialchars($data['user_email']); ?>"></div>
            </div>
            <div class="form-row">
              <div class="form-group col-md-6"><label>Mot de passe</label><input name="user_pass" type="password" class="form-control"></div>
              <div class="form-group col-md-6"><label>Confirmer Mot de passe</label><input name="user_pass_confirm" type="password" class="form-control"></div>
            </div>
            <div class="form-row">
              <div class="form-group col-md-4"><label>Rôle</label><select name="user_role" class="form-control"><option value="user" <?php if($data['user_role']==='user') echo 'selected'; ?>>Utilisateur</option><option value="admin" <?php if($data['user_role']==='admin') echo 'selected'; ?>>Admin</option></select></div>
              <div class="form-group col-md-4"><label>Statut</label><select name="status" class="form-control"><option value="active" <?php if($data['status']==='active') echo 'selected'; ?>>Actif</option><option value="disabled" <?php if($data['status']==='disabled') echo 'selected'; ?>>Désactivé</option></select></div>
            </div>
            <button class="btn btn-primary"><i class="fas fa-save"></i> Enregistrer</button>
          </form>
        </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>
