<?php
// Include database connection
include 'config/connexion.php';
require_once 'includes/simple_log.php';

// Vérifier que l'utilisateur est connecté
if (empty($_SESSION['user_email'])) {
    header('Location: login.php');
    exit;
}

// Initialize variables
$errors = [];
$success = "";
$user = null;
$user_id = $_SESSION['user_id'];

// Fetch current user details
$query = "SELECT * FROM users_table WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    $user = $result->fetch_assoc();
} else {
    header('Location: login.php');
    exit;
}
$stmt->close();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $first_name = trim($_POST['first_name']);
    $last_name = trim($_POST['last_name']);
    $phone_num = trim($_POST['phone_num']);
    $user_email = trim($_POST['user_email']);

    // Validate First Name
    if (empty($first_name)) {
        $errors['first_name'] = "Le prénom est obligatoire.";
    } elseif (!preg_match("/^[a-zA-ZÀ-ÿ\s\-]+$/u", $first_name)) {
        $errors['first_name'] = "Le prénom ne doit contenir que des lettres, des espaces et des tirets.";
    }

    // Validate Last Name
    if (empty($last_name)) {
        $errors['last_name'] = "Le nom est obligatoire.";
    } elseif (!preg_match("/^[a-zA-ZÀ-ÿ\s\-]+$/u", $last_name)) {
        $errors['last_name'] = "Le nom ne doit contenir que des lettres, des espaces et des tirets.";
    }

    // Validate Phone
    if (empty($phone_num)) {
        $errors['phone_num'] = "Le numéro de téléphone est obligatoire.";
    } elseif (!preg_match("/^\d+$/", $phone_num)) {
        $errors['phone_num'] = "Le numéro de téléphone ne doit contenir que des chiffres.";
    } else {
        // Check if Phone is unique (excluding current user)
        $query = "SELECT id FROM users_table WHERE phone_num = ? AND id != ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("si", $phone_num, $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result->num_rows > 0) {
            $errors['phone_num'] = "Ce numéro de téléphone est déjà utilisé.";
        }
        $stmt->close();
    }

    // Validate Email
    if (empty($user_email)) {
        $errors['user_email'] = "L'email est obligatoire.";
    } elseif (!filter_var($user_email, FILTER_VALIDATE_EMAIL)) {
        $errors['user_email'] = "L'email n'est pas valide.";
    } else {
        // Check if Email is unique (excluding current user)
        $query = "SELECT id FROM users_table WHERE user_email = ? AND id != ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("si", $user_email, $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result->num_rows > 0) {
            $errors['user_email'] = "Cet email est déjà utilisé.";
        }
        $stmt->close();
    }

    // Update the user if no errors
    if (!array_filter($errors)) {
        // Stocker les anciennes données pour le log
        $oldData = $user;
        
        $updateQuery = "UPDATE users_table 
                        SET first_name = ?, last_name = ?, phone_num = ?, user_email = ? 
                        WHERE id = ?";
        $updateStmt = $conn->prepare($updateQuery);
        $updateStmt->bind_param("ssssi", $first_name, $last_name, $phone_num, $user_email, $user_id);

        if ($updateStmt->execute()) {
            // Mettre à jour les données de session
            $_SESSION['first_name'] = $first_name;
            $_SESSION['last_name'] = $last_name;
            $_SESSION['user_name'] = $first_name . ' ' . $last_name;
            $_SESSION['phone_num'] = $phone_num;
            $_SESSION['user_email'] = $user_email;

            // Préparer les nouvelles données pour le log
            $newData = [
                'first_name' => $first_name,
                'last_name' => $last_name,
                'phone_num' => $phone_num,
                'user_email' => $user_email
            ];

            // Enregistrer dans le log
            logMessage("à modifier son Profile : " . $oldData['first_name'] . " " . $oldData['last_name'] . " -> " . $first_name . " " . $last_name);

            $success = "Profil mis à jour avec succès.";

            // Reload updated user information
            $query = "SELECT * FROM users_table WHERE id = ?";
            $stmt = $conn->prepare($query);
            $stmt->bind_param("i", $user_id);
            $stmt->execute();
            $result = $stmt->get_result();
            if ($result->num_rows > 0) {
                $user = $result->fetch_assoc();
            }
            $stmt->close();

            // Synchronisation centrale users_compagnie
            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)){
                        $old_email = $oldData['user_email'] ?? $user_email;
                        // Vérifier si enregistrement existe (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)){
                            // Colonnes dynamiques
                            $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];
                            // user_role et status disponibles localement dans $user
                            if(isset($cols['user_role']) && isset($user['user_role'])){ $set[]='user_role=?'; $params[]=$user['user_role']; }
                            if(isset($cols['status']) && isset($user['status'])){ $set[]='status=?'; $params[]=$user['status']; }
                            $params[]=$compagnieRef; $params[]=$old_email; $params[]=$user_email;
                            $sqlC='UPDATE users_compagnie SET '.implode(',', $set).' WHERE compagnie_ref=? AND user_email IN (?,?) LIMIT 1';
                            $up=$gc_pdo->prepare($sqlC); $up->execute($params);
                        } else {
                            // Insérer si absent
                            $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,''];
                            if(isset($cols['user_role']) && isset($user['user_role'])){ $baseCols[]='user_role'; $place.=',?'; $values[]=$user['user_role']; }
                            if(isset($cols['status']) && isset($user['status'])){ $baseCols[]='status'; $place.=',?'; $values[]=$user['status']; }
                            $sqlIns='INSERT INTO users_compagnie('.implode(',',$baseCols).') VALUES('.$place.')';
                            $ins=$gc_pdo->prepare($sqlIns); $ins->execute($values);
                        }
                    }
                }
            } catch(Throwable $syncE){ /* silencieux */ }
        } else {
            $errors['general'] = "Erreur lors de la mise à jour du profil.";
        }

        $updateStmt->close();
    }
}

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

<head>
  <?php include('includes/head.php'); ?>
  <style>
    .profile-form {
        background: #fff;
        border-radius: 10px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    }
    
    .form-control:focus {
        border-color: #667eea;
        box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
    }
    
    .btn-primary {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: none;
    }
    
    .btn-primary:hover {
        background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
    }
    
    .alert-success {
        border-left: 4px solid #28a745;
    }
    
    .alert-danger {
        border-left: 4px solid #dc3545;
    }
  </style>
</head>

<body id="page-top">
  <div id="wrapper">
    <!-- Sidebar -->
    <?php include('includes/sidebar.php'); ?>
    <!-- Sidebar -->
    <div id="content-wrapper" class="d-flex flex-column">
      <div id="content">
        <!-- TopBar -->
        <?php include('includes/topbar.php'); ?>
        <!-- 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">Modifier Mon Profil</h1>
            <ol class="breadcrumb">
              <li class="breadcrumb-item"><a href="dashboard.php">Accueil</a></li>
              <li class="breadcrumb-item"><a href="profile.php">Mon Profil</a></li>
              <li class="breadcrumb-item active" aria-current="page">Modifier</li>
            </ol>
          </div>

          <div class="row justify-content-center">
            <div class="col-lg-8">
              <!-- Form -->
              <div class="card profile-form mb-4">
                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                  <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-user-edit mr-2"></i>Informations Personnelles
                  </h6>
                  <a href="profile.php" class="btn btn-sm btn-secondary">
                    <i class="fas fa-arrow-left mr-1"></i>Retour
                  </a>
                </div>
                <div class="card-body">
                  <?php if (!empty($errors)): ?>
                      <div class="alert alert-danger">
                          <h6><i class="fas fa-exclamation-triangle mr-1"></i>Erreurs de validation :</h6>
                          <ul class="mb-0">
                              <?php foreach ($errors as $error): ?>
                                  <li><?php echo htmlspecialchars($error); ?></li>
                              <?php endforeach; ?>
                          </ul>
                      </div>
                  <?php endif; ?>

                  <?php if (isset($success) && $success): ?>
                      <div class="alert alert-success alert-dismissible fade show" role="alert">
                          <i class="fas fa-check-circle mr-2"></i><?php echo htmlspecialchars($success); ?>
                          <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                              <span aria-hidden="true">&times;</span>
                          </button>
                      </div>
                  <?php endif; ?>

                  <form method="POST" action="edit_profile.php">
                      <div class="row">
                          <div class="col-md-6">
                              <div class="form-group">
                                  <label for="first_name">
                                      <i class="fas fa-user mr-1"></i>Prénom <span class="text-danger">*</span>
                                  </label>
                                  <input type="text" class="form-control" id="first_name" name="first_name" required 
                                         value="<?php echo htmlspecialchars($user['first_name'] ?? ''); ?>"
                                         placeholder="Votre prénom">
                                  <?php if (isset($errors['first_name'])): ?>
                                      <small class="text-danger"><?php echo $errors['first_name']; ?></small>
                                  <?php endif; ?>
                              </div>
                          </div>
                          <div class="col-md-6">
                              <div class="form-group">
                                  <label for="last_name">
                                      <i class="fas fa-user mr-1"></i>Nom <span class="text-danger">*</span>
                                  </label>
                                  <input type="text" class="form-control" id="last_name" name="last_name" required 
                                         value="<?php echo htmlspecialchars($user['last_name'] ?? ''); ?>"
                                         placeholder="Votre nom">
                                  <?php if (isset($errors['last_name'])): ?>
                                      <small class="text-danger"><?php echo $errors['last_name']; ?></small>
                                  <?php endif; ?>
                              </div>
                          </div>
                      </div>

                      <div class="form-group">
                          <label for="user_email">
                              <i class="fas fa-envelope mr-1"></i>Adresse Email <span class="text-danger">*</span>
                          </label>
                          <input type="email" class="form-control" id="user_email" name="user_email" required 
                                 value="<?php echo htmlspecialchars($user['user_email'] ?? ''); ?>"
                                 placeholder="votre.email@exemple.com">
                          <?php if (isset($errors['user_email'])): ?>
                              <small class="text-danger"><?php echo $errors['user_email']; ?></small>
                          <?php endif; ?>
                      </div>

                      <div class="form-group">
                          <label for="phone_num">
                              <i class="fas fa-phone mr-1"></i>Numéro de Téléphone <span class="text-danger">*</span>
                          </label>
                          <input type="text" class="form-control" id="phone_num" name="phone_num" required 
                                 value="<?php echo htmlspecialchars($user['phone_num'] ?? ''); ?>"
                                 placeholder="0123456789">
                          <?php if (isset($errors['phone_num'])): ?>
                              <small class="text-danger"><?php echo $errors['phone_num']; ?></small>
                          <?php endif; ?>
                      </div>

                      <!-- Informations non modifiables -->
                      <div class="row">
                          <div class="col-md-6">
                              <div class="form-group">
                                  <label>
                                      <i class="fas fa-shield-alt mr-1"></i>Rôle
                                  </label>
                                  <input type="text" class="form-control" readonly 
                                         value="<?php echo htmlspecialchars($user['user_role']); ?>">
                                  <small class="form-text text-muted">Ce champ ne peut pas être modifié.</small>
                              </div>
                          </div>
                          <div class="col-md-6">
                              <div class="form-group">
                                  <label>
                                      <i class="fas fa-toggle-on mr-1"></i>Statut
                                  </label>
                                  <input type="text" class="form-control" readonly 
                                         value="<?php echo $user['status'] == 1 ? 'Actif' : 'Inactif'; ?>">
                                  <small class="form-text text-muted">Ce champ ne peut pas être modifié.</small>
                              </div>
                          </div>
                      </div>

                      <hr>

                      <div class="d-flex justify-content-between">
                          <a href="profile.php" class="btn btn-secondary">
                              <i class="fas fa-times mr-1"></i>Annuler
                          </a>
                          <button type="submit" class="btn btn-primary">
                              <i class="fas fa-save mr-1"></i>Sauvegarder les modifications
                          </button>
                      </div>
                  </form>
                </div>
              </div>
            </div>
          </div>

          <!-- Information Card -->
          <div class="row justify-content-center">
            <div class="col-lg-8">
              <div class="card">
                <div class="card-header py-3">
                  <h6 class="m-0 font-weight-bold text-info">
                    <i class="fas fa-info-circle mr-2"></i>Informations importantes
                  </h6>
                </div>
                <div class="card-body">
                  <div class="row">
                    <div class="col-md-6">
                      <h6 class="font-weight-bold">Champs modifiables :</h6>
                      <ul>
                        <li>Prénom et Nom</li>
                        <li>Adresse Email</li>
                        <li>Numéro de Téléphone</li>
                      </ul>
                    </div>
                    <div class="col-md-6">
                      <h6 class="font-weight-bold">Champs protégés :</h6>
                      <ul>
                        <li>Rôle utilisateur</li>
                        <li>Statut du compte</li>
                        <li>Mot de passe</li>
                      </ul>
                    </div>
                  </div>
                  
                  <div class="alert alert-warning mt-3">
                    <strong>Note :</strong> Pour modifier votre mot de passe, utilisez la page 
                    <a href="change_password.php" class="alert-link">Changer le mot de passe</a>.
                  </div>
                </div>
              </div>
            </div>
          </div>

        </div>
        <!---Container Fluid-->
      </div>
      <!-- Footer -->
      <?php include('includes/footer.php'); ?>
      <!-- Footer -->
    </div>
  </div>

  <!-- 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>

  <script>
    $(document).ready(function() {
        // Validation en temps réel
        $('#phone_num').on('input', function() {
            this.value = this.value.replace(/[^0-9]/g, '');
        });
        
        // Auto-focus sur le premier champ
        $('#first_name').focus();
        
        // Confirmation avant soumission si des changements ont été faits
        let originalFormData = $('form').serialize();
        
        $('form').on('submit', function(e) {
            let currentFormData = $(this).serialize();
            
            if (originalFormData === currentFormData) {
                e.preventDefault();
                alert('Aucune modification détectée.');
                return false;
            }
        });
    });
  </script>

</body>

</html>
