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

// Initialize variables
$errors = [
    'type' => '',
    'risque' => ''
];
$success = "";
$typeData = null;

// Get the type ID from URL
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
    $typeId = $_GET['id'];
    
    // Fetch existing type data
    $query = "SELECT id, type, risque FROM policy_type WHERE id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $typeId);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $typeData = $result->fetch_assoc();
    } else {
        header("Location: policy_types_table.php");
        exit;
    }
    $stmt->close();
} else {
    header("Location: policy_types_table.php");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $newType = strtoupper(trim($_POST['type']));
    $newRisque = trim($_POST['risque']);
    $oldType = $typeData['type'];
    $oldRisque = $typeData['risque'];

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

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

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

    // Update the type if no validation errors
    if (!array_filter($errors)) {
        $updateQuery = "UPDATE policy_type SET type = ?, risque = ? WHERE id = ?";
        $updateStmt = $conn->prepare($updateQuery);
        $updateStmt->bind_param("ssi", $newType, $newRisque, $typeId);

        if ($updateStmt->execute()) {
            // Enregistrer la modification du type de police dans le log global
            if ($newType !== $oldType || $newRisque !== $oldRisque) {
                logPolicyTypeEdit($oldType, $newType);
            }
            
            $success = "Type de police modifié avec succès.";
            // Update local data
            $typeData['type'] = $newType;
            $typeData['risque'] = $newRisque;
        } else {
            $errors['general'] = "Erreur lors de la modification du type de police.";
        }

        $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 un Type de Police</h1>
            <ol class="breadcrumb">
              <li class="breadcrumb-item"><a href="./">Accueil</a></li>
              <li class="breadcrumb-item"><a href="policy_types_table.php">Types de Police</a></li>
              <li class="breadcrumb-item active" aria-current="page">Modifier</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"></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="edit_policy_type.php?id=<?php echo $typeData['id']; ?>">
                      <div class="form-group">
                          <label for="type">Type de Police</label>
                          <input type="text" class="form-control" id="type" name="type" required 
                                 value="<?php echo htmlspecialchars($typeData['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($typeData['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($typeData['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-save"></i> Enregistrer les modifications
                          </button>
                          <a href="policy_types_table.php" class="btn btn-secondary">
                              <i class="fas fa-arrow-left"></i> Retour à 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">Informations</h6>
                </div>                <div class="card-body">
                  <h6 class="font-weight-bold">Type de police actuel :</h6>
                  <div class="alert alert-info">
                    <span class="badge badge-primary px-3 py-2 h5">
                      <?php echo htmlspecialchars($typeData['type']); ?>
                    </span>
                    <br><br>
                    <span class="badge badge-<?php echo ($typeData['risque'] === 'V') ? 'success' : 'info'; ?> px-3 py-2">
                      <?php echo ($typeData['risque'] === 'V') ? 'Assurance Véhicule (V)' : 'Risque Divers (RD)'; ?>
                    </span>
                  </div>
                  
                  <div class="alert alert-warning mt-3">
                    <strong><i class="fas fa-exclamation-triangle"></i> Attention :</strong> 
                    La modification de ce type de police affectera toutes les polices existantes qui l'utilisent.
                  </div>

                  <h6 class="font-weight-bold mt-3">Conseils :</h6>
                  <ul>
                    <li>Le texte sera automatiquement converti en majuscules</li>
                    <li>Assurez-vous que le nouveau nom est explicite</li>
                    <li>Évitez les noms trop longs ou complexes</li>
                    <li>Vérifiez qu'aucun type similaire n'existe déjà</li>
                  </ul>
                </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>
