<?php

require_once __DIR__ . '/../models/Payroll.php';
require_once __DIR__ . '/../models/Employee.php';
require_once __DIR__ . '/../helpers/AuthHelper.php';


class PayrollsController
{
    private PDO $db;

    public function __construct(PDO $db) { $this->db = $db; }

    public function index(): void
    {
        // 1) Ler filtros vindos por GET
        $filters = [
            'employee_id' => isset($_GET['employee_id']) && $_GET['employee_id'] !== '' ? (int)$_GET['employee_id'] : null,
            'month'       => isset($_GET['month'])       && $_GET['month']       !== '' ? (int)$_GET['month']       : null,
            'year'        => isset($_GET['year'])        && $_GET['year']        !== '' ? (int)$_GET['year']        : null,
        ];
        $page    = max(1, (int)($_GET['page'] ?? 1));
        $perPage = max(10, (int)($_GET['per_page'] ?? 10));
        $offset  = ($page - 1) * $perPage;

        // 2) Carregar colaboradores p/ o select
        $stmtEmp = $this->db->query("
            SELECT id, full_name
            FROM employees
            WHERE status = 'ativo'
            ORDER BY full_name
        ");
        $employees = $stmtEmp->fetchAll(PDO::FETCH_ASSOC);

        // 3) Montar WHERE dinâmico
        $where   = [];
        $params  = [];
        if ($filters['employee_id'] !== null) { $where[] = "p.employee_id = :employee_id"; $params[':employee_id'] = $filters['employee_id']; }
        if ($filters['month']       !== null) { $where[] = "p.reference_month = :month";   $params[':month']       = $filters['month']; }
        if ($filters['year']        !== null) { $where[] = "p.reference_year  = :year";    $params[':year']        = $filters['year']; }
        $whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

        // 4) Total para paginação
        $sqlCount = "SELECT COUNT(*) AS total FROM payrolls p {$whereSql}";
        $stmtCnt  = $this->db->prepare($sqlCount);
        foreach ($params as $k=>$v) $stmtCnt->bindValue($k, $v, PDO::PARAM_INT);
        $stmtCnt->execute();
        $totalCount = (int)$stmtCnt->fetchColumn();

        // 5) Buscar folhas com JOIN (status virtual)
        $sql = "
            SELECT
              p.id,
              p.employee_id,
              e.full_name           AS employee_name,
              p.reference_month,
              p.reference_year,
              p.base_salary,
              p.total_discounts,
              p.net_salary,
              'processada'          AS status,
              p.generated_at
            FROM payrolls p
            JOIN employees e ON e.id = p.employee_id
            {$whereSql}
            ORDER BY p.reference_year DESC, p.reference_month DESC, e.full_name ASC
            LIMIT :limit OFFSET :offset
        ";
        $stmt = $this->db->prepare($sql);
        foreach ($params as $k=>$v) $stmt->bindValue($k, $v, PDO::PARAM_INT);
        $stmt->bindValue(':limit',  $perPage, PDO::PARAM_INT);
        $stmt->bindValue(':offset', $offset,  PDO::PARAM_INT);
        $stmt->execute();
        $payrolls = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // 6) Render da view (a que deixei pronta no canvas)
        // Certifique-se que BASE_URL e partials estão corretos no seu bootstrap.
        $pageVars = compact('employees','payrolls','filters','totalCount','page','perPage');
        extract($pageVars);
        require __DIR__ . '/../views/payrolls/index.php';
    }

    public function export(): void
    {
        $id     = isset($_GET['id']) && ctype_digit((string)$_GET['id']) ? (int)$_GET['id'] : null;
        $empId  = isset($_GET['employee_id']) && $_GET['employee_id'] !== '' ? (int)$_GET['employee_id'] : null;
        $month  = isset($_GET['month']) && $_GET['month'] !== '' ? (int)$_GET['month'] : null;
        $year   = isset($_GET['year'])  && $_GET['year']  !== '' ? (int)$_GET['year']  : null;

        $where   = [];
        $params  = [];
        if ($id !== null)     { $where[] = 'p.id = :id';                  $params[':id'] = $id; }
        if ($empId !== null)  { $where[] = 'p.employee_id = :employee_id'; $params[':employee_id'] = $empId; }
        if ($month !== null)  { $where[] = 'p.reference_month = :month';   $params[':month'] = $month; }
        if ($year  !== null)  { $where[] = 'p.reference_year  = :year';    $params[':year']  = $year; }
        $whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

        $sql = "SELECT p.id, e.full_name AS employee_name, p.reference_month, p.reference_year, p.base_salary, p.total_discounts, p.net_salary
                FROM payrolls p
                JOIN employees e ON e.id = p.employee_id
                {$whereSql}
                ORDER BY p.reference_year DESC, p.reference_month DESC, e.full_name ASC";

        $stmt = $this->db->prepare($sql);
        foreach ($params as $k=>$v) { $stmt->bindValue($k, $v, PDO::PARAM_INT); }
        $stmt->execute();
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $filename = 'payrolls' . ($id ? '-' . $id : '') . '-' . date('Ymd_His') . '.csv';
        header('Content-Type: text/csv; charset=UTF-8');
        header('Content-Disposition: attachment; filename=' . $filename);
        header('Pragma: no-cache');
        header('Expires: 0');

        $out = fopen('php://output', 'w');
        fwrite($out, chr(0xEF) . chr(0xBB) . chr(0xBF)); // BOM para Excel
        fputcsv($out, ['ID','Colaborador','Mês','Ano','Salário base','Descontos','Líquido']);
        foreach ($rows as $r) {
          fputcsv($out, [
            $r['id'] ?? '',
            $r['employee_name'] ?? '',
            $r['reference_month'] ?? '',
            $r['reference_year'] ?? '',
            number_format((float)($r['base_salary'] ?? 0), 2, '.', ''),
            number_format((float)($r['total_discounts'] ?? 0), 2, '.', ''),
            number_format((float)($r['net_salary'] ?? 0), 2, '.', ''),
          ]);
        }
        fclose($out);
        exit;
    }
}
