<?php
declare(strict_types=1);

namespace App\Modules\HR\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\HR\Models\HrTaxRecord;
use App\Modules\HR\Models\HrEmployeeProfile;

class TaxController extends Controller
{
    public function index(Request $request): Response
    {
        $year = (int) $request->get('year', (int) date('Y'));

        $db = App::getInstance()->db();

        // Monthly summary
        $monthlySummary = $db->select(
            "SELECT pp.month,
                    COUNT(tr.id) as employee_count,
                    SUM(tr.gross_taxable_monthly) as total_gross_taxable,
                    SUM(tr.monthly_tax) as total_tax
             FROM hr_payroll_periods pp
             LEFT JOIN hr_tax_records tr ON tr.period_id = pp.id AND tr.is_archived = 0
             WHERE pp.year = ? AND pp.is_archived = 0
             GROUP BY pp.month
             ORDER BY pp.month ASC",
            [$year]
        );

        // YTD totals
        $ytdTotals = $db->selectOne(
            "SELECT SUM(tr.gross_taxable_monthly) as ytd_gross_taxable,
                    SUM(tr.monthly_tax) as ytd_tax
             FROM hr_tax_records tr
             JOIN hr_payroll_periods pp ON pp.id = tr.period_id
             WHERE pp.year = ? AND tr.is_archived = 0 AND pp.is_archived = 0",
            [$year]
        );

        return $this->view('HR.Views.tax.index', [
            'monthlySummary' => $monthlySummary,
            'ytdTotals'      => $ytdTotals,
            'year'           => $year,
        ]);
    }

    public function employeeHistory(Request $request, string $employeeId): Response
    {
        $profile = HrEmployeeProfile::find((int) $employeeId);
        if (!$profile) {
            return $this->redirect('/hr/tax')->withError('الموظف غير موجود');
        }

        $year = (int) $request->get('year', (int) date('Y'));
        $records = HrTaxRecord::getForEmployee((int) $employeeId, $year);

        // YTD for this employee
        $ytd = HrTaxRecord::getYtdForEmployee((int) $employeeId, $year);

        return $this->view('HR.Views.tax.employee_history', [
            'profile' => $profile,
            'records' => $records,
            'ytd'     => $ytd,
            'year'    => $year,
        ]);
    }
}
