<?php

namespace Modules\Payroll\Services;

use App\Models\CompanySettingsModel;
use App\Models\PayrollItemModel;
use App\Models\PayrollRunModel;
use App\Models\PayrollSettingsModel;

class WpsExportService
{
    protected PayrollRunModel $runs;
    protected PayrollItemModel $items;
    protected PayrollSettingsModel $settings;
    protected CompanySettingsModel $company;

    public function __construct()
    {
        $this->runs     = new PayrollRunModel();
        $this->items    = new PayrollItemModel();
        $this->settings = new PayrollSettingsModel();
        $this->company  = new CompanySettingsModel();
    }

    public function generateCsv(int $runId): array
    {
        $run = $this->runs->find($runId);
        if (! $run) {
            return ['success' => false, 'error' => 'Payroll run not found.'];
        }

        if (! in_array($run['status'], ['approved', 'paid'], true)) {
            return ['success' => false, 'error' => 'WPS export requires an approved or paid payroll run.'];
        }

        $settings = $this->settings->getSettings();
        $company  = $this->company->getSettings();
        $items    = $this->items->getForRun($runId);

        $period = sprintf('%04d-%02d', (int) $run['period_year'], (int) $run['period_month']);
        $lines  = [];
        $lines[] = implode(',', [
            'Employer ID',
            'Period',
            'Employee CPR',
            'Employee Name',
            'Employee Number',
            'IBAN',
            'Bank Name',
            'Net Salary (BHD)',
            'Reference',
        ]);

        foreach ($items as $item) {
            if ((float) $item['net_pay'] <= 0) {
                continue;
            }

            $ref = 'PAY-' . $period . '-' . $item['employee_number'];
            $lines[] = implode(',', [
                $this->csvEscape($settings['wps_employer_id'] ?? ''),
                $period,
                $this->csvEscape($item['cpr_number'] ?? ''),
                $this->csvEscape($item['full_name'] ?? ''),
                $this->csvEscape($item['employee_number'] ?? ''),
                $this->csvEscape($item['bank_account'] ?? ''),
                $this->csvEscape($item['bank_name'] ?? ''),
                number_format((float) $item['net_pay'], 3, '.', ''),
                $this->csvEscape($ref),
            ]);
        }

        $filename = 'wps_' . strtolower(str_replace(' ', '_', $company['name'] ?? 'company'))
            . '_' . $period . '.csv';

        return [
            'success'  => true,
            'content'  => implode("\r\n", $lines),
            'filename' => $filename,
        ];
    }

    protected function csvEscape(string $value): string
    {
        if (str_contains($value, ',') || str_contains($value, '"') || str_contains($value, "\n")) {
            return '"' . str_replace('"', '""', $value) . '"';
        }

        return $value;
    }
}
