<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

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

require_once __DIR__ . '/../../models/Database.php';
require_once __DIR__ . '/../../utils/Helpers.php';

use Models\Database;

$response = ['success' => false];

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception("Méthode non autorisée", 405);
    }

    $json = file_get_contents('php://input');
    $data = json_decode($json, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception("Données JSON invalides", 400);
    }

    foreach (['employee_id', 'period', 'gross_salary'] as $field) {
        if (empty($data[$field])) {
            throw new Exception("Le champ $field est obligatoire", 400);
        }
    }

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

    $employeeId = (int)$data['employee_id'];
    $period = htmlspecialchars($data['period']);
    $gross = (float)$data['gross_salary'];
    $benefits = isset($data['benefits']) ? (float)$data['benefits'] : 0;
    $total_gross = (float)$data['total_gross'];

    $abattements = $data['moderation_lines'] ?? [];
    $plus = $data['plus'] ?? [];
    $minus = $data['minus'] ?? [];

    // 🔷 1. Calcul des cotisations
    $cotisations = calculerCotisations($gross, $benefits);
    // $socialCharges = array_sum(array_column($cotisations, 'amount'));
    $socialCharges = (float)$data['social_charges'];

    $totalAbattements = array_sum(array_column($abattements, 'amount'));
    $tauxImpot = (float)($data['taux_impot'] ?? 0);
    $imposable = $total_gross - $socialCharges - $totalAbattements;
    $impot = calculImpots($imposable, $tauxImpot);

    $cis =  (float)$data['cis'];
    $co2 =  (float)$data['co2'];

    $netAvantImpot = $gross + $benefits - $socialCharges;
    $netApresImpot = $netAvantImpot - $impot + $cis + $co2;

    $otherPlus = array_sum(array_column($plus, 'amount'));
    $otherMinus = array_sum(array_column($minus, 'amount'));
    $netFinal = $netApresImpot + $otherPlus + $otherMinus - $benefits;

    $year = (int)substr($period, -4);

    // 🔷 2. Insertion dans payslips
    $stmt = $pdo->prepare("
        INSERT INTO payslips 
        (employee_id, period, gross_salary, benefits, total_gross, social_charges, abattements, taux_impot, cis, co2, imposable, impots, other_plus, other_minus, net_salary, net_apres_impot, net_final, year)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->execute([
        $employeeId, $period, $gross, $benefits, $total_gross, $socialCharges, $totalAbattements, $tauxImpot,
        $cis, $co2, $imposable, $impot, $otherPlus, $otherMinus,
        $netAvantImpot, $netApresImpot, $netFinal, $year
    ]);
    $payslipId = $pdo->lastInsertId();

    // 🔷 3. Insertion cotisations sociales
    $stmtSocial = $pdo->prepare("
        INSERT INTO payslip_social
        (payslip_id, employee_id, period, keyname, label, rate, gross_base, amount)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    ");
    foreach ($cotisations as $c) {
        $stmtSocial->execute([
            $payslipId, $employeeId, $period,
            $c['keyname'], $c['label'], $c['rate'], $c['base'], $c['amount']
        ]);
    }

    // 🔷 4. Insertion abattements
    if (!empty($abattements)) {
        $stmtAbatt = $pdo->prepare("
            INSERT INTO payslip_moderation 
            (payslip_id, employee_id, keyname, label, amount) 
            VALUES (?, ?, ?, ?, ?)
        ");
        foreach ($abattements as $a) {
            $stmtAbatt->execute([
                $payslipId, $employeeId,
                $a['key'], $a['label'], $a['amount']
            ]);
        }
    }
    // 🔷 5. Insertion des taxes
    if (!empty($data['taux_impot']) && !empty($data['montant_impot'])) {
        $stmtTax = $pdo->prepare("INSERT INTO payslip_taxes 
                                 (payslip_id, employee_id, base_gross, tax_rate, tax_amount, period)
                                 VALUES (?, ?, ?, ?, ?, ?)");
        $stmtTax->execute([
            $payslipId, $employeeId, $data['salaire_imposable'], $data['taux_impot'], $data['montant_impot'], $period
        ]);
    }

    // 🔷 6. Insertion plus/minus
    $stmtPM = $pdo->prepare("
        INSERT INTO payslip_plus_minus
        (payslip_id, employee_id, keyname, label, amount)
        VALUES (?, ?, ?, ?, ?)
    ");
    foreach ($plus as $p) {
        $pkeyname = preg_replace('/[^A-Za-z0-9\-]/', '', substr($p['label'], 0, 10));
        $stmtPM->execute([
            $payslipId, $employeeId,
            strtoupper($pkeyname), $p['label'], $p['amount']
        ]);
    }
    foreach ($minus as $m) {
        $mkeyname = preg_replace('/[^A-Za-z0-9\-]/', '', substr($p['label'], 0, 10));
        $stmtPM->execute([
            $payslipId, $employeeId,
             strtoupper($mkeyname), $m['label'], $m['amount']
        ]);
    }

    $pdo->commit();

    $response['success'] = true;
    $response['payslip_id'] = $payslipId;

} catch (Throwable $e) {
    if (isset($pdo) && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    http_response_code(500);
    $response['error'] = $e->getMessage();
    $response['file'] = $e->getFile();
    $response['line'] = $e->getLine();
}

echo json_encode($response);
