<?php
include 'config/connexion.php';
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['id'])) {
    $id = intval($_GET['id']);

    // Fetch user details
    $stmt = $conn->prepare("SELECT first_name, last_name, phone_num, user_email, user_role, status FROM users_table WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 1) {
        $user = $result->fetch_assoc();
    } else {
        die("Utilisateur introuvable.");
    }

    $stmt->close();
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Fetch original user details to populate $old_agent
    $id = intval($_POST['id']);
  $stmt = $conn->prepare("SELECT first_name, last_name, user_email, phone_num, user_role, status FROM users_table WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows === 1) {
        $original_user = $result->fetch_assoc();
  $old_agent = $original_user['first_name'] . ' ' . $original_user['last_name'];
  $old_email = $original_user['user_email'];
    } else {
        die("Utilisateur introuvable.");
    }
    $stmt->close();

    // Ensure $user is defined to avoid undefined variable error
    $user = [
        'first_name' => '',
        'last_name' => '',
        'phone_num' => '',
        'user_email' => '',
        'user_role' => '',
        'status' => 0
    ];

  // Update user details
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $phone_num = $_POST['phone_num'];
    $user_email = $_POST['user_email'];
    $user_role = $_POST['user_role'];
    $status = intval($_POST['status']);
  // Fetch current role to validate demotion of Super admin
  $stmtCur = $conn->prepare("SELECT user_role FROM users_table WHERE id=? LIMIT 1");
  $stmtCur->bind_param("i", $id);
  $stmtCur->execute();
  $resCur = $stmtCur->get_result();
  $currentRow = $resCur->fetch_assoc();
  $stmtCur->close();
  if($currentRow){
    $currentRole = $currentRow['user_role'];
    if(strcasecmp($currentRole,'Super admin')===0 && strcasecmp($user_role,'Super admin')!==0){
      // Check if there is at least another Super admin
      $cnt = $conn->query("SELECT COUNT(*) AS c FROM users_table WHERE user_role='Super admin' AND id<>".$id);
      $rowCnt = $cnt? $cnt->fetch_assoc():null;
      $otherSupers = $rowCnt? (int)$rowCnt['c']:0;
      if($otherSupers < 1){
        $error = "Impossible de retirer le rôle Super admin: il doit rester au moins un Super admin.";
      }
    }
  }

    // Validation
    if (!preg_match("/^[a-zA-ZÀ-ÿ\s]+$/", $first_name)) {
        $error = "Le prénom doit contenir uniquement des lettres.";
    } elseif (!preg_match("/^[a-zA-ZÀ-ÿ\s]+$/", $last_name)) {
        $error = "Le nom doit contenir uniquement des lettres.";
    } else {
        // Check if phone number is unique
        $stmt = $conn->prepare("SELECT id FROM users_table WHERE phone_num = ? AND id != ?");
        $stmt->bind_param("si", $phone_num, $id);
        $stmt->execute();
        $stmt->store_result();
        if ($stmt->num_rows > 0) {
            $error = "Le numéro de téléphone est déjà utilisé.";
        }
        $stmt->close();

        // Check if email is unique
        if (!isset($error)) {
            $stmt = $conn->prepare("SELECT id FROM users_table WHERE user_email = ? AND id != ?");
            $stmt->bind_param("si", $user_email, $id);
            $stmt->execute();
            $stmt->store_result();
            if ($stmt->num_rows > 0) {
                $error = "L'email est déjà utilisé.";
            }
            $stmt->close();
        }
    }

    // If no errors, proceed with the update
    if (!isset($error)) {
  if(!isset($error)){
  $stmt = $conn->prepare("UPDATE users_table SET first_name = ?, last_name = ?, phone_num = ?, user_email = ?, user_role = ?, status = ? WHERE id = ?");
        $stmt->bind_param("ssssssi", $first_name, $last_name, $phone_num, $user_email, $user_role, $status, $id);

  if ($stmt->execute()) {
            // Update agent in history_table if first_name or last_name is changed
            $new_agent = $first_name . ' ' . $last_name;
      if ($new_agent !== $old_agent) {
        // Vérifier existence de history_table avant mise à jour
        try {
          $tableCheck = $conn->query("SHOW TABLES LIKE 'history_table'");
          if($tableCheck && $tableCheck->num_rows > 0){
            $stmt_history = $conn->prepare("UPDATE history_table SET agent = ? WHERE agent = ?");
            if($stmt_history){
              $stmt_history->bind_param("ss", $new_agent, $old_agent);
              $stmt_history->execute();
              $stmt_history->close();
            }
          }
        } catch(Throwable $hx){ /* ignorer si table absente */ }
      }

            // Synchronisation centrale users_compagnie (si disponible)
            try {
              if(session_status()===PHP_SESSION_NONE) @session_start();
              $compagnieRef = $_SESSION['compagnie_ref'] ?? null;
              if($compagnieRef){
                if(!isset($gc_pdo)) { @require_once __DIR__.'/gestion_compagnies/config/connexion.php'; }
                if(isset($gc_pdo)){
                  // Vérifier si l'enregistrement existe déjà (selon ancien ou nouvel email)
                  $check = $gc_pdo->prepare('SELECT id FROM users_compagnie WHERE compagnie_ref=? AND user_email IN (?,?) LIMIT 1');
                  $check->execute([$compagnieRef,$old_email,$user_email]);
                  if($check->fetch(PDO::FETCH_ASSOC)){
                    // Récupérer colonnes existantes
                    $cols=[]; $rc=$gc_pdo->query('SHOW COLUMNS FROM users_compagnie'); while($c=$rc->fetch(PDO::FETCH_ASSOC)){ $cols[$c['Field']]=true; }
                    $set=['first_name=?','last_name=?','phone_num=?','user_email=?'];
                    $params=[$first_name,$last_name,$phone_num,$user_email];
                    if(isset($cols['user_role'])){ $set[]='user_role=?'; $params[]=$user_role; }
                    if(isset($cols['status'])){ $set[]='status=?'; $params[]=$status; }
                    $params[]=$compagnieRef; $params[]=$old_email; $params[]=$user_email; // conditions
                    $sqlC="UPDATE users_compagnie SET ".implode(',', $set)." WHERE compagnie_ref=? AND user_email IN (?,?) LIMIT 1";
                    $upC=$gc_pdo->prepare($sqlC); $upC->execute($params);
                  } else {
                    // Insérer si absent (structure minimale + colonnes optionnelles si existent)
                    $cols=[]; $rc2=$gc_pdo->query('SHOW COLUMNS FROM users_compagnie'); while($c2=$rc2->fetch(PDO::FETCH_ASSOC)){ $cols[$c2['Field']]=true; }
                    $baseCols=['compagnie_ref','first_name','last_name','phone_num','user_email','user_pass'];
                    $place='?,?,?,?,?,?';
                    $values=[$compagnieRef,$first_name,$last_name,$phone_num,$user_email,'']; // mot de passe inconnu ici
                    if(isset($cols['user_role'])){ $baseCols[]='user_role'; $place.=',?'; $values[]=$user_role; }
                    if(isset($cols['status'])){ $baseCols[]='status'; $place.=',?'; $values[]=$status; }
                    $sqlIns='INSERT INTO users_compagnie('.implode(',',$baseCols).') VALUES('.$place.')';
                    $insC=$gc_pdo->prepare($sqlIns); $insC->execute($values);
                  }
                }
              }
            } catch(Throwable $eSync){ /* silencieux */ }

            echo "<script>
                    document.addEventListener('DOMContentLoaded', function() {
                        $('#successModal').modal('show');
                    });
                  </script>";
        } else {
            $error = "Échec de la mise à jour de l'utilisateur.";
        }

        $stmt->close();
  }
    }

    // Ensure $user is defined to retain form values
    $user = [
        'first_name' => $first_name,
        'last_name' => $last_name,
        'phone_num' => $phone_num,
        'user_email' => $user_email,
        'user_role' => $user_role,
        'status' => $status
    ];
}

// Fetch roles for dropdown (common for both GET and POST requests)
$roles = [];
$roles_stmt = $conn->prepare("SELECT role_name FROM roles_table");
$roles_stmt->execute();
$roles_result = $roles_stmt->get_result();
while ($row = $roles_result->fetch_assoc()) {
    $roles[] = $row['role_name'];
}
$roles_stmt->close();

// Connection is managed globally; do not close it here.
?>
<!DOCTYPE html>
<html lang="fr">

<head>
 <?php include ('includes/head.php'); ?>
</head>

<body id="page-top">
  <div id="wrapper">
    <!-- Sidebar -->
   <?php include ('includes/sidebar.php'); ?> <!-- Inclusion de la barre latérale -->
    <!-- Sidebar -->
    <div id="content-wrapper" class="d-flex flex-column">
      <div id="content">
        <!-- TopBar -->
       <?php include ('includes/topbar.php'); ?> <!-- Inclusion de la barre supérieure -->
        <!-- Topbar -->
        <!-- Container Fluid-->
        <div class="container-fluid" id="container-wrapper">
          <div class="d-sm-flex align-items-center justify-content-between mb-4">
            <h1 class="h3 mb-0 text-gray-800">Éditer l'utilisateur</h1>
            <ol class="breadcrumb">
              <li class="breadcrumb-item"><a href="./">Accueil</a></li>
              <li class="breadcrumb-item"><a href="users_table.php">Table des utilisateurs</a></li>
              <li class="breadcrumb-item active" aria-current="page">Éditer l'utilisateur</li>
            </ol>
          </div>

          <!-- Edit User Form -->
          <div class="card mb-4">
            <div class="card-header py-3">
              <h6 class="m-0 font-weight-bold text-primary">Modifier les informations de l'utilisateur</h6>
            </div>
            <div class="card-body">
              <?php if (isset($error)): ?>
                <div class="alert alert-danger"><?php echo $error; ?></div>
              <?php endif; ?>
              <form method="POST" action="edit_user.php?id=<?php echo htmlspecialchars($id); ?>">
                <input type="hidden" name="id" value="<?php echo htmlspecialchars($id); ?>">
                <div class="form-group">
                  <label for="first_name">Prénom</label>
                  <input type="text" class="form-control" id="first_name" name="first_name" value="<?php echo htmlspecialchars($user['first_name']); ?>" required>
                </div>
                <div class="form-group">
                  <label for="last_name">Nom</label>
                  <input type="text" class="form-control" id="last_name" name="last_name" value="<?php echo htmlspecialchars($user['last_name']); ?>" required>
                </div>
                <div class="form-group">
                  <label for="phone_num">Numéro de téléphone</label>
                  <input type="text" class="form-control" id="phone_num" name="phone_num" value="<?php echo htmlspecialchars($user['phone_num']); ?>" required>
                </div>
                <div class="form-group">
                  <label for="user_email">Email</label>
                  <input type="email" class="form-control" id="user_email" name="user_email" value="<?php echo htmlspecialchars($user['user_email']); ?>" required>
                </div>
                <div class="form-group">
                  <label for="user_role">Rôle</label>
                  <select class="form-control" id="user_role" name="user_role" required>
                    <?php foreach ($roles as $role): ?>
                      <option value="<?php echo htmlspecialchars($role); ?>" <?php echo htmlspecialchars($user['user_role']) === $role ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($role); ?>
                      </option>
                    <?php endforeach; ?>
                  </select>
                </div>
                <div class="form-group">
                  <label for="status">Statut</label>
                  <select class="form-control" id="status" name="status" required>
                    <option value="1" <?php echo $user['status'] == 1 ? 'selected' : ''; ?>>Activé</option>
                    <option value="0" <?php echo $user['status'] == 0 ? 'selected' : ''; ?>>Désactivé</option>
                  </select>
                </div>
                <button type="submit" class="btn btn-primary">Enregistrer</button>
                <a href="users_table.php" class="btn btn-secondary">Annuler</a>
              </form>
            </div>
          </div>
          <!-- End Edit User Form -->
        </div>
        <!---Container Fluid-->
      </div>
      <!-- Footer -->
      <?php include ('includes/footer.php'); ?>
      <!-- Footer -->
    </div>
  </div>

  <!-- Success Modal -->
  <div class="modal fade" id="successModal" tabindex="-1" role="dialog" aria-labelledby="successModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="successModalLabel">Succès</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <h5 class="text-success">Mise à jour réussie !</h5>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-primary" onclick="window.location.href='users_table.php';">OK</button>
        </div>
      </div>
    </div>
  </div>
  <!-- End Success Modal -->

  <!-- Scroll to top -->
  <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>