<?php
// Include database connection
include 'config/connexion.php';
require_once 'includes/simple_log.php';
// Initialize variables
$errors = [];
$success = "";
$client = null;

// Check if client ID is provided
if (isset($_GET['id'])) {
    $clientId = intval($_GET['id']);

    // Fetch client details
    $query = "SELECT id, client_cin, client_name, client_phone, client_email, client_company, client_genre, client_adresse, n_dossier, client_ice FROM clients_table WHERE id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $clientId);
    $stmt->execute();
    $stmt->bind_result($id, $client_cin, $client_name, $client_phone, $client_email, $client_company, $client_genre, $client_adresse, $n_dossier, $client_ice);

    if ($stmt->fetch()) {
        $client = array(
            'id' => $id,
            'client_cin' => $client_cin,
            'client_name' => $client_name,
            'client_phone' => $client_phone,
            'client_email' => $client_email,
            'client_company' => $client_company,
            'client_genre' => $client_genre,
            'client_adresse' => $client_adresse,
            'n_dossier' => $n_dossier,
            'client_ice' => $client_ice
        );
    } else {
        $errors[] = "Client introuvable.";
    }
    $stmt->close();
} else {
    $errors[] = "Aucun ID de client fourni.";
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {    $client_cin = strtoupper(trim($_POST['client_cin']));
    $client_name = strtoupper(trim($_POST['client_name']));
    $client_phone = trim($_POST['client_phone']);
    $client_email = trim($_POST['client_email']);
    $client_company = strtoupper(trim($_POST['client_company']));
    $client_genre = trim($_POST['client_genre']);
    $client_adresse = trim($_POST['client_adresse']);
    $n_dossier = trim($_POST['n_dossier']); // Nouveau champ
    $client_ice = trim($_POST['client_ice']); // Champ ICE non obligatoire

    // Validate CIN
    if (empty($client_cin)) {
        $errors['client_cin'] = "Le CIN du client est obligatoire.";
    } else {
        // Check if CIN is unique
        $query = "SELECT id FROM clients_table WHERE client_cin = ? AND id != ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("si", $client_cin, $clientId);
        $stmt->execute();
        $stmt->bind_result($existing_id);
        if ($stmt->fetch()) {
            $errors['client_cin'] = "Le CIN existe déjà.";
        }
        $stmt->close();
    }

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

    // Validate Phone
    if (empty($client_phone)) {
        $errors['client_phone'] = "Le numéro de téléphone du client est obligatoire.";
    } elseif (!preg_match("/^\d+$/", $client_phone)) {
        $errors['client_phone'] = "Le numéro de téléphone ne doit contenir que des chiffres.";
    } else {
        // Check if Phone is unique
        $query = "SELECT id FROM clients_table WHERE client_phone = ? AND id != ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("si", $client_phone, $clientId);
        $stmt->execute();
        $stmt->bind_result($existing_id);
        if ($stmt->fetch()) {
            $errors['client_phone'] = "Le numéro de téléphone existe déjà.";
        }
        $stmt->close();
    }

    // Validate Email
    if (!empty($client_email)) {
        if (!filter_var($client_email, FILTER_VALIDATE_EMAIL)) {
            $errors['client_email'] = "L'email n'est pas valide.";
        } else {
            // Check if Email is unique
            $query = "SELECT id FROM clients_table WHERE client_email = ? AND id != ?";
            $stmt = $conn->prepare($query);
            $stmt->bind_param("si", $client_email, $clientId);
            $stmt->execute();
            $stmt->bind_result($existing_id);
            if ($stmt->fetch()) {
                $errors['client_email'] = "L'email existe déjà.";
            }
            $stmt->close();
        }
    }

    // Validate Genre
    if (empty($client_genre)) {
        $errors['client_genre'] = "Le genre du client est obligatoire.";
    }

    // Validate Address
    if (empty($client_adresse)) {
        $errors['client_adresse'] = "L'adresse du client est obligatoire.";
    }

    // Validate Folder Number
    if (empty($n_dossier)) {
        $errors['n_dossier'] = "Le numéro de dossier est obligatoire.";
    } else {
        // Check if the folder number is unique
        $query = "SELECT id FROM clients_table WHERE n_dossier = ? AND id != ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("si", $n_dossier, $clientId);
        $stmt->execute();
        $stmt->bind_result($existing_id);
        if ($stmt->fetch()) {
            $errors['n_dossier'] = "Le numéro de dossier existe déjà.";
        }
        $stmt->close();
    }    // Si Entreprise est vide, utiliser le nom du client
    if (empty($client_company)) {
        $client_company = $client_name;
    }
    
    // Si l'entreprise était identique à l'ancien nom du client et que le nom change,
    // mettre à jour automatiquement l'entreprise avec le nouveau nom
    if (isset($client['client_name']) && isset($client['client_company'])) {
        if ($client['client_company'] === $client['client_name'] && $client_name !== $client['client_name']) {
            $client_company = $client_name;
        }
    }// Update the client if no errors
    if (!array_filter($errors)) {
        // Stocker les anciennes données pour le log
        $oldData = $client;

        $updateQuery = "UPDATE clients_table 
                        SET client_cin = ?, client_name = ?, client_phone = ?, client_email = ?, client_company = ?, client_genre = ?, client_adresse = ?, n_dossier = ?, client_ice = ? 
                        WHERE id = ?";
        $updateStmt = $conn->prepare($updateQuery);
        $updateStmt->bind_param("sssssssssi", $client_cin, $client_name, $client_phone, $client_email, $client_company, $client_genre, $client_adresse, $n_dossier, $client_ice, $clientId);

        if ($updateStmt->execute()) {
            // Préparer les nouvelles données pour le log
            $newData = [
                'client_cin' => $client_cin,
                'client_name' => $client_name,
                'client_phone' => $client_phone,
                'client_email' => $client_email,
                'client_company' => $client_company,
                'client_genre' => $client_genre,
                'client_adresse' => $client_adresse,
                'n_dossier' => $n_dossier,
                'client_ice' => $client_ice
            ];
            
            // Enregistrer dans le log avec détails des changements
            logClientEdit($client_name, $clientId, $oldData, $newData);

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

            // Reload updated client information
            $query = "SELECT id, client_cin, client_name, client_phone, client_email, client_company, client_genre, client_adresse, n_dossier, client_ice FROM clients_table WHERE id = ?";
            $stmt = $conn->prepare($query);
            $stmt->bind_param("i", $clientId);
            $stmt->execute();
            $stmt->bind_result($id, $client_cin, $client_name, $client_phone, $client_email, $client_company, $client_genre, $client_adresse, $n_dossier, $client_ice);
            if ($stmt->fetch()) {
                $client = array(
                    'id' => $id,
                    'client_cin' => $client_cin,
                    'client_name' => $client_name,
                    'client_phone' => $client_phone,
                    'client_email' => $client_email,
                    'client_company' => $client_company,
                    'client_genre' => $client_genre,
                    'client_adresse' => $client_adresse,
                    'n_dossier' => $n_dossier,
                    'client_ice' => $client_ice
                );
            }
            $stmt->close();

            // Trigger success modal
            echo "<script>
                document.addEventListener('DOMContentLoaded', function() {
                    $('#successModal').modal('show');
                });
            </script>";
        } else {
            $errors['client_cin'] = "Erreur lors de la mise à jour du client.";
        }

        $updateStmt->close();
    }
}

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

<head>
  <?php include ('includes/head.php'); ?>
  <style>
    /* Afficher automatiquement en majuscules */
    #client_name, #client_company, #client_cin {
        text-transform: uppercase;
    }
  </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'); ?> <!-- 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">Modifier un client</h1>
            <ol class="breadcrumb">
              <li class="breadcrumb-item"><a href="./">Accueil</a></li>
              <li class="breadcrumb-item">Clients</li>
              <li class="breadcrumb-item active" aria-current="page">Modifier un client</li>
            </ol>
          </div>

          <div class="row">
            <div class="col-lg-6">
              <!-- Form -->
              <div class="card 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">Formulaire de modification</h6>
                </div>
                <div class="card-body">
                  <?php if (!empty($errors)): ?>
                      <div class="alert alert-danger">
                          <ul>
                              <?php foreach ($errors as $error): ?>
                                  <li><?php echo $error; ?></li>
                              <?php endforeach; ?>
                          </ul>
                      </div>
                  <?php endif; ?>                  <?php if (isset($success) && $success): ?>
                      <div class="alert alert-success alert-dismissible fade show" role="alert">
                          <?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; ?>

                  <?php if ($client): ?>
                      <form method="POST" action="edit_client.php?id=<?php echo $clientId; ?>">
                          <div class="form-group">
                              <label for="client_cin">CIN du client</label>
                              <input type="text" class="form-control" id="client_cin" name="client_cin" required value="<?php echo htmlspecialchars($client['client_cin'] ?? ''); ?>">
                          </div>
                          <div class="form-group">
                              <label for="client_name">Nom du client</label>
                              <input type="text" class="form-control" id="client_name" name="client_name" required value="<?php echo htmlspecialchars($client['client_name'] ?? ''); ?>">
                          </div>
                          <div class="form-group">
                              <label for="client_phone">Numéro de téléphone</label>
                              <input type="text" class="form-control" id="client_phone" name="client_phone" required value="<?php echo htmlspecialchars($client['client_phone'] ?? ''); ?>">
                          </div>
                          <div class="form-group">
                              <label for="client_email">Email</label>
                              <input type="email" class="form-control" id="client_email" name="client_email" value="<?php echo htmlspecialchars($client['client_email'] ?? ''); ?>">
                          </div>
                          <div class="form-group">
                              <label for="client_company">Entreprise</label>
                              <input type="text" class="form-control" id="client_company" name="client_company" value="<?php echo htmlspecialchars($client['client_company'] ?? ''); ?>">
                          </div>
                          <div class="form-group">
                              <label for="client_genre">Genre</label>
                              <select class="form-control" id="client_genre" name="client_genre" required>
                                  <option value="Mâle" <?php if (($client['client_genre'] ?? '') === 'Mâle') echo 'selected'; ?>>Mâle</option>
                                  <option value="Femelle" <?php if (($client['client_genre'] ?? '') === 'Femelle') echo 'selected'; ?>>Femelle</option>
                                  <option value="Personne Morale" <?php if (($client['client_genre'] ?? '') === 'Personne Morale') echo 'selected'; ?>>Personne Morale</option>
                              </select>
                          </div>
                          <div class="form-group">
                              <label for="client_adresse">Adresse</label>
                              <input type="text" class="form-control" id="client_adresse" name="client_adresse" required value="<?php echo htmlspecialchars($client['client_adresse'] ?? ''); ?>">
                          </div>                          <div class="form-group">
                              <label for="n_dossier">Numéro de dossier</label>
                              <input type="text" class="form-control" id="n_dossier" name="n_dossier" required value="<?php echo htmlspecialchars($client['n_dossier'] ?? ''); ?>">
                          </div>
                          <div class="form-group">
                              <label for="client_ice">ICE (Identifiant Commun de l'Entreprise)</label>
                              <input type="text" class="form-control" id="client_ice" name="client_ice" 
                                     value="<?php echo htmlspecialchars($client['client_ice'] ?? ''); ?>"
                                     placeholder="Facultatif">
                          </div>
                          <div class="d-flex justify-content-between">
                              <button type="submit" class="btn btn-primary">Mettre à jour</button>
                              <a href="clients_table.php" class="btn btn-secondary">Annuler</a>
                          </div>
                      </form>
                  <?php endif; ?>
                </div>
              </div>
            </div>
          </div>
          <!--Row-->

          <!-- Success Modal -->
          <div class="modal fade" id="successModal" tabindex="-1" role="dialog" aria-labelledby="successModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered" role="document">
              <div class="modal-content">
                <div class="modal-header">
                  <h5 class="modal-title" id="successModalLabel">Mise à jour réussie</h5>
                  <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                  </button>
                </div>                <div class="modal-body">
                  <?php echo isset($success) ? htmlspecialchars($success) : 'Le client a été mis à jour avec succès.'; ?>
                </div>
                <div class="modal-footer">
                  <a href="clients_table.php" class="btn btn-primary">Retour à la liste des clients</a>
                </div>
              </div>
            </div>
          </div>

        </div>
        <!---Container Fluid-->
      </div>
      <!-- Footer -->
      <?php include ('includes/footer.php'); ?>
      <!-- Footer -->
    </div>
  </div>
  <!-- Include required scripts -->
  <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 pour convertir automatiquement en majuscules -->
  <script>
    $(document).ready(function() {
        // Convertir en majuscules lors de la frappe pour le nom du client
        $('#client_name').on('input', function() {
            var cursorPosition = this.selectionStart;
            var value = $(this).val().toUpperCase();
            $(this).val(value);
            this.setSelectionRange(cursorPosition, cursorPosition);
            
            // Si l'entreprise est identique au nom du client, la mettre à jour aussi
            var currentCompany = $('#client_company').val();
            var originalName = "<?php echo htmlspecialchars($client['client_name'] ?? ''); ?>";
            if (currentCompany === originalName || currentCompany === '') {
                $('#client_company').val(value);
            }
        });
        
        // Convertir en majuscules lors de la frappe pour l'entreprise
        $('#client_company').on('input', function() {
            var cursorPosition = this.selectionStart;
            var value = $(this).val().toUpperCase();
            $(this).val(value);
            this.setSelectionRange(cursorPosition, cursorPosition);
        });
        
        // Convertir en majuscules lors de la frappe pour le CIN
        $('#client_cin').on('input', function() {
            var cursorPosition = this.selectionStart;
            var value = $(this).val().toUpperCase();
            $(this).val(value);
            this.setSelectionRange(cursorPosition, cursorPosition);
        });
    });
  </script>
</body>

</html>