<?php
// Include database connection
include 'config/connexion.php';
include 'includes/simple_log.php';
session_start();

// Initialize variables
$errors = [
    'marque' => ''
];
$success = "";
$marqueData = null;

// Get marque ID from URL
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header('Location: marques_table.php');
    exit;
}

$id = $_GET['id'];

// Fetch existing marque data
$query = "SELECT * FROM marques_transport WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    header('Location: marques_table.php');
    exit;
}

$marqueData = $result->fetch_assoc();
$stmt->close();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $marque = strtoupper(trim($_POST['marque']));

    // Validate marque
    if (empty($marque)) {
        $errors['marque'] = "La marque est obligatoire.";
    }

    // Check if marque already exists (excluding current record)
    if (!empty($marque)) {
        $query = "SELECT id FROM marques_transport WHERE marque = ? AND id != ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("si", $marque, $id);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result->num_rows > 0) {
            $errors['general'] = "Cette marque existe déjà.";
        }
        $stmt->close();
    }

    // Update the marque if no validation errors
    if (!array_filter($errors)) {
        $updateQuery = "UPDATE marques_transport SET marque = ? WHERE id = ?";
        $updateStmt = $conn->prepare($updateQuery);
        $updateStmt->bind_param("si", $marque, $id);        if ($updateStmt->execute()) {
            // Enregistrer la modification de la marque dans le log global
            logMarqueEdit($marqueData['marque'], $marque);
            
            $success = "Marque modifiée avec succès.";
            // Refresh marque data
            $marqueData['marque'] = $marque;
        } else {
            $errors['general'] = "Erreur lors de la modification de la marque.";
        }

        $updateStmt->close();
    }
}

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

<head>
 <?php include('includes/head.php'); ?>
</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 une Marque de Transport</h1>
            <ol class="breadcrumb">
              <li class="breadcrumb-item"><a href="./">Accueil</a></li>
              <li class="breadcrumb-item"><a href="marques_table.php">Marques</a></li>
              <li class="breadcrumb-item active" aria-current="page">Modifier une Marque</li>
            </ol>
          </div>

          <div class="row">
            <div class="col-lg-6">
              <!-- Form Basic -->
              <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 ($success): ?>
                      <div class="alert alert-success">
                          <i class="fas fa-check-circle mr-2"></i><?php echo $success; ?>
                      </div>
                  <?php endif; ?>

                  <?php if (!empty($errors['general'])): ?>
                      <div class="alert alert-danger">
                          <i class="fas fa-exclamation-triangle mr-2"></i><?php echo $errors['general']; ?>
                      </div>
                  <?php endif; ?>                  <form method="POST" action="edit_marque.php?id=<?php echo $id; ?>">
                      <div class="form-group">
                          <label for="marque">Marque <span class="text-danger">*</span></label>
                          <input type="text" class="form-control" id="marque" name="marque" required 
                                 value="<?php echo htmlspecialchars($marqueData['marque']); ?>"
                                 placeholder="Exemple: TOYOTA, MERCEDES, BMW, YAMAHA...">
                          <?php if ($errors['marque']): ?>
                              <small class="text-danger"><?php echo $errors['marque']; ?></small>
                          <?php endif; ?>
                      </div>

                      <div class="d-flex justify-content-between">
                          <button type="submit" class="btn btn-primary">
                              <i class="fas fa-save mr-1"></i>Sauvegarder
                          </button>
                          <a href="marques_table.php" class="btn btn-secondary">
                              <i class="fas fa-arrow-left mr-1"></i>Retour à la liste
                          </a>
                      </div>
                  </form>
                </div>
              </div>
            </div>

            <div class="col-lg-6">
              <!-- Current Info Card -->
              <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-info">Informations actuelles</h6>
                </div>                <div class="card-body">
                  <dl class="row">
                    <dt class="col-sm-4">ID:</dt>
                    <dd class="col-sm-8"><?php echo htmlspecialchars($marqueData['id']); ?></dd>
                    
                    <dt class="col-sm-4">Marque:</dt>
                    <dd class="col-sm-8"><span class="badge badge-primary"><?php echo htmlspecialchars($marqueData['marque']); ?></span></dd>
                  </dl>
                </div>
              </div>

              <!-- Instructions Card -->
              <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-warning">Instructions</h6>
                </div>                <div class="card-body">
                  <h6 class="font-weight-bold">Comment modifier :</h6>
                  <ul>
                    <li><strong>Marque :</strong> Modifiez le nom de la marque (sera automatiquement converti en majuscules)</li>
                  </ul>
                  
                  <div class="alert alert-warning mt-3">
                    <strong>Attention :</strong> Le nom de la marque doit être unique dans la base de données.
                  </div>
                </div>
              </div>
            </div>
          </div>
          <!--Row-->
          
        </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>

  <!-- Auto-transform to uppercase script -->
  <script>
    $(document).ready(function() {
        // Convertir le champ marque en majuscules
        $('#marque').on('input', function() {
            this.value = this.value.toUpperCase();
        });
    });
  </script>

</body>

</html>
