<?php
// Activer les erreurs (uniquement en développement)
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Charger la configuration
require_once '../src/includes/config.php';

// Démarrer la session pour les messages d'erreur
//session_start();

// Générer un numéro de dossier unique
$numero_dossier = genererNumeroDossier('ethique');

// Récupérer les types de situation depuis la base de données
try {
    $sql = "SELECT id, libelle FROM types_situation WHERE dossier_type_id = 1 AND actif = 1 AND id != 1 ORDER BY id";
    $stmt = $pdo->query($sql);
    $types_situation = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    // Fallback si la table n'existe pas
    $types_situation = [
        ['id' => 2, 'libelle' => 'Harcèlement moral ou sexuel'],
        ['id' => 3, 'libelle' => 'Fraude / Détournement de fonds'],
        ['id' => 4, 'libelle' => 'Conflit d\'intérêts'],
        ['id' => 5, 'libelle' => 'Violation de la sécurité ou des procédures'],
        ['id' => 6, 'libelle' => 'Discrimination'],
        ['id' => 7, 'libelle' => 'Autre comportement non éthique']
    ];
    error_log("Erreur chargement types situation: " . $e->getMessage());
}

// Récupérer les données du formulaire en cas d'erreur
$form_data = $_SESSION['form_data'] ?? [];
$form_errors = $_SESSION['form_errors'] ?? [];

// Nettoyer les données de session après utilisation
unset($_SESSION['form_data']);
unset($_SESSION['form_errors']);
?>

<!-- Inclure le header -->
<?php include 'header.php'; ?>

<div class="container py-5">
  <div class="row justify-content-center">
    <div class="col-lg-9 col-xl-8">
      
      <!-- En-tête du formulaire -->
      <div class="text-center mb-5">
        <div class="modern-icon mb-4">
          <div class="icon-wrapper">
            <i class="fas fa-shield-alt"></i>
          </div>
        </div>
        <h1 class="display-6 fw-bold text-dark mb-3">Signaler un fait non éthique</h1>
        <p class="lead text-muted mb-4">
          Votre identité est protégée. Communication 100% anonyme et sécurisée
        </p>
        <div class="dossier-number">
          <span class="dossier-badge">
            <i class="fas fa-hashtag me-2"></i>
            <?= htmlspecialchars($numero_dossier) ?>
          </span>
        </div>
      </div>

      <!-- Affichage des erreurs -->
      <?php if (!empty($form_errors)): ?>
        <div class="alert-modern alert-error">
          <div class="alert-icon">
            <i class="fas fa-exclamation-circle"></i>
          </div>
          <div class="alert-content">
            <h5 class="alert-title">Erreurs à corriger</h5>
            <ul class="alert-list">
              <?php foreach ($form_errors as $error): ?>
                <li><?= htmlspecialchars($error) ?></li>
              <?php endforeach; ?>
            </ul>
          </div>
        </div>
      <?php endif; ?>

      <!-- Formulaire -->
      <div class="modern-card">
        <div class="card-body p-5">
          <form action="save_signalement.php" method="POST" enctype="multipart/form-data" id="formSignalement" class="needs-validation" novalidate>
            
            <!-- Numéro de dossier (caché) -->
            <input type="hidden" name="numero_dossier" value="<?= htmlspecialchars($numero_dossier) ?>">

            <!-- Type de situation -->
            <div class="form-modern mb-4">
              <label for="type_situation_id" class="form-label">
                <span class="label-text">Type de situation</span>
                <span class="required">*</span>
              </label>
              <div class="input-wrapper">
                <i class="input-icon fas fa-list-alt"></i>
                <select name="type_situation_id" id="type_situation_id" class="form-control" required>
                  <option value="" disabled selected>Choisissez une catégorie</option>
                  <?php foreach ($types_situation as $type): ?>
                    <option value="<?= $type['id'] ?>" 
                      <?= (isset($form_data['type_situation_id']) && $form_data['type_situation_id'] == $type['id']) ? 'selected' : '' ?>>
                      <?= htmlspecialchars($type['libelle']) ?>
                    </option>
                  <?php endforeach; ?>
                </select>
              </div>
              <div class="invalid-feedback">Veuillez sélectionner un type de situation.</div>
            </div>

            <!-- Lieu des faits -->
            <div class="form-modern mb-4">
              <label for="lieu" class="form-label">
                <span class="label-text">Lieu des faits</span>
                <span class="required">*</span>
              </label>
              <div class="input-wrapper">
                <i class="input-icon fas fa-map-marker-alt"></i>
                <input type="text" name="lieu" id="lieu" class="form-control" 
                       placeholder="Ex: Siège social, Site de production Lyon..." 
                       value="<?= htmlspecialchars($form_data['lieu'] ?? '') ?>" 
                       required>
              </div>
              <div class="invalid-feedback">Veuillez préciser le lieu des faits.</div>
            </div>

            <!-- Description détaillée -->
            <div class="form-modern mb-4">
              <label for="description" class="form-label">
                <span class="label-text">Description détaillée</span>
                <span class="required">*</span>
              </label>
              <div class="input-wrapper">
                <i class="input-icon fas fa-align-left"></i>
                <textarea name="description" id="description" class="form-control" 
                          rows="6" 
                          placeholder="Décrivez les faits avec précision (qui, quoi, quand, où, comment)..." 
                          required><?= htmlspecialchars($form_data['description'] ?? '') ?></textarea>
              </div>
              <div class="form-text">
                <i class="fas fa-info-circle me-1"></i>
                Soyez factuel et détaillé pour faciliter le traitement
              </div>
              <div class="invalid-feedback">Veuillez fournir une description détaillée.</div>
            </div>

            <!-- Pièce jointe -->
            <div class="form-modern mb-4">
              <label for="fichier" class="form-label">
                <span class="label-text">Pièce jointe</span>
                <span class="optional">(facultatif)</span>
              </label>
              <div class="file-upload-wrapper">
                <input type="file" name="fichier" id="fichier" class="file-input" 
                       accept=".pdf,.jpg,.jpeg,.png,.doc,.docx,.mp3,.wav">
                <label for="fichier" class="file-label">
                  <i class="fas fa-cloud-upload-alt me-2"></i>
                  <span class="file-text">Choisir un fichier</span>
                  <span class="file-hint">PDF, images, audio, documents • Max 10 Mo</span>
                </label>
              </div>
            </div>

            <!-- Bouton de soumission -->
            <div class="form-modern mt-5">
              <button type="submit" class="btn-submit">
                <span class="btn-content">
                  <i class="fas fa-paper-plane me-2"></i>Envoyer le signalement
                </span>
                <div class="btn-loading">
                  <i class="fas fa-spinner fa-spin"></i>
                </div>
              </button>
            </div>

          </form>
        </div>
      </div>

      <!-- Informations de confidentialité -->
      <div class="modern-info mt-4">
        <div class="info-content">
          <i class="fas fa-user-shield info-icon"></i>
          <div class="info-text">
            <strong>Protection garantie</strong>
            <span>Votre signalement est entièrement anonyme et sécurisé</span>
          </div>
        </div>
      </div>

    </div>
  </div>
</div>

<style>
:root {
  --ci-orange: #F36F21;
  --ci-green: #84BD00;
  --ci-dark: #2C2C2C;
  --ci-light: #F8F9FA;
  --ci-border: #E1E5E9;
  --ci-shadow: 0 8px 30px rgba(0, 0, 0, 0.08);
  --ci-radius: 12px;
  --ci-transition: all 0.3s ease;
}

.modern-icon {
  display: flex;
  justify-content: center;
}

.icon-wrapper {
  width: 80px;
  height: 80px;
  background: linear-gradient(135deg, var(--ci-orange) 0%, #FF8C42 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: var(--ci-shadow);
}

.icon-wrapper i {
  font-size: 2rem;
  color: white;
}

.display-6 {
  font-size: 2.5rem;
  font-weight: 800;
}

.lead {
  font-size: 1.25rem;
  font-weight: 400;
}

.dossier-badge {
  display: inline-block;
  background: var(--ci-light);
  border: 2px dashed var(--ci-orange);
  border-radius: 50px;
  padding: 12px 24px;
  font-weight: 600;
  color: var(--ci-dark);
  font-size: 1.1rem;
}

.modern-card {
  background: white;
  border-radius: var(--ci-radius);
  box-shadow: var(--ci-shadow);
  border: none;
  overflow: hidden;
}

.form-modern {
  position: relative;
}

.form-label {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  font-weight: 600;
  color: var(--ci-dark);
  font-size: 1rem;
}

.label-text {
  margin-right: 4px;
}

.required {
  color: #dc3545;
}

.optional {
  color: #6c757d;
  font-weight: 400;
  font-size: 0.9rem;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.input-icon {
  position: absolute;
  left: 16px;
  color: var(--ci-orange);
  z-index: 2;
  font-size: 1.1rem;
}

.form-control {
  width: 100%;
  padding: 16px 16px 16px 48px;
  border: 2px solid var(--ci-border);
  border-radius: var(--ci-radius);
  font-size: 1rem;
  transition: var(--ci-transition);
  background: white;
}

.form-control:focus {
  border-color: var(--ci-orange);
  box-shadow: 0 0 0 4px rgba(243, 111, 33, 0.1);
  outline: none;
}

select.form-control {
  appearance: none;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='%23F36F21' viewBox='0 0 16 16'%3E%3Cpath d='M7.247 11.14 2.451 5.658C1.885 5.013 2.345 4 3.204 4h9.592a1 1 0 0 1 .753 1.659l-4.796 5.48a1 1 0 0 1-1.506 0z'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: right 16px center;
  padding-right: 48px;
}

textarea.form-control {
  resize: vertical;
  min-height: 120px;
}

.form-text {
  margin-top: 8px;
  color: #6c757d;
  font-size: 0.875rem;
}

.file-upload-wrapper {
  position: relative;
}

.file-input {
  position: absolute;
  opacity: 0;
  width: 0;
  height: 0;
}

.file-label {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 32px;
  border: 2px dashed var(--ci-border);
  border-radius: var(--ci-radius);
  background: var(--ci-light);
  cursor: pointer;
  transition: var(--ci-transition);
  text-align: center;
}

.file-label:hover {
  border-color: var(--ci-orange);
  background: rgba(243, 111, 33, 0.05);
}

.file-text {
  font-weight: 600;
  color: var(--ci-dark);
  margin-bottom: 8px;
}

.file-hint {
  font-size: 0.875rem;
  color: #6c757d;
}

.btn-submit {
  width: 100%;
  background: linear-gradient(135deg, var(--ci-orange) 0%, #FF8C42 100%);
  border: none;
  border-radius: var(--ci-radius);
  padding: 20px;
  color: white;
  font-weight: 700;
  font-size: 1.1rem;
  transition: var(--ci-transition);
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.btn-submit:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 25px rgba(243, 111, 33, 0.3);
}

.btn-loading {
  display: none;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.btn-submit.loading .btn-content {
  opacity: 0;
}

.btn-submit.loading .btn-loading {
  display: block;
}

.alert-modern {
  display: flex;
  align-items: flex-start;
  padding: 20px;
  border-radius: var(--ci-radius);
  margin-bottom: 24px;
  background: #fff5f5;
  border-left: 4px solid #e53e3e;
}

.alert-error {
  background: #fff5f5;
  border-left-color: #e53e3e;
}

.alert-icon {
  margin-right: 12px;
  color: #e53e3e;
  font-size: 1.2rem;
}

.alert-title {
  margin: 0 0 8px 0;
  color: #c53030;
  font-size: 1rem;
}

.alert-list {
  margin: 0;
  padding-left: 20px;
  color: #742a2a;
}

.modern-info {
  background: linear-gradient(135deg, #f8fff0 0%, #f0f9ff 100%);
  border-radius: var(--ci-radius);
  padding: 20px;
  border: 1px solid #e1f5e1;
}

.info-content {
  display: flex;
  align-items: center;
  justify-content: center;
}

.info-icon {
  font-size: 1.5rem;
  color: var(--ci-green);
  margin-right: 12px;
}

.info-text {
  display: flex;
  flex-direction: column;
}

.info-text strong {
  color: var(--ci-dark);
  font-size: 0.9rem;
}

.info-text span {
  color: #6c757d;
  font-size: 0.85rem;
}

.invalid-feedback {
  color: #dc3545;
  font-size: 0.875rem;
  margin-top: 6px;
}

.was-validated .form-control:invalid {
  border-color: #dc3545;
}

@media (max-width: 768px) {
  .container {
    padding: 1rem;
  }
  
  .card-body {
    padding: 2rem !important;
  }
  
  .display-6 {
    font-size: 2rem;
  }
  
  .lead {
    font-size: 1.1rem;
  }
  
  .icon-wrapper {
    width: 70px;
    height: 70px;
  }
  
  .icon-wrapper i {
    font-size: 1.7rem;
  }
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
  const form = document.getElementById('formSignalement');
  const fileInput = document.getElementById('fichier');
  const fileLabel = document.querySelector('.file-label');
  const fileText = document.querySelector('.file-text');
  const submitBtn = document.querySelector('.btn-submit');
  
  // Gestion de l'affichage du nom du fichier
  if (fileInput) {
    fileInput.addEventListener('change', function() {
      if (this.files && this.files[0]) {
        fileText.textContent = this.files[0].name;
      } else {
        fileText.textContent = 'Choisir un fichier';
      }
    });
  }
  
  // Gestion de la soumission du formulaire
  form.addEventListener('submit', function(event) {
    if (!form.checkValidity()) {
      event.preventDefault();
      event.stopPropagation();
    } else {
      // Ajouter la classe de chargement au bouton
      submitBtn.classList.add('loading');
      submitBtn.disabled = true;
    }
    
    form.classList.add('was-validated');
  }, false);
});
</script>

<!-- Inclure le footer -->
<?php include 'footer.php'; ?>