<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Payroll;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Response as StreamResponse;

class SalarySheetExportController extends Controller
{
    public function export(Request $request, Payroll $payroll): mixed
    {
        $format = $request->get('format', 'csv');
        $payroll->load(['items.employee.employeeProfile']);

        return match ($format) {
            'pdf' => $this->exportPdf($payroll),
            default => $this->exportCsv($payroll),
        };
    }

    private function exportCsv(Payroll $payroll): \Symfony\Component\HttpFoundation\StreamedResponse
    {
        $filename = 'salary_sheet_'.$payroll->month->format('Y-m').'.csv';

        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => "attachment; filename=\"{$filename}\"",
        ];

        $callback = function () use ($payroll) {
            $file = fopen('php://output', 'w');

            fputcsv($file, ['Employee', 'Department', 'Gross Salary', 'Total Earnings', 'Income Tax', 'Loan', 'Addition', 'Deduction', 'Net Salary']);

            $totalNet = 0;

            foreach ($payroll->items as $item) {
                fputcsv($file, [
                    $item->employee->name,
                    $item->employee->employeeProfile?->departmentRel?->name ?? '-',
                    $item->gross_salary,
                    $item->total_earnings,
                    $item->tax_deduction > 0 ? '-'.$item->tax_deduction : 0,
                    $item->loan_deduction > 0 ? '-'.$item->loan_deduction : 0,
                    $item->addition_adjustment > 0 ? '+'.$item->addition_adjustment : 0,
                    $item->deduction_adjustment > 0 ? '-'.$item->deduction_adjustment : 0,
                    $item->net_salary,
                ]);
                $totalNet += $item->net_salary;
            }

            fputcsv($file, ['TOTAL', '', '', '', '', '', '', '', $totalNet]);

            fclose($file);
        };

        return StreamResponse::stream($callback, 200, $headers);
    }

    private function exportPdf(Payroll $payroll): Response
    {
        $pdf = Pdf::loadView('pdf.salary_sheet', [
            'payroll' => $payroll,
            'companyName' => config('branding.theme.app_name', config('app.name')),
        ])->setPaper('a4', 'landscape');

        $filename = 'salary_sheet_'.$payroll->month->format('Y-m').'.pdf';

        return $pdf->download($filename);
    }
}
