<?php
ini_set('display_errors', 0);
error_reporting(0);

require_once __DIR__ . '/../../models/Database.php';
use Models\Database;
$pdo = Database::getInstance()->getConnection();
//$socials = $pdo->query("SELECT * FROM social_settings")->fetchAll();
//$employees = $pdo->query("SELECT id, CONCAT(first_name, ' ', last_name) AS full_name FROM employees ORDER BY last_name")->fetchAll();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <title>Créer une fiche de paie</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/plugins/monthSelect/style.css">
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="container mt-5">
  <h2>Créer une fiche de paie</h2>
  <form id="payslipForm">

    <div class="row mb-3">
      <div class="col">
        <label>Employé</label>
        <select name="employee_id" id="employee_id" class="form-select" required>
          <option value="">-- Sélectionnez --</option>
          <?php foreach ($employees as $e): ?>
            <option value="<?= $e['id'] ?>"><?= htmlspecialchars($e['full_name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col">
        <label>Période</label>
        <input type="text" id="period" name="period" class="form-control">
      </div>
      <div class="col">
        <label>Salaire brut (€)</label>
        <input type="number" step="0.01" id="gross_salary" name="gross_salary" class="form-control">
      </div>
      <h5>Avantages en nature</h5>
        <table class="table" id="benefits-table"><tbody></tbody></table>
        <label>Total avantages en nature (€)</label>
        <input type="text" id="total_benefits" class="form-control mb-4" readonly placeholder="Total avantages en nature (€)">
        <label>Brut total (€)</label>
        <input type="text" id="total_gross" class="form-control mb-4" readonly placeholder="Brut total (€)">
    </div>

    <h5>Cotisations sociales</h5>
    <table class="table table-bordered">
      <thead><tr><th>Libellé</th><th>Base</th><th>Taux</th><th>Montant</th></tr></thead>
      <tbody>
      <?php foreach ($cotisations as $s): ?>
        <tr>
          <td><?= $s['label'] ?></td>
          <td><input type="text" readonly class="form-control base-amount" data-base="<?= $s['gross_base'] ?>"></td>
          <td><?= $s['rate'] ?>%</td>
          <td><input type="text" readonly class="form-control social-amount" data-label="<?= $s['keyname'] ?>" data-base="<?= $s['gross_base'] ?>" data-rate="<?= $s['rate'] ?>"></td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
    <label>Total cotisations</label>
    <input type="text" id="social_charges" class="form-control mb-4" readonly placeholder="Total cotisations (€)">

    <h5>Abattements</h5>
    <table class="table" id="abattements-table"><tbody></tbody></table>
    <input type="text" id="total_abattements" class="form-control mb-4" readonly placeholder="Total abattements (€)">

    <label>Net avant impôts</label>
    <input type="text" id="net_avant_impot" class="form-control mb-4" readonly placeholder="Net avant impôts (€)">

    <label>Imposable</label>
    <input type="text" id="imposable" class="form-control mb-4" readonly placeholder="Imposable (€)">

    <div class="row mb-3">
      <div class="col">
        <label>Taux d’imposition (%)</label>
        <input type="number" step="0.01" name="taux_impot" id="taux_impot" class="form-control" readonly>
      </div>
      <div class="col">
        <label>Impôt (€)</label>
        <input type="text" id="montant_impot" class="form-control" readonly>
      </div>
    </div>
    <h5>Crédits d'impôt</h5>
    <div class="row mb-3">
      <div class="col">
        <label>Crédit d’impôt salarié (CIS)</label>
        <input type="text" id="cis" name="cis" class="form-control mb-4" readonly placeholder="CIS (€)">
      </div>
      <div class="col">
        <label>Crédit d’impôt climat (CO2)</label>
        <input type="text" id="co2" name="co2" class="form-control mb-4" readonly placeholder="CO2 (€)">
      </div>
    </div>
    <label>Net après impôt</label>
    <input type="text" id="net_apres_impot" class="form-control mb-4" readonly placeholder="Net après impôt (€)">
        <!-- AJOUTS -->
    <h5>Ajouts au net</h5>
    <div id="plus-container" class="mb-3"></div>
    <button type="button" class="btn btn-success mb-3" onclick="addPlus()">+ Ajouter un ajout</button>
    <input type="text" id="total_plus" class="form-control mb-4" readonly placeholder="Total ajouts (€)">

    <!-- DÉDUCTIONS -->
    <h5>Déductions du net</h5>
    <div id="minus-container" class="mb-3"></div>
    <button type="button" class="btn btn-danger mb-3" onclick="addMinus()">+ Ajouter une déduction</button>
    <input type="text" id="total_minus" class="form-control mb-4" readonly placeholder="Total déductions (€)">
    
    <!-- NET FINAL -->
    <input type="text" id="net_final" class="form-control" readonly placeholder="Net à payer final (€)">    
    <button type="submit" class="btn btn-primary">Enregistrer</button>
  </form>
</div>
<script>
$('#employee_id').on('change', function () {
  const id = $(this).val();
  if (!id) return;

  $('#employee_id, #period').on('change', function () {
      const employeeId = $('#employee_id').val();
      const period = $('#period').val();

      if (!employeeId || !period) return;

      $.getJSON('/public/api/check_unvalidated.php', { employee_id: employeeId }, function (data) {
          if (data.has_unvalidated) {
              alert("Cet employé a déjà des bulletins non validés. Veuillez les valider avant d'en créer un nouveau.");
              window.location.href = '/payslips';
          }
      });
  });

  $.getJSON('/public/api/get_employee_salary.php?id=' + id, function (d) {
    $('#gross_salary').val(d.gross_salary || 0);
    calculateSocial();
  });

  $.getJSON('/public/api/get_benefits.php?employee_id=' + id, function (a) {
    let total = 0;
    $('#benefits-table tbody').empty();
    a.forEach(row => {
      $('#benefits-table tbody').append(`<tr><td>${row.keyname}</td><td>${row.label}</td><td>${row.amount}</td></tr>`);
      total += parseFloat(row.amount);
    });
    $('#total_benefits').val(total.toFixed(2));
    $('#total_gross').val(parseFloat($('#gross_salary').val()) + parseFloat($('#total_benefits').val()));
    calculateImposable();
  });

  $.getJSON('/public/api/get_abattements.php?employee_id=' + id, function (a) {
    let total = 0;
    $('#abattements-table tbody').empty();
    a.forEach(row => {
      $('#abattements-table tbody').append(`<tr><td>${row.keyname}</td><td>${row.label}</td><td>${row.amount}</td></tr>`);
      total += parseFloat(row.amount);
    });
    $('#total_abattements').val(total.toFixed(2));
    calculateImposable();
  });

  $.getJSON('/public/api/get_taux_impot.php?employee_id=' + id, function (d) {
    $('#taux_impot').val(d.taux_impot);
    calculateImpot();
  });

  $.getJSON('/public/api/get_tax_credits.php?id=' + id, function (d) {
    $('#cis').val(d.cis || 0);
    $('#co2').val(d.co2 || 0);

  });
});

$('#gross_salary').on('input', calculateSocial);

/* function calculateSocial() {
  const g = parseFloat($('#gross_salary').val()) || 0;
  let total = 0;

  $('.social-amount').each(function () {
    const base = parseFloat($(this).data('base')) || 0;
    const rate = parseFloat($(this).data('rate')) || 0;
    const baseAmount = g * base / 100;
    const amount = baseAmount * rate / 100;
    $(this).val(amount.toFixed(2));
    $(this).closest('tr').find('.base-amount').val(baseAmount.toFixed(2));
    total += amount;
  });

  $('#social_charges').val(total.toFixed(2));
  calculateImposable();
} */
function calculateSocial() {
  const g = parseFloat($('#gross_salary').val()) || 0;
    // 🔄 Récupérer la franchise avant le calcul
  $.getJSON('/public/api/get_franchise.php', function (data) {
    const franchise = parseFloat(data.franchise) || 659.45;
    const b = parseFloat($('#total_benefits').val()) || 0;
    //const gt = g + b;
    let total = 0;

    $('.social-amount').each(function () {
      const label = $(this).data('label');
      const basePercent = parseFloat($(this).data('base')) || 0;
      const rate = parseFloat($(this).data('rate')) || 0;

      let baseAmount = (g + b) * basePercent / 100;
      // ✅ C.ME ne prend pas en compte les avantaves en nature
      if (label === 'C.ME') {
        baseAmount = g * basePercent / 100;
      }
      // ✅ Appliquer la franchise uniquement à la cotisation S.D
      if (label === 'S.D') {
        baseAmount = Math.max(0, baseAmount - franchise);
      }

      const amount = baseAmount * rate / 100;

      $(this).val(amount.toFixed(2));
      $(this).closest('tr').find('.base-amount').val(baseAmount.toFixed(2));

      total += amount;
    });
    let net_avant_impot = g + b - total;
    $('#social_charges').val(total.toFixed(2));
    $('#net_avant_impot').val((net_avant_impot).toFixed(2));
    calculateImposable();
  });
}


function calculateImposable() {
  const g = parseFloat($('#gross_salary').val()) || 0;
  const b = parseFloat($('#total_benefits').val()) || 0;
  const c = parseFloat($('#social_charges').val()) || 0;
  const a = parseFloat($('#total_abattements').val()) || 0;
  const n = parseFloat($('#net_avant_impot').val()) || 0;
  $('#total_gross').val(g + b);
  $('#imposable').val((n - a).toFixed(2));

  calculateImpot();
}

function calculateImpot() {
  const imp = parseFloat($('#imposable').val()) || 0;
  const taux = parseFloat($('#taux_impot').val()) || 0;
  const impots = imp * (taux / 100);
  $('#montant_impot').val(impots.toFixed(2));
  const gross = parseFloat($('#total_gross').val()) || 0;
  const cotisations = parseFloat($('#social_charges').val()) || 0;
  const cis = parseFloat($('#cis').val()) || 0;
  const co2 = parseFloat($('#co2').val()) || 0;
  const net = gross - cotisations - impots + cis + co2;
  $('#net_apres_impot').val(net.toFixed(2)); calculateFinalNet();
}

function addPlus() {
  $('#plus-container').append(`<div class="row mb-2">
    <div class="col"><input type="text" class="form-control plus-label" placeholder="Libellé"></div>
    <div class="col"><input type="number" step="0.01" class="form-control plus-value" value="0" oninput="calculateFinalNet()"></div>
  </div>`);
}

function addMinus() {
  $('#minus-container').append(`<div class="row mb-2">
    <div class="col"><input type="text" class="form-control minus-label" placeholder="Libellé"></div>
    <div class="col"><input type="number" step="0.01" class="form-control minus-value" value="0" oninput="calculateFinalNet()"></div>
  </div>`);
}

function calculateFinalNet() {
  const net = parseFloat($('#net_apres_impot').val()) || 0;
  let plus = 0, minus = 0;

  $('.plus-value').each(function () {
    plus += parseFloat($(this).val()) || 0;
  });

  $('.minus-value').each(function () {
    minus += parseFloat($(this).val()) || 0;
  });

  $('#total_plus').val(plus.toFixed(2));
  $('#total_minus').val(minus.toFixed(2));

  const final = net + plus - minus;
  $('#net_final').val(final.toFixed(2));
}
document.getElementById('payslipForm').addEventListener('submit', function (e) {
  e.preventDefault();

  const data = {
    employee_id: parseInt(document.getElementById('employee_id').value),
    period: document.getElementById('period').value,
    gross_salary: parseFloat(document.getElementById('gross_salary').value) || 0,
    benefits: parseFloat(document.getElementById('total_benefits').value) || 0,
    total_gross: parseFloat(document.getElementById('total_gross').value) || 0,
    social_charges: parseFloat(document.getElementById('social_charges').value) || 0,
    salaire_imposable: parseFloat(document.getElementById('imposable').value) || 0,
    taux_impot: parseFloat(document.getElementById('taux_impot').value) || 0,
    montant_impot: parseFloat(document.getElementById('montant_impot').value) || 0,
    cis: parseFloat(document.getElementById('cis').value) || 0,
    co2: parseFloat(document.getElementById('co2').value) || 0,
    net_apres_impot: parseFloat(document.getElementById('net_apres_impot').value) || 0
  };

  
  // Préparer les données additionnelles
  data.moderation_lines = [];
  document.querySelectorAll('#abattements-table tbody tr').forEach(row => {
    const label = row.cells[0].textContent.trim();
    const amount = parseFloat(row.cells[2].textContent) || 0;
    const key = label.match(/\b[A-Z]{2,4}\b/) ? label.match(/\b[A-Z]{2,4}\b/)[0] : label.substring(0, 3).toUpperCase();
    data.moderation_lines.push({ key, label, amount });
  });

  data.social_lines = [{
    cm_rate: parseFloat(document.querySelector('.social-amount[data-label="C.M"]').dataset.rate) || 0,
    cm_amount: parseFloat(document.querySelector('.social-amount[data-label="C.M"]').value) || 0,
    cme_rate: parseFloat(document.querySelector('.social-amount[data-label="C.ME"]').dataset.rate) || 0,
    cme_amount: parseFloat(document.querySelector('.social-amount[data-label="C.ME"]').value) || 0,
    cp_rate: parseFloat(document.querySelector('.social-amount[data-label="C.P"]').dataset.rate) || 0,
    cp_amount: parseFloat(document.querySelector('.social-amount[data-label="C.P"]').value) || 0,
    sd_rate: parseFloat(document.querySelector('.social-amount[data-label="S.D"]').dataset.rate) || 0,
    sd_amount: parseFloat(document.querySelector('.social-amount[data-label="S.D"]').value) || 0
  }];

  data.plus = [];
  document.querySelectorAll('.plus-label').forEach((input, i) => {
    const label = input.value.trim();
    const amount = parseFloat(document.querySelectorAll('.plus-value')[i].value) || 0;
    if (label && amount !== 0) data.plus.push({ label, amount });
  });

  data.minus = [];
  document.querySelectorAll('.minus-label').forEach((input, i) => {
    const label = input.value.trim();
    const amount = parseFloat(document.querySelectorAll('.minus-value')[i].value) || 0;
    if (label && amount !== 0) data.minus.push({ label, amount: -amount });
  });

  fetch('/public/api/store_payslip.php', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest'
    },
    body: JSON.stringify(data)
})
.then(response => {
    // Vérifie d'abord le statut HTTP
    if (!response.ok) {
        return response.text().then(text => {
            throw new Error(`Erreur HTTP ${response.status}: ${text}`);
        });
    }
    return response.json();
})
.then(data => {
    if (!data.success) {
        throw new Error(data.error || "Erreur inconnue");
    }
    window.location.href = `/payslips/show?id=${data.payslip_id}`;
})
.catch(error => {
    console.error('Erreur complète:', error);
    alert(error.message.includes('HTTP') 
        ? error.message 
        : 'Erreur technique. Voir console (F12)');
});
  

});

</script>
<!-- ✅ Flatpickr scripts -->
<script src="https://cdn.jsdelivr.net/npm/flatpickr@4.6.13/dist/flatpickr.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/flatpickr@4.6.13/dist/l10n/fr.js"></script>
<script src="https://cdn.jsdelivr.net/npm/flatpickr@4.6.13/dist/plugins/monthSelect/index.js"></script>

<script>
document.addEventListener('DOMContentLoaded', () => {
    // Création du locale personnalisé
    const frMajuscule = {
        ...flatpickr.l10ns.fr,  // On étend la locale française existante
        months: {
            shorthand: [
                "Jan", "Fév", "Mar", "Avr", "Mai", "Juin",
                "Juil", "Août", "Sep", "Oct", "Nov", "Déc"
            ],
            longhand: [
                "Janvier", "Février", "Mars", "Avril", "Mai", "Juin",
                "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"
            ]
        }
    };

    // Initialisation de flatpickr
    flatpickr("#period", {
        locale: frMajuscule,
        plugins: [new monthSelectPlugin({ 
            shorthand: false, 
            dateFormat: "F Y", 
            altFormat: "F Y"
        })],
        disableMobile: true // Option recommandée pour éviter les problèmes sur mobile
    });
});
/*
document.addEventListener('DOMContentLoaded', () => {
    flatpickr("#period", {
        locale: flatpickr.l10ns.fr,
        plugins: [
            new monthSelectPlugin({
                shorthand: false,
                dateFormat: "F Y",
                altFormat: "F Y",
                theme: "light"
            })
        ]
    });
});
*/
</script>
</body>
</html>