<?php
namespace Controllers;
use \PDO;

require_once __DIR__ . '/../models/Database.php';
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../utils/logger.php';

use Models\Database;
use Models\Payslip;
use Utils\Auth;

class PayslipController {
    private $pdo;
    private $payslipModel;

   public function __construct() {
        require_once __DIR__ . '/../models/Database.php'; // Assure l'inclusion
        $db = \Models\Database::getInstance();

        if (!$db) {
            throw new \Exception("Impossible d'initialiser Database::getInstance()");
        }

        $this->pdo = $db->getConnection();

        if (!$this->pdo) {
            throw new \Exception("Connexion PDO échouée");
        }

        $this->payslipModel = new \Models\Payslip(); // Assure que le modèle est aussi bien inclus
    }
    public function index() {
        Auth::checkPermission(['admin', 'chef_comptable', 'comptable']);
        $data = [
            'payslips' => $this->payslipModel->findAll(),
            'pageTitle' => 'Fiches de paie'
        ];
        $this->loadInDashboard('index.php', $data);
    }

    public function create() {
    try {
            Auth::checkPermission(['admin', 'chef_comptable']);

            $pdo = $this->pdo;
            //$employees = $pdo->query("SELECT id, first_name, last_name, cis, co2 FROM employees WHERE status = 'actif'")->fetchAll();
            $employees = $pdo->query("SELECT id, CONCAT(first_name, ' ', last_name) AS full_name FROM employees ORDER BY last_name")->fetchAll();
            $cotisations = $pdo->query("SELECT * FROM social_settings")->fetchAll();
            $settings = $pdo->query("SELECT `keyname`, `value` FROM settings")->fetchAll(PDO::FETCH_KEY_PAIR);

            $data = [
                'employees'   => $employees,
                'cotisations' => $cotisations,
                'settings'    => $settings,
                'pageTitle'   => 'Créer une fiche de paie'
            ];
            extract($data);
            $this->loadInDashboard('create.php', $data);
        } catch (\Throwable $e) {
            http_response_code(500);
            echo "<pre>Erreur create(): " . $e->getMessage() . "\nFichier : " . $e->getFile() . "\nLigne : " . $e->getLine() . "</pre>";
        }
    }

    public function store() {
        header('Content-Type: application/json');
        
        try {
            $input = json_decode(file_get_contents('php://input'), true);
            // Valider les données...
            if (empty($input['employee_id'])) {
                throw new \Exception("Employee ID required");
            }

            // Traitement...
            $response = ['success' => true, 'message' => 'Payslip stored'];
            echo json_encode($response);
            
        } catch (\Exception $e) {
            http_response_code(400);
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
    }
/* 
    public function store() {
        Auth::checkPermission(['admin', 'chef_comptable']);
        $model = new Payslip();
        if ($model->create($_POST)) {
            header('Location: /payslips');
            exit;
        } else {
            echo 'Erreur lors de la création de la fiche de paie';
        }
    }
 */

    public function delete($id) {
        $stmt = $this->pdo->prepare("SELECT validated FROM payslips WHERE id = ?");
        $stmt->execute([$id]);
        $payslip = $stmt->fetch();

        if (!$payslip) {
            $_SESSION['error'] = "Fiche introuvable.";
        } elseif ($payslip['validated']) {
            $_SESSION['error'] = "Impossible de supprimer un bulletin validé.";
        } else {
            $stmt = $this->pdo->prepare("DELETE FROM payslips WHERE id = ?");
            $stmt->execute([$id]);
            $_SESSION['message'] = "Bulletin supprimé.";
        }

        header("Location: /payslips");
        exit;
    }

    public function edit($id) {
        $stmt = $this->pdo->prepare("
            SELECT p.*, e.first_name, e.last_name
            FROM payslips p
            JOIN employees e ON p.employee_id = e.id
            WHERE p.id = ?
        ");
        $stmt->execute([$id]);
        $payslip = $stmt->fetch();

        if (!$payslip) {
            $_SESSION['error'] = 'Fiche introuvable';
            header('Location: /payslips');
            exit;
        }

        $this->loadInDashboard('update.php', ['payslip' => $payslip]);
    }


    public function update() {
        custom_log("Méthode update() appelée avec POST: " . print_r($_POST, true) . " - et Gross salary = " . $_POST['gross_salary']);
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id'])) {
            $id = (int)$_POST['id'];

            $stmt = $this->pdo->prepare("
                UPDATE payslips 
                SET period = ?, gross_salary = ?
                WHERE id = ?
            ");
            $stmt->execute([
                $_POST['period'],
                $_POST['gross_salary'],
                $id
            ]);

            $_SESSION['message'] = 'Fiche de paie mise à jour avec succès.';
            header('Location: /payslips');
            exit;
        }

        $_SESSION['error'] = 'Requête invalide.';
        header('Location: /payslips');
        exit;
    }


    public function show() {
        $this->pdo = Database::getInstance()->getConnection();
        $pdo = $this->pdo;
        $stmt = $pdo->prepare("
            SELECT keyname, label, gross_base, rate, amount
            FROM payslip_social
            WHERE payslip_id = ?
        ");
        $stmt->execute([$payslipId]);
        $socials = $stmt->fetchAll();

        $this->loadInDashboard('show.php', $socials);
    }

    public function validate($id) {
        $stmt = $this->pdo->prepare("UPDATE payslips SET validated = 1 WHERE id = ?");
        $stmt->execute([$id]);
        $_SESSION['message'] = 'Bulletin validé avec succès';
        header('Location: /payslips');
        exit;
    }

    public function success() {
        $this->loadInDashboard('success.php');
    }

    public function duplicate() {
        $this->loadInDashboard('duplicate.php');
    }

    public function exportPdf($id) {
    // Récupération de la fiche de paie
    $stmt = $this->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 de paie introuvable.");
    }

    $payslip_id = $id;

    // 📄 Récupération des avantages en nature enregistrées
    $pdo = Database::getInstance()->getConnection();
    $stmt = $pdo->prepare("SELECT b.*
        FROM benefits_in_kind_settings b
        JOIN payslips p ON b.employee_id = p.employee_id
        WHERE p.id = ?;");
    $stmt->execute([$payslip_id]);
    $benefits = $stmt->fetchAll();

    $benefits_lines = [];
    $totalBenefits = 0;
    foreach ($benefits as $benefit) {
        $benefits_lines[] = [
            'code' => $benefit['keyname'],
            'label' => $benefit['label'],
            'base' => $benefit['gross_base'],
            'rate' => $benefit['rate'],
            'amount' => $benefit['amount']
        ];
        $totalBenefits += $benefit['amount'];
    }

    // 📄 Récupération des cotisations sociales enregistrées
    $pdo = Database::getInstance()->getConnection();
    $stmt = $pdo->prepare("SELECT * FROM payslip_social WHERE payslip_id = ?");
    $stmt->execute([$payslip_id]);
    $socials = $stmt->fetchAll();

    $cotisations = [];
    $totalCotisations = 0;
    foreach ($socials as $social) {
        $cotisations[] = [
            'code' => $social['keyname'],
            'label' => $social['label'],
            'base' => $social['gross_base'],
            'rate' => $social['rate'],
            'amount' => $social['amount']
        ];
        $totalCotisations += $social['amount'];
    }

    // 📄 Récupération des abattements
    $stmt = $this->pdo->prepare("
        SELECT keyname, label, amount 
        FROM payslip_moderation 
        WHERE payslip_id = ?
    ");
    $stmt->execute([$payslip_id]);
    $abattements = $stmt->fetchAll();
    $totalAbattements = array_sum(array_column($abattements, 'amount'));

    // 📄 Récupération des autres +/-
    $stmt = $this->pdo->prepare("
        SELECT keyname, label, amount 
        FROM payslip_plus_minus 
        WHERE payslip_id = ?
    ");
    $stmt->execute([$payslip_id]);
    $plus_minus = $stmt->fetchAll();

    // 📄 Cumuls annuels
   $year = (int)substr($payslip['period'], -4);
    $stmt = $this->pdo->prepare("
        SELECT 
            COALESCE(SUM(gross_salary), 0) AS gross_total,
            COALESCE(SUM(social_charges), 0) AS charges_total,
            COALESCE(SUM(impots), 0) AS impots_total,
            COALESCE(SUM(net_salary), 0) AS net_avant_impot,
            COALESCE(SUM(net_apres_impot), 0) AS net_total,
            COALESCE(SUM(other_plus), 0) AS ajouts,
            COALESCE(SUM(other_minus), 0) AS diminutions,
            COALESCE(SUM(net_final), 0) AS net_a_payer
        FROM payslips
        WHERE employee_id = ? AND year = ?
    ");
    $stmt->execute([$payslip['employee_id'], $year]);
    $cumuls = $stmt->fetch();
    $cumuls['year'] = $year;
    $file = fopen(__DIR__ .'/../logs/PayslipController.txt', 'w');
    fwrite($file, "Pattern utilisé : >$pattern<");
    fwrite($file, "year : >$year<");
    fwrite($file, 'cumuls = ' . print_r($cumuls, true));
    fclose($file);

    // 📄 Génération du PDF
    require_once __DIR__ . '/../utils/MyPdf.php';
    $pdf = new \MyPdf('P', 'mm', 'A4', true, 'UTF-8', false);
    $pdf->SetAutoPageBreak(true, 20);
    $pdf->SetMargins(15, 50, 15);
    $pdf->AddPage();
    $pdf->SetFont('dejavusans', '', 10);

    // 📄 Préparation des données pour la vue
    extract([
        'payslip' => $payslip,
        'benefits' => $benefits_lines,
        'cotisations' => $cotisations,
        'abattements' => $abattements,
        'plus_minus' => $plus_minus,
        'cumuls' => $cumuls,
        'year' => $year,
        'totalBenefits' => $totalBenefits,
        'totalCotisations' => $totalCotisations,
        'totalAbattements' => $totalAbattements
    ]);

    ob_start();
    include __DIR__ . '/../views/payslips/pdf_template.php';
    $html = ob_get_clean();
    $pdf->writeHTML($html, true, false, true, false, '');
    $pdf->Output('bulletin_' . $id . '.pdf', 'I');
}

    private function loadInDashboard($viewFile, $data = []) {
        extract($data);
        $viewPath = __DIR__ . '/../views/payslips/' . $viewFile;
        if (!file_exists($viewPath)) {
            throw new \Exception("Vue $viewFile introuvable");
        }
        $view = $viewPath;
        require __DIR__ . '/../views/dashboard.php';
    }
}