<?php
require_once '/home/advanck/salaires/models/Database.php';
require '/home/advanck/salaires/vendor/autoload.php';

use Models\Database;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

session_start();

if (!isset($_SESSION['user']['id'])) {
    header('Location: /salaires/views/auth/login.php');
    exit();
}

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

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

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

// 🔍 Cotisations sociales
$socials = $pdo->query("SELECT * FROM social_settings")->fetchAll();
$total_cotisations = 0;
$cotisation_rows = [];
foreach ($socials as $row) {
    $rate = floatval($row['rate']);
    $amount = $payslip['gross_salary'] * ($rate / 100);
    $cotisation_rows[] = [$row['label'], $rate, $amount];
    $total_cotisations += $amount;
}

// 🔍 Abattements
$stmt = $pdo->prepare("SELECT label, amount FROM moderation_settings WHERE employee_id = ?");
$stmt->execute([$payslip['employee_id']]);
$abattements = $stmt->fetchAll();
$total_abattements = array_sum(array_column($abattements, 'amount'));

// ✅ Génération Excel
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Fiche de paie');

// 👤 Informations de base
$sheet->setCellValue('A1', 'Fiche de paie - Employé :');
$sheet->setCellValue('B1', $payslip['last_name'] . ' ' . $payslip['first_name']);
$sheet->setCellValue('A2', 'Matricule');
$sheet->setCellValue('B2', $payslip['matricule']);
$sheet->setCellValue('A3', 'Période');
$sheet->setCellValue('B3', $payslip['period']);

// 💸 Résumé
$sheet->fromArray([
    ['Détails', 'Montant (€)'],
    ['Salaire brut', $payslip['gross_salary']],
    ['Cotisations sociales', $payslip['social_charges']],
    ['Abattements fiscaux', $payslip['abattements']],
    ['Impôt', $payslip['tax']],
    ['Autres +', $payslip['other_plus']],
    ['Autres -', $payslip['other_minus']],
    ['Net à payer', $payslip['net_salary']],
], null, 'A5');

// 🧮 Cotisations sociales détaillées
$sheet->setCellValue('D1', 'Cotisations sociales');
$sheet->fromArray([['Intitulé', 'Taux (%)', 'Montant (€)']], null, 'D2');
$sheet->fromArray($cotisation_rows, null, 'D3');
$sheet->setCellValue('D' . (count($cotisation_rows) + 3), 'Total');
$sheet->setCellValue('F' . (count($cotisation_rows) + 3), $total_cotisations);

// 💼 Abattements
$rowStart = count($cotisation_rows) + 6;
$sheet->setCellValue('D' . $rowStart, 'Abattements fiscaux');
$sheet->fromArray([['Type', 'Montant (€)']], null, 'D' . ($rowStart + 1));
foreach ($abattements as $index => $ab) {
    $sheet->setCellValue('D' . ($rowStart + 2 + $index), $ab['label']);
    $sheet->setCellValue('E' . ($rowStart + 2 + $index), $ab['amount']);
}
$sheet->setCellValue('D' . ($rowStart + 3 + count($abattements)), 'Total');
$sheet->setCellValue('E' . ($rowStart + 3 + count($abattements)), $total_abattements);

// ✅ Export
$filename = 'fiche_' . $payslip_id . '.xlsx';
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header("Content-Disposition: attachment; filename=\"$filename\"");
$writer = new Xlsx($spreadsheet);
$writer->save("php://output");
exit();
