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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $type = strtoupper(trim($_POST['type']));
    $risque = trim($_POST['risque']);

    // Validate type
    if (empty($type)) {
        $errors['type'] = "Le type de police est obligatoire.";
    }

    // Validate risque
    if (empty($risque)) {
        $errors['risque'] = "Le type de risque est obligatoire.";
    }

    // Check if type already exists
    if (!empty($type)) {
        $query = "SELECT id FROM policy_type WHERE type = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("s", $type);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result->num_rows > 0) {
            $errors['general'] = "Ce type de police existe déjà.";
        }
        $stmt->close();
    }

    // Insert the type if no validation errors
    if (!array_filter($errors)) {
        $insertQuery = "INSERT INTO policy_type (type, risque) VALUES (?, ?)";
        $insertStmt = $conn->prepare($insertQuery);
        $insertStmt->bind_param("ss", $type, $risque);

        if ($insertStmt->execute()) {
            // Enregistrer l'ajout du type de police dans le log global
            logPolicyTypeCreation($type);
            
            $success = "Type de police ajouté avec succès.";
            // Clear form fields after success
            $type = '';
            $risque = '';
        } else {
            $errors['general'] = "Erreur lors de l'ajout du type de police.";
        }

        $insertStmt->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">Ajouter un Type de Police</h1>
            <ol class="breadcrumb">
              <li class="breadcrumb-item"><a href="./">Accueil</a></li>
              <li class="breadcrumb-item">Types de Police</li>
              <li class="breadcrumb-item active" aria-current="page">Ajouter un Type</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">
                          <i class="fas fa-check-circle"></i> <?php echo $success; ?>
                      </div>
                  <?php endif; ?>

                  <?php if (!empty($errors['general'])): ?>
                      <div class="alert alert-danger">
                          <i class="fas fa-exclamation-triangle"></i> <?php echo $errors['general']; ?>
                      </div>
                  <?php endif; ?>                  <form method="POST" action="add_policy_type.php">
                      <div class="form-group">
                          <label for="type">Type de Police</label>
                          <input type="text" class="form-control" id="type" name="type" required 
                                 value="<?php if(!empty($type)){echo htmlspecialchars($type);} ?>"
                                 placeholder="Exemple: AUTOMOBILE, MOTO, TRANSPORT MARCHANDISES...">
                          <?php if ($errors['type']): ?>
                              <small class="text-danger"><?php echo $errors['type']; ?></small>
                          <?php endif; ?>
                      </div>

                      <div class="form-group">
                          <label class="font-weight-bold">Type de Risque</label>
                          <div class="row">
                              <div class="col-md-6">
                                  <div class="form-check">
                                      <input class="form-check-input" type="radio" name="risque" id="risque_v" value="V" 
                                             <?php if(!empty($risque) && $risque === 'V') echo 'checked'; ?> required>
                                      <label class="form-check-label font-weight-bold text-primary" for="risque_v">
                                          <i class="fas fa-car mr-2"></i>Assurance Véhicule (V)
                                      </label>
                                  </div>
                              </div>
                              <div class="col-md-6">
                                  <div class="form-check">
                                      <input class="form-check-input" type="radio" name="risque" id="risque_rd" value="RD"
                                             <?php if(!empty($risque) && $risque === 'RD') echo 'checked'; ?> required>
                                      <label class="form-check-label font-weight-bold text-info" for="risque_rd">
                                          <i class="fas fa-shield-alt mr-2"></i>Risque Divers (RD)
                                      </label>
                                  </div>
                              </div>
                          </div>
                          <?php if ($errors['risque']): ?>
                              <small class="text-danger"><?php echo $errors['risque']; ?></small>
                          <?php endif; ?>
                      </div>

                      <div class="d-flex justify-content-between">
                          <button type="submit" class="btn btn-primary">
                              <i class="fas fa-plus"></i> Ajouter
                          </button>
                          <a href="policy_types_table.php" class="btn btn-secondary">
                              <i class="fas fa-list"></i> 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>Type de Police :</strong> Saisissez le nom du type de police (sera automatiquement converti en majuscules)</li>
                  </ul>
                  
                  <div class="alert alert-info mt-3">
                    <strong><i class="fas fa-info-circle"></i> Note :</strong> Chaque type de police doit être unique. Vous ne pouvez pas ajouter deux fois le même type.
                  </div>

                  <h6 class="font-weight-bold mt-3">Exemples de saisie :</h6>
                  <div class="table-responsive">
                    <table class="table table-sm table-striped">
                      <thead class="thead-light">
                        <tr>
                          <th>Type de Police</th>
                          <th>Description</th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr>
                          <td><span class="badge badge-primary">AUTOMOBILE</span></td>
                          <td>Assurance pour véhicules particuliers</td>
                        </tr>
                        <tr>
                          <td><span class="badge badge-success">MOTO</span></td>
                          <td>Assurance pour motocycles</td>
                        </tr>
                        <tr>
                          <td><span class="badge badge-warning">TRANSPORT MARCHANDISES</span></td>
                          <td>Assurance pour camions et poids lourds</td>
                        </tr>
                        <tr>
                          <td><span class="badge badge-info">TRANSPORT VOYAGEURS</span></td>
                          <td>Assurance pour bus et cars</td>
                        </tr>
                        <tr>
                          <td><span class="badge badge-secondary">HABITATION</span></td>
                          <td>Assurance pour logements</td>
                        </tr>
                      </tbody>
                    </table>
                  </div>

                  <div class="alert alert-warning mt-3">
                    <strong><i class="fas fa-exclamation-circle"></i> Important :</strong> 
                    Les types de police sont utilisés dans les nouvelles polices d'assurance. 
                    Assurez-vous de bien nommer vos types pour faciliter la gestion ultérieure.
                  </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() {
        // Conversion automatique en majuscules
        $('#type').on('input', function() {
            this.value = this.value.toUpperCase();
        });
    });
  </script>

</body>

</html>
