<?php
session_start();
@date_default_timezone_set('Africa/Casablanca');
require_once __DIR__.'/config/connexion.php'; // connexion centrale uniquement
require_once __DIR__.'/config/auth.php';
gc_require_login();
$me = gc_current_user($gc_pdo);
$isAdmin = $me && $me['user_role']==='admin';
$messages=[]; $errors=[];

if($isAdmin && $_SERVER['REQUEST_METHOD']==='POST'){
  $action = $_POST['action'] ?? '';
  if($action==='update_user'){
    $id = (int)($_POST['id']??0);
    $fn = trim($_POST['first_name']??'');
    $ln = trim($_POST['last_name']??'');
    $ph = trim($_POST['phone_num']??'');
    $role = $_POST['user_role']??'user';
    $status = $_POST['status']??'active';
    if($fn==='') $errors[]='Prénom requis';
    if($ln==='') $errors[]='Nom requis';
    if(!in_array($role,['admin','user'],true)) $role='user';
    if(!in_array($status,['active','disabled'],true)) $status='active';
    if(!$errors){
      try{
        $st=$gc_pdo->prepare('UPDATE users_table SET first_name=?, last_name=?, phone_num=?, user_role=?, status=? WHERE id=? LIMIT 1');
        $st->execute([$fn,$ln,$ph,$role,$status,$id]);
        $messages[]=['type'=>'success','text'=>'Utilisateur mis à jour'];
      }catch(Throwable $e){ $messages[]=['type'=>'danger','text'=>'Erreur maj: '.$e->getMessage()]; }
    }
  } elseif($action==='reset_pass'){
    $id=(int)($_POST['id']??0);
    $pw= $_POST['new_pass']??''; $pw2=$_POST['new_pass_confirm']??'';
    if(strlen($pw)<6) $errors[]='Mot de passe min 6 car.';
    if($pw!==$pw2) $errors[]='Confirmation différente';
    if(!$errors){
      try{
        $hash=password_hash($pw,PASSWORD_BCRYPT);
        $st=$gc_pdo->prepare('UPDATE users_table SET user_pass=? WHERE id=? LIMIT 1');
        $st->execute([$hash,$id]);
        $messages[]=['type'=>'success','text'=>'Mot de passe réinitialisé'];
      }catch(Throwable $e){ $messages[]=['type'=>'danger','text'=>'Erreur reset: '.$e->getMessage()]; }
    }
  } elseif($action==='delete_user'){
    $id=(int)($_POST['id']??0);
    if($id===$me['id']){ $messages[]=['type'=>'warning','text'=>'Impossible de supprimer votre propre compte']; }
    else {
      try{ $st=$gc_pdo->prepare('DELETE FROM users_table WHERE id=? LIMIT 1'); $st->execute([$id]); $messages[]=['type'=>'success','text'=>'Utilisateur supprimé']; }
      catch(Throwable $e){ $messages[]=['type'=>'danger','text'=>'Erreur suppression: '.$e->getMessage()]; }
    }
  }
}

// Chargement utilisateurs
$users=[]; try{ $users=$gc_pdo->query('SELECT id,first_name,last_name,phone_num,user_email,user_role,status,created_at FROM users_table ORDER BY created_at DESC, id DESC')->fetchAll(); }catch(Throwable $e){ $messages[]=['type'=>'danger','text'=>'Lecture users impossible: '.$e->getMessage()]; }
?><!DOCTYPE html><html lang="fr"><head>
<meta charset="utf-8"><title>Utilisateurs - 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">
<style>.collapse-row{background:#f9fafb}.small-badge{font-size:11px}</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-users text-primary"></i> Utilisateurs</h4>
          <div>
            <a href="add_user.php" class="btn btn-sm btn-primary"><i class="fas fa-user-plus"></i> Ajouter</a>
          </div>
        </div>
        <?php foreach($messages as $m): ?><div class="alert alert-<?php echo htmlspecialchars($m['type']); ?> py-2"><?php echo htmlspecialchars($m['text']); ?></div><?php endforeach; ?>
        <?php if($errors): ?><div class="alert alert-danger py-2"><?php echo htmlspecialchars(implode(' | ',$errors)); ?></div><?php endif; ?>
        <?php if(!$isAdmin): ?><div class="alert alert-warning">Accès restreint. Seul un administrateur peut gérer les utilisateurs.</div><?php endif; ?>
        <div class="card shadow-sm mb-4"><div class="card-body p-2">
          <div class="table-responsive">
            <table class="table table-sm table-bordered mb-0">
              <thead class="thead-light"><tr><th>ID</th><th>Nom</th><th>Email</th><th>Téléphone</th><th>Rôle</th><th>Statut</th><th>Créé</th><th style="width:130px"></th></tr></thead>
              <tbody>
              <?php if(!$users): ?>
                <tr><td colspan="8" class="text-center text-muted">Aucun utilisateur</td></tr>
              <?php else: foreach($users as $u): $rowId='u'.$u['id']; ?>
                <tr>
                  <td><?php echo (int)$u['id']; ?></td>
                  <td><?php echo htmlspecialchars($u['first_name'].' '.$u['last_name']); ?></td>
                  <td><?php echo htmlspecialchars($u['user_email']); ?></td>
                  <td><?php echo htmlspecialchars($u['phone_num']); ?></td>
                  <td><span class="badge badge-<?php echo $u['user_role']==='admin'?'danger':'secondary'; ?> small-badge"><?php echo htmlspecialchars($u['user_role']); ?></span></td>
                  <td><span class="badge badge-<?php echo $u['status']==='active'?'success':'warning'; ?> small-badge"><?php echo htmlspecialchars($u['status']); ?></span></td>
                  <td><?php echo htmlspecialchars(substr($u['created_at'],0,16)); ?></td>
                  <td class="text-right">
                    <button class="btn btn-sm btn-outline-info" type="button" data-toggle="collapse" data-target="#c<?php echo $rowId; ?>" <?php if(!$isAdmin) echo 'disabled'; ?>><i class="fas fa-edit"></i></button>
                    <form method="post" class="d-inline" onsubmit="return confirm('Supprimer cet utilisateur ?');">
                      <input type="hidden" name="action" value="delete_user"><input type="hidden" name="id" value="<?php echo (int)$u['id']; ?>">
                      <button class="btn btn-sm btn-outline-danger" <?php if(!$isAdmin || $u['id']==$me['id']) echo 'disabled'; ?>><i class="fas fa-trash"></i></button>
                    </form>
                  </td>
                </tr>
                <tr id="c<?php echo $rowId; ?>" class="collapse collapse-row">
                  <td colspan="8">
                    <div class="p-2">
                      <div class="row">
                        <div class="col-md-6 border-right">
                          <h6 class="text-primary">Modifier Infos</h6>
                          <form method="post" class="mb-2">
                            <input type="hidden" name="action" value="update_user">
                            <input type="hidden" name="id" value="<?php echo (int)$u['id']; ?>">
                            <div class="form-row">
                              <div class="form-group col-md-6 mb-1"><label class="small mb-0">Prénom</label><input name="first_name" class="form-control form-control-sm" value="<?php echo htmlspecialchars($u['first_name']); ?>" <?php if(!$isAdmin) echo 'disabled'; ?>></div>
                              <div class="form-group col-md-6 mb-1"><label class="small mb-0">Nom</label><input name="last_name" class="form-control form-control-sm" value="<?php echo htmlspecialchars($u['last_name']); ?>" <?php if(!$isAdmin) echo 'disabled'; ?>></div>
                            </div>
                            <div class="form-row">
                              <div class="form-group col-md-6 mb-1"><label class="small mb-0">Téléphone</label><input name="phone_num" class="form-control form-control-sm" value="<?php echo htmlspecialchars($u['phone_num']); ?>" <?php if(!$isAdmin) echo 'disabled'; ?>></div>
                              <div class="form-group col-md-6 mb-1"><label class="small mb-0">Rôle</label><select name="user_role" class="form-control form-control-sm" <?php if(!$isAdmin) echo 'disabled'; ?>><option value="user" <?php if($u['user_role']==='user') echo 'selected'; ?>>user</option><option value="admin" <?php if($u['user_role']==='admin') echo 'selected'; ?>>admin</option></select></div>
                            </div>
                            <div class="form-row">
                              <div class="form-group col-md-6 mb-1"><label class="small mb-0">Statut</label><select name="status" class="form-control form-control-sm" <?php if(!$isAdmin) echo 'disabled'; ?>><option value="active" <?php if($u['status']==='active') echo 'selected'; ?>>active</option><option value="disabled" <?php if($u['status']==='disabled') echo 'selected'; ?>>disabled</option></select></div>
                            </div>
                            <?php if($isAdmin): ?><button class="btn btn-sm btn-primary"><i class="fas fa-save"></i> Enregistrer</button><?php endif; ?>
                          </form>
                        </div>
                        <div class="col-md-6">
                          <h6 class="text-primary">Réinitialiser Mot de Passe</h6>
                          <form method="post" class="mb-2" onsubmit="return confirm('Confirmer le reset du mot de passe ?');">
                            <input type="hidden" name="action" value="reset_pass">
                            <input type="hidden" name="id" value="<?php echo (int)$u['id']; ?>">
                            <div class="form-row">
                              <div class="form-group col-md-6 mb-1"><label class="small mb-0">Nouveau</label><input type="password" name="new_pass" class="form-control form-control-sm" <?php if(!$isAdmin) echo 'disabled'; ?>></div>
                              <div class="form-group col-md-6 mb-1"><label class="small mb-0">Confirmer</label><input type="password" name="new_pass_confirm" class="form-control form-control-sm" <?php if(!$isAdmin) echo 'disabled'; ?>></div>
                            </div>
                            <?php if($isAdmin): ?><button class="btn btn-sm btn-warning"><i class="fas fa-key"></i> Réinitialiser</button><?php endif; ?>
                          </form>
                        </div>
                      </div>
                    </div>
                  </td>
                </tr>
              <?php endforeach; endif; ?>
              </tbody>
            </table>
          </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>
