<?php
declare(strict_types=1);

namespace App\Modules\HR\Services;

use App\Core\App;

final class BankTransferService
{
    public static function generateTransferData(int $periodId): array
    {
        $db = App::getInstance()->db();

        $period = $db->selectOne("SELECT * FROM hr_payroll_periods WHERE id = ?", [$periodId]);
        if (!$period) {
            return ['success' => false, 'error' => 'فترة الرواتب غير موجودة'];
        }

        $rows = $db->select(
            "SELECT pr.net_salary, pr.employee_number,
                    ep.first_name_ar, ep.last_name_ar,
                    ep.national_id, ep.bank_name, ep.bank_account_number
             FROM hr_payroll_runs pr
             JOIN hr_employee_profiles ep ON ep.id = pr.employee_profile_id
             WHERE pr.period_id = ? AND pr.status IN ('calculated', 'approved', 'paid')
                   AND ep.bank_account_number IS NOT NULL AND ep.bank_account_number != ''
                   AND ep.is_archived = 0
             ORDER BY ep.first_name_ar ASC",
            [$periodId]
        );

        if (empty($rows)) {
            return ['success' => false, 'error' => 'لا يوجد موظفون لديهم حسابات بنكية لهذه الفترة'];
        }

        $transfers = [];
        $totalAmount = '0.00';

        foreach ($rows as $row) {
            $name = trim(($row['first_name_ar'] ?? '') . ' ' . ($row['last_name_ar'] ?? ''));
            $transfers[] = [
                'employee_number'    => $row['employee_number'],
                'employee_name'      => $name,
                'national_id'        => $row['national_id'] ?? '',
                'bank_name'          => $row['bank_name'] ?? 'بنك الاسكندرية',
                'bank_account_number'=> $row['bank_account_number'],
                'net_salary'         => $row['net_salary'],
            ];
            $totalAmount = bcadd($totalAmount, $row['net_salary'], 2);
        }

        return [
            'success'      => true,
            'period'       => $period,
            'transfers'    => $transfers,
            'total_amount' => $totalAmount,
            'count'        => count($transfers),
        ];
    }

    public static function generateCsv(int $periodId): ?string
    {
        $result = self::generateTransferData($periodId);
        if (!$result['success']) {
            return null;
        }

        $lines = [];
        $lines[] = implode(',', ['م', 'اسم الموظف', 'الرقم القومي', 'رقم الحساب', 'صافي الراتب']);

        $i = 1;
        foreach ($result['transfers'] as $t) {
            $lines[] = implode(',', [
                $i,
                '"' . str_replace('"', '""', $t['employee_name']) . '"',
                $t['national_id'],
                $t['bank_account_number'],
                $t['net_salary'],
            ]);
            $i++;
        }

        $lines[] = implode(',', ['', '', '', 'الإجمالي', $result['total_amount']]);

        return "\xEF\xBB\xBF" . implode("\r\n", $lines);
    }
}
