<?php
require_once '../models/Database.php';
use Models\Database;

header('Content-Type: application/json');

$data = json_decode(file_get_contents('php://input'), true);
$employee_id = intval($data['employee_id'] ?? 0);
$gross = floatval($data['gross_salary'] ?? 0);

$pdo = Database::getInstance()->getConnection();

$stmt = $pdo->prepare("SELECT taux_impot FROM employees WHERE id = ?");
$stmt->execute([$employee_id]);
$taux_impot = floatval($stmt->fetchColumn());

$socials = $pdo->query("SELECT * FROM social_settings")->fetchAll();
$cotisations = [];
$total_cotisations = 0;

foreach ($socials as $s) {
  $base = $gross * ($s['gross_base'] / 100);
  $amount = $base * ($s['rate'] / 100);
  $cotisations[] = [
    'keyname' => $s['keyname'] .'***',
    'value' => $s['value'],
    'rate' => $s['rate'],
    'base' => round($base, 2),
    'amount' => round($amount, 2)
  ];
  $total_cotisations += $amount;
}

$imposable = $gross - $total_cotisations;
$impot = $imposable * ($taux_impot / 100);

echo json_encode([
  'taux_impot' => $taux_impot,
  'imposable' => round($imposable, 2),
  'impot' => round($impot, 2),
  'total_cotisations' => round($total_cotisations, 2),
  'cotisations' => $cotisations
]);
