<?php

namespace App\Http\Controllers\Web\Payroll;

use App\Http\Controllers\Controller;
use App\Models\EmployeePayroll;

class PayslipController extends Controller
{
    public function show(\App\Models\PayrollCycle $cycle, EmployeePayroll $employeePayroll)
    {
        $companyId = auth()->user()->company_id;
        if ($companyId && (int) $employeePayroll->company_id !== $companyId) {
            abort(403);
        }
        if ((int) $employeePayroll->payroll_cycle_id !== (int) $cycle->id) {
            abort(404);
        }
        $employeePayroll->load(['user.department', 'user.designation', 'payrollCycle', 'components']);
        return view('payroll.cycles.payslip-show', [
            'employeePayroll' => $employeePayroll,
        ]);
    }

    public function download(\App\Models\PayrollCycle $cycle, EmployeePayroll $employeePayroll)
    {
        $companyId = auth()->user()->company_id;
        if ($companyId && (int) $employeePayroll->company_id !== $companyId) {
            abort(403);
        }
        if ((int) $employeePayroll->payroll_cycle_id !== (int) $cycle->id) {
            abort(404);
        }
        if (! class_exists(\Barryvdh\DomPDF\Facade\Pdf::class)) {
            return redirect()->back()->with('error', 'PDF download requires barryvdh/laravel-dompdf.');
        }
        $employeePayroll->load(['user', 'payrollCycle', 'components']);
        $pdf = \Barryvdh\DomPDF\Facade\Pdf::loadView('payroll.cycles.payslip-pdf', ['employeePayroll' => $employeePayroll]);
        $filename = 'payslip-' . $employeePayroll->user_id . '-' . $employeePayroll->payrollCycle->year . '-' . str_pad((string) $employeePayroll->payrollCycle->month, 2, '0', STR_PAD_LEFT) . '.pdf';
        return $pdf->download($filename);
    }
}
