<?php
require_once __DIR__ . '/../models/Database.php';
require_once __DIR__ . '/../utils/logger.php';
use Models\Database;
use Utils\MoisFrHelper;

function genererSelectMois(string $name, ?string $selected = null, int $nbMonths = 12): string {
    $html = "<select name=\"$name\" class=\"form-select\">\n";

    for ($i = 0; $i < $nbMonths; $i++) {
        $dateObj = new DateTime("-$i months");
        $sqlValue = $dateObj->format('Y-m');
        $frValue = MoisFrHelper::sqlToFr($sqlValue);

        $isSelected = ($sqlValue === $selected) ? 'selected' : '';
        $html .= "<option value=\"$sqlValue\" $isSelected>$frValue</option>\n";
    }

    $html .= "</select>\n";
    return $html;
}

function genererSelectPeriode(
    string $nameStart,
    string $nameEnd,
    ?string $selectedStart = null,
    ?string $selectedEnd = null,
    int $nbMonths = 12
): string {
    $options = [];

    for ($i = 0; $i < $nbMonths; $i++) {
        $dateObj = new DateTime("-$i months");
        $sqlValue = $dateObj->format('Y-m');
        $frValue = MoisFrHelper::sqlToFr($sqlValue);

        $options[] = [
            'sql' => $sqlValue,
            'fr' => $frValue
        ];
    }

    $html = '<div class="row">';

    // Début
    $html .= '<div class="col-md-6 mb-3">';
    $html .= '<label for="' . $nameStart . '">Période début</label>';
    $html .= '<select name="' . $nameStart . '" class="form-select">';
    foreach ($options as $opt) {
        $selected = ($opt['sql'] === $selectedStart) ? 'selected' : '';
        $html .= '<option value="' . $opt['sql'] . '" ' . $selected . '>' . $opt['fr'] . '</option>';
    }
    $html .= '</select>';
    $html .= '</div>';

    // Fin
    $html .= '<div class="col-md-6 mb-3">';
    $html .= '<label for="' . $nameEnd . '">Période fin</label>';
    $html .= '<select name="' . $nameEnd . '" class="form-select">';
    foreach ($options as $opt) {
        $selected = ($opt['sql'] === $selectedEnd) ? 'selected' : '';
        $html .= '<option value="' . $opt['sql'] . '" ' . $selected . '>' . $opt['fr'] . '</option>';
    }
    $html .= '</select>';
    $html .= '</div>';

    $html .= '</div>';

    return $html;
}

function sanitize($data) {
    if (is_array($data)) {
        return array_map('sanitize', $data);
    }
    return htmlspecialchars(trim($data), ENT_QUOTES, 'UTF-8');
}

function redirect($url, $statusCode = 303) {
    header('Location: ' . $url, true, $statusCode);
    exit();
}

function formatCurrency($amount) {
    return number_format($amount, 2, ',', ' ') . ' €';
}

function getFranchise() {
    $pdo = Database::getInstance()->getConnection();
    $stmt = $pdo->prepare("SELECT value FROM settings WHERE keyname = 'franchise'");
    $stmt->execute();
    $result = $stmt->fetch();
    return isset($result['value']) ? floatval(str_replace(',', '.', $result['value'])) : 659.45;
}

function getSocialRates() {
    $pdo = Database::getInstance()->getConnection();
    $stmt = $pdo->query("SELECT keyname, label, rate, gross_base FROM social_settings");
    $result = [];
    while ($row = $stmt->fetch()) {
        $key = strtoupper(trim($row['keyname']));
        $result[$key] = [
            'label' => $row['label'],
            'rate'  => floatval($row['rate']),
            'base'  => floatval($row['gross_base'])
        ];
    }
    return $result;
}

function calculCotisationGenerique($salaireBrut, $cle, $socialRates) {
    $cle = strtoupper(trim($cle));
    if (!isset($socialRates[$cle])) return null;

    $taux = $socialRates[$cle]['rate'];
    $basePercent = $socialRates[$cle]['base'];
    $base = $salaireBrut * $basePercent / 100;
    $montant = $base * $taux / 100;

    return [
        'keyname' => $cle,
        'label'   => $socialRates[$cle]['label'],
        'base'    => round($base, 2),
        'rate'    => $taux,
        'amount'  => round($montant, 2)
    ];
}

function calculCotisationDependance($salaireBrut, $socialRates) {
    $cle = 'S.D';
    if (!isset($socialRates[$cle])) return null;

    $franchise = getFranchise();
    $taux = $socialRates[$cle]['rate'];
    $basePercent = $socialRates[$cle]['base'];
    $base = max(0, ($salaireBrut * $basePercent / 100) - $franchise);
    $montant = $base * $taux / 100;

    return [
        'keyname' => $cle,
        'label'   => $socialRates[$cle]['label'],
        'base'    => round($base, 2),
        'rate'    => $taux,
        'amount'  => round($montant, 2)
    ];
}

function calculCotisationsSociales($salaireBrut) {
    $socialRates = getSocialRates();

    $cotisations = [];
    foreach (['C.M', 'C.ME', 'C.P'] as $code) {
        $c = calculCotisationGenerique($salaireBrut, $code, $socialRates);
        if ($c) $cotisations[] = $c;
    }

    $sd = calculCotisationDependance($salaireBrut, $socialRates);
    if ($sd) $cotisations[] = $sd;

    $total = array_sum(array_column($cotisations, 'amount'));

    return [
        'cotisations' => $cotisations,
        'total' => round($total, 2)
    ];
}

function calculImpots($salaireImposable, $tauxImpot) {
    return round($salaireImposable * ($tauxImpot / 100), 2);
}

function calculerCotisations($salaireBrut, $avantageNature = 0) {
    $pdo = Database::getInstance()->getConnection();

    // Lecture des paramètres dans social_settings
    $stmt = $pdo->query("SELECT keyname, label, rate, gross_base FROM social_settings");
    $socialSettings = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Initialisation
    $brutAvecAvantage = $salaireBrut + $avantageNature;
    $cotisations = [];

    foreach ($socialSettings as $row) {
        $key = $row['keyname'];
        $label = $row['label'];
        $rate = (float) $row['rate'];
        $grossBase = (float) $row['gross_base'];

        // Base de calcul
        if ($key === 'C.ME') {
            // Caisse maladie espèces : seulement sur le brut
            $base = $salaireBrut * $grossBase / 100;
        } else {
            // Les autres prennent en compte avantage en nature
            $base = $brutAvecAvantage * $grossBase / 100;
        }

        // Franchise pour S.D
        if ($key === 'S.D') {
            $franchise = getFranchise(); // 🔷 fonction déjà existante dans helpers.php
            $base = max(0, $base - $franchise);
        }

        $amount = round($base * $rate / 100, 2);

        $cotisations[] = [
            'keyname' => $key,
            'label' => $label,
            'base' => round($base, 2),
            'rate' => $rate,
            'amount' => $amount
        ];
    }

    return $cotisations;
}


?>