<?php
require_once __DIR__ . '/../../models/Database.php';
use Models\Database;
$pdo = Database::getInstance()->getConnection();
$socials = $pdo->query("SELECT * FROM social_settings")->fetchAll();
$pdo = Database::getInstance()->getConnection();
$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>
  <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">
  <meta charset="UTF-8">
  <title>Créer une fiche de paie</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <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">

    <!-- Brut, Cotisations, Abattements -->
    <div class="row mb-3">
      <div class="col"><label for="employee_id" class="form-label">Employé</label>
        <select name="employee_id" id="employee_id" class="form-select" required>
          <option value="">-- Sélectionnez un employé --</option>
          <?php foreach ($employees as $emp): ?>
            <option value="<?= $emp['id'] ?>"><?= htmlspecialchars($emp['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>
    </div>

    <h5>Cotisations sociales</h5>
    <table class="table table-bordered">
      <thead><tr><th>Description</th><th>Base</th><th>Taux</th><th>Montant</th></tr></thead>
      <tbody>
      <?php foreach ($socials as $s): ?>
        <tr>
          <td><?= $s['value'] ?></td>
          <td><input type="text" readonly class="form-control base-amount" data-base="<?= $s['gross_base'] ?>" value="0"></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'] ?>" value="0"></td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
    <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 (€)">

    <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="text" 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>
    <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="button" class="btn btn-primary" onclick="submitPayslip()">Enregistrer</button>
</form>
</div>

<script>
$(document).ready(function () {
  $('#gross_salary').on('input', calculateSocialCharges);

  $('#employee_id').on('change', function () {
    const id = $(this).val();
    if (!id) return;

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

    $.getJSON('/public/api/get_taux_impot.php', { employee_id: id }, function (d) {
      $('#taux_impot').val(parseFloat(d.taux_impot).toFixed(2)); calculateImpot();
    });
  });
});

function calculateSocialCharges() {
  const g = parseFloat($('#gross_salary').val()) || 0;
  let t = 0;
  $('.base-amount').each(function () {
    const b = g * (parseFloat($(this).data('base')) / 100);
    $(this).val(b.toFixed(2));
  });
  $('.social-amount').each(function () {
    const b = g * (parseFloat($(this).data('base')) / 100);
    const r = parseFloat($(this).data('rate'));
    const a = b * (r / 100);
    $(this).val(a.toFixed(2)); t += a;
  });
  $('#social_charges').val(t.toFixed(2)); calculateImposable();
}

function calculateImposable() {
  const g = parseFloat($('#gross_salary').val()) || 0;
  const c = parseFloat($('#social_charges').val()) || 0;
  const a = parseFloat($('#total_abattements').val()) || 0;
  const imp = g - c - a;
  $('#imposable').val(imp.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($('#gross_salary').val()) || 0;
  const cotisations = parseFloat($('#social_charges').val()) || 0;
  const net = gross - cotisations - impots;
  $('#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));
}


function submitPayslip() {
  const grossSalary = parseFloat(document.getElementById('gross_salary').value);
  const period = document.getElementById('period').value;

  if (isNaN(grossSalary) || grossSalary <= 0) {
    alert("Le salaire brut doit être un nombre strictement supérieur à zéro.");
    return;
  }

  if (!period || period.trim() === '') {
    alert("Veuillez sélectionner une période valide.");
    return;
  }

  // suite du code normalement ici...
 {
  const data = {
    employee_id: $('#employee_id').val(),
    period: $('#period').val(),
    gross_salary: parseFloat($('#gross_salary').val()) || 0,
    social_charges: parseFloat($('#social_charges').val()) || 0,
    total_abattements: parseFloat($('#total_abattements').val()) || 0,
    imposable: parseFloat($('#imposable').val()) || 0,
    taux_impot: parseFloat($('#taux_impot').val()) || 0,
    montant_impot: parseFloat($('#montant_impot').val()) || 0,
    net_apres_impot: parseFloat($('#net_apres_impot').val()) || 0,
    total_plus: parseFloat($('#total_plus').val()) || 0,
    total_minus: parseFloat($('#total_minus').val()) || 0,
    net_final: parseFloat($('#net_final').val()) || 0,
    plus: [],
    minus: []
  };

  $('.plus-label').each(function(i) {
    const label = $(this).val();
    const val = parseFloat($('.plus-value').eq(i).val()) || 0;
    if (label && val !== 0) {
      data.plus.push({ label, amount: val });
    }
  });

  $('.minus-label').each(function(i) {
    const label = $(this).val();
    const val = parseFloat($('.minus-value').eq(i).val()) || 0;
    if (label && val !== 0) {
      data.minus.push({ label, amount: -val }); // négatif ici
    }
  });
  // --- Blocs ajoutés dynamiquement ---

data.moderation_lines = [];
$('#abattements-table tbody tr').each(function () {
  const label = $(this).find('td:first').text();
  const amount = parseFloat($(this).find('td:last').text()) || 0;
  const key = label.match(/\b[A-Z]{2,3}\b/) ? label.match(/\b[A-Z]{2,3}\b/)[0] : label.substring(0, 2).toUpperCase();
  data.moderation_lines.push({ key: key, label: label, amount: amount });
});

data.social_lines = [{
  cm_rate: parseFloat($('.social-amount[data-label="C.M"]').data('rate')) || 0,
  cm_amount: parseFloat($('.social-amount[data-label="C.M"]').val()) || 0,
  cme_rate: parseFloat($('.social-amount[data-label="C.ME"]').data('rate')) || 0,
  cme_amount: parseFloat($('.social-amount[data-label="C.ME"]').val()) || 0,
  cp_rate: parseFloat($('.social-amount[data-label="C.P"]').data('rate')) || 0,
  cp_amount: parseFloat($('.social-amount[data-label="C.P"]').val()) || 0,
  sd_rate: parseFloat($('.social-amount[data-label="S.D"]').data('rate')) || 0,
  sd_amount: parseFloat($('.social-amount[data-label="S.D"]').val()) || 0
}];
  fetch('/public/api/store_payslip.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data)
  })
  .then(res => res.json())
  .then(response => {
    if (response.success) {
      alert('Fiche enregistrée avec succès.');
      window.location.href = '/payslips';//location.reload();
    } else {
      alert('Erreur : ' + response.error);
    }
  })
  .catch(error => {
    alert('Erreur AJAX : ' + error);
  });
}

</script>

  <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
  <script src="https://cdn.jsdelivr.net/npm/flatpickr/dist/plugins/monthSelect/index.js"></script>
  <script>
    flatpickr("#period", {
      dateFormat: "F Y",
      plugins: [
        new monthSelectPlugin({
          shorthand: false,
          dateFormat: "F Y",
          altFormat: "F Y"
        })
      ],
      locale: {
        firstDayOfWeek: 1,
        weekdays: {
          shorthand: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'],
          longhand: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'],
        },
        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'],
        },
      }
    });

    document.addEventListener('DOMContentLoaded', function () {
      const employeeSelect = document.getElementById('employee_id');
      const grossSalaryInput = document.getElementById('gross_salary');

      employeeSelect.addEventListener('change', function () {
        const employeeId = this.value;

        if (employeeId) {
          fetch(`/public/api/get_employee_salary.php?id=${employeeId}`)
            .then(response => response.json())
            .then(data => {
              if (data && data.gross_salary) {
                grossSalaryInput.value = data.gross_salary;

              const salary = parseFloat(grossSalaryInput.value) || 0;
              document.querySelectorAll('.social-amount').forEach(input => {
                const rate = parseFloat(input.dataset.rate) || 0;
                const amount = (salary * rate / 100).toFixed(2);
                input.value = amount;
              });

              } else {
                grossSalaryInput.value = '';
              }

              // Charger les abattements
              fetch(`/public/api/get_abattements.php?employee_id=${employeeId}`)
                .then(res => res.json())
                .then(mods => {
                  const tbody = document.querySelector('#abattements-table tbody');
                  tbody.innerHTML = '';
                  let total = 0;
                  mods.forEach(row => {
                    const tr = document.createElement('tr');
                    tr.innerHTML = `<td>${row.value}</td><td class="text-end">${parseFloat(row.amount).toFixed(2)}</td>`;
                    tbody.appendChild(tr);
                    total += parseFloat(row.amount);
                  });
                  document.getElementById('total_abattements').textContent = total.toFixed(2);
                });
            })
            .catch(error => {
              console.error('Erreur AJAX :', error);
              grossSalaryInput.value = '';
            });
        } else {
          grossSalaryInput.value = '';
        }
      });
    });
  </script>

  <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
  <script src="https://cdn.jsdelivr.net/npm/flatpickr/dist/plugins/monthSelect/index.js"></script>
</body>
</html>
