<?php

namespace App\Services;

use App\Models\PayrollEntry;

class PayrollPayslipPdfService
{
    public function __construct(private BrandedPdfService $pdf) {}

    public function generate(PayrollEntry $entry): string
    {
        $entry->loadMissing(['period.branch.business', 'financialAccount', 'accountTransaction', 'payer']);
        $period = $entry->period;
        $business = $period->branch->business;

        $lines = [
            'Payroll Period: '.$period->period_number.' — '.$period->name,
            'Period: '.$period->start_date->format('d M Y').' to '.$period->end_date->format('d M Y'),
            'Branch: '.$period->branch->name,
            'Scheduled Pay Date: '.$period->pay_date->format('d M Y'),
            'Paid At: '.($entry->paid_at?->format('d M Y H:i') ?? 'Not paid'),
            '',
            'EMPLOYEE',
            'Name: '.$entry->employee_name_snapshot,
            'Employee Number: '.($entry->employee_number_snapshot ?: 'N/A'),
            'Position: '.($entry->position_snapshot ?: 'N/A'),
            '',
            'EARNINGS',
            'Basic Salary: '.$this->pdf->money($business, $entry->basic_salary),
            'Allowances: '.$this->pdf->money($business, $entry->allowances),
            'Bonus: '.$this->pdf->money($business, $entry->bonus),
            'Commission: '.$this->pdf->money($business, $entry->commission),
            'Overtime: '.$this->pdf->money($business, $entry->overtime),
            'GROSS PAY: '.$this->pdf->money($business, $entry->gross),
            '',
            'DEDUCTIONS',
            'Deductions: '.$this->pdf->money($business, $entry->deductions),
            'Advances: '.$this->pdf->money($business, $entry->advances),
            'Other Deductions: '.$this->pdf->money($business, $entry->other_deductions),
            'TOTAL DEDUCTIONS: '.$this->pdf->money($business, $entry->total_deductions),
            '',
            'NET PAY: '.$this->pdf->money($business, $entry->net),
            '',
            'PAYMENT',
            'Paid From: '.($entry->financialAccount?->name ?: 'N/A'),
            'Transaction Reference: '.($entry->accountTransaction?->transaction_number ?: 'N/A'),
            'Accounting Journal: '.($entry->accounting_journal_number ?: 'N/A'),
            'Processed By: '.($entry->payer?->name ?: 'N/A'),
        ];

        return $this->pdf->generate($business, 'EMPLOYEE PAYSLIP', $lines, $entry->payslip_number);
    }
}
