<?php
require_once '../vendor/autoload.php';
require_once '../utils/MyPdf.php';
require_once '../models/Database.php';
use Models\Database;

if (!isset($_GET['id'])) die("ID manquant");

$id = intval($_GET['id']);
$pdo = Database::getInstance()->getConnection();

$stmt = $pdo->prepare("SELECT p.*, e.* FROM payslips p JOIN employees e ON p.employee_id = e.id WHERE p.id = ?");
$stmt->execute([$id]);
$payslip = $stmt->fetch();
if (!$payslip) die("Fiche introuvable");

// Données liées
function fetch($table) {
  global $pdo, $payslip;
  $stmt = $pdo->prepare("SELECT * FROM $table WHERE employee_id = ? AND period = ?");
  $stmt->execute([$payslip['employee_id'], $payslip['period']]);
  return $stmt->fetchAll();
}

$cotisations = fetch('payslip_social');
$abattements = fetch('payslip_moderation');
$plus_minus = fetch('payslip_plus_minus');
$impot = $pdo->prepare("SELECT * FROM payslip_taxes WHERE employee_id = ? AND period = ?");
$impot->execute([$payslip['employee_id'], $payslip['period']]);
$impot = $impot->fetch();

$year = substr($payslip['period'], -4);
$stmt = $pdo->prepare("SELECT SUM(gross_salary) as brut, SUM(social_charges) as charges, SUM(net_salary) as net FROM payslips WHERE employee_id = ? AND period LIKE ?");
$stmt->execute([$payslip['employee_id'], "%$year"]);
$cumuls = $stmt->fetch();

$pdf = new MyPdf();
$pdf->AddPage();
$pdf->SetFont('dejavusans', '', 10);

ob_start();
include '../views/payslips/pdf_template.php';
$html = ob_get_clean();

$pdf->writeHTML($html, true, false, true, false, '');
$pdf->Output('fiche_' . $id . '.pdf', 'I');
