<?php
// Include database connection and session guard
if (session_status() === PHP_SESSION_NONE) { session_start(); }
include 'config/connexion.php';
if (empty($_SESSION['user_email']) && empty($_SESSION['user_name'])) { header('Location: login.php'); exit; }
if (empty($COMPANY_DB_AVAILABLE) || !($conn instanceof mysqli)) { header('Location: login.php'); exit; }
include 'includes/simple_log.php';

// Initialize variables for form submission
$errors = [
    'marque' => ''
];
$success = "";

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
    if (!empty($marque)) {
        $query = "SELECT id FROM marques_transport WHERE marque = ?";
  $stmt = $conn->prepare($query);
        $stmt->bind_param("s", $marque);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result->num_rows > 0) {
            $errors['general'] = "Cette marque existe déjà.";
        }
        $stmt->close();
    }

    // Insert the marque if no validation errors
    if (!array_filter($errors)) {
        $insertQuery = "INSERT INTO marques_transport (marque) VALUES (?)";
  $insertStmt = $conn->prepare($insertQuery);
        $insertStmt->bind_param("s", $marque);        if ($insertStmt->execute()) {
            // Enregistrer l'ajout de la marque dans le log global
            logMarqueCreation($marque);
            
            $success = "Marque ajoutée avec succès.";
            // Clear form fields after success
            $marque = '';
        } else {
            $errors['general'] = "Erreur lors de l'ajout de la marque.";
        }

        $insertStmt->close();
    }
}
?>
<!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">Ajouter une Marque de Transport</h1>
            <ol class="breadcrumb">
              <li class="breadcrumb-item"><a href="./">Accueil</a></li>
              <li class="breadcrumb-item">Marques</li>
              <li class="breadcrumb-item active" aria-current="page">Ajouter 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 d'ajout</h6>
                </div>
                <div class="card-body">
                  <?php if ($success): ?>
                      <div class="alert alert-success">
                          <?php echo $success; ?>
                      </div>
                  <?php endif; ?>

                  <?php if (!empty($errors['general'])): ?>
                      <div class="alert alert-danger">
                          <?php echo $errors['general']; ?>
                      </div>
                  <?php endif; ?>

                  <form method="POST" action="add_marque.php">                      <div class="form-group">
                          <label for="marque">Marque</label>
                          <input type="text" class="form-control" id="marque" name="marque" required 
                                 value="<?php if(!empty($marque)){echo htmlspecialchars($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">Ajouter</button>
                          <a href="marques_table.php" class="btn btn-secondary">Voir la liste</a>
                      </div>
                  </form>
                </div>
              </div>
            </div>

            <div class="col-lg-6">
              <!-- 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">Instructions</h6>
                </div>
                <div class="card-body">                  <h6 class="font-weight-bold">Comment remplir le formulaire :</h6>
                  <ul>
                    <li><strong>Marque :</strong> Saisissez le nom de la marque (sera automatiquement converti en majuscules)</li>
                  </ul>
                  
                  <div class="alert alert-info mt-3">
                    <strong>Note :</strong> Chaque marque doit être unique. Vous ne pouvez pas ajouter deux fois la même marque.
                  </div>

                  <h6 class="font-weight-bold mt-3">Exemples de saisie :</h6>
                  <div class="table-responsive">
                    <table class="table table-sm">
                      <thead>
                        <tr>
                          <th>Marque</th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr>
                          <td>TOYOTA</td>
                        </tr>
                        <tr>
                          <td>MERCEDES</td>
                        </tr>                        <tr>
                          <td>YAMAHA</td>
                        </tr>
                        <tr>
                          <td>VOLVO</td>
                        </tr>
                        <tr>
                          <td>IVECO</td>
                        </tr>
                      </tbody>
                    </table>
                  </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() {
        // La conversion en majuscules n'est plus nécessaire car on utilise un select
        $('#marque').on('input', function() {
            this.value = this.value.toUpperCase();
        });
    });
  </script>

</body>

</html>
