<?php

namespace App\Services;

use App\Models\Employee;
use App\Models\EmployeeDocument;
use App\Models\EmployeeSalaryLine;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;

class EmployeeFormService
{
    public function buildAttributes(array $validated, bool $isInactive = false): array
    {
        $displayName = trim($validated['display_name'] ?? '');
        $validated['name'] = $displayName !== ''
            ? $displayName
            : trim(implode(' ', array_filter([
                $validated['first_name'] ?? null,
                $validated['middle_name'] ?? null,
                $validated['last_name'] ?? null,
            ])));

        $validated['display_name'] = $displayName !== '' ? $displayName : $validated['name'];
        $validated['is_active'] = !$isInactive;

        if (array_key_exists('terminated_employee', $validated)) {
            $validated['terminated_employee'] = (bool) $validated['terminated_employee'];
        }

        if (!empty($validated['account_no'])) {
            $validated['bank_account'] = $validated['account_no'];
        }

        unset(
            $validated['is_inactive'],
            $validated['account_no'],
            $validated['earnings'],
            $validated['deductions'],
            $validated['irregulars'],
            $validated['documents']
        );

        return $validated;
    }

    public function syncSalaryLines(Employee $employee, Request $request): void
    {
        $employee->salaryLines()->delete();

        foreach (['earning' => 'earnings', 'deduction' => 'deductions', 'irregular' => 'irregulars'] as $type => $key) {
            $rows = $request->input($key, []);
            if (!is_array($rows)) {
                continue;
            }

            foreach ($rows as $index => $row) {
                if (!is_array($row)) {
                    continue;
                }

                $componentId = $row['salary_component_id'] ?? null;
                $componentName = trim($row['component_name'] ?? '');
                $amount = (float) ($row['amount'] ?? 0);

                if (!$componentId && $componentName === '' && $amount <= 0) {
                    continue;
                }

                EmployeeSalaryLine::create([
                    'employee_id'         => $employee->id,
                    'line_type'           => $type,
                    'salary_component_id' => $componentId ?: null,
                    'component_name'      => $componentName ?: null,
                    'amount'              => $amount,
                    'validity'            => $row['validity'] ?? 'Unlimited',
                    'qty_per_year'        => isset($row['qty_per_year']) && $row['qty_per_year'] !== ''
                        ? (int) $row['qty_per_year']
                        : null,
                    'sort_order'          => $index + 1,
                ]);
            }
        }
    }

    public function storeDocuments(Employee $employee, Request $request): void
    {
        if (!$request->hasFile('documents')) {
            return;
        }

        $maxKb = (int) (\App\Models\Setting::get($employee->company_id, 'max_attachment_size_kb', 10240));
        $maxBytes = max(256, $maxKb) * 1024;

        /** @var UploadedFile[] $files */
        $files = $request->file('documents');
        foreach ($files as $file) {
            if (!$file || !$file->isValid()) {
                continue;
            }
            if ($file->getSize() > $maxBytes) {
                continue;
            }

            $path = $file->store("employee-documents/{$employee->company_id}/{$employee->id}", 'local');

            EmployeeDocument::create([
                'employee_id'   => $employee->id,
                'original_name' => $file->getClientOriginalName(),
                'file_path'     => $path,
                'file_size'     => (int) $file->getSize(),
                'mime_type'     => $file->getClientMimeType(),
            ]);
        }
    }

    public function deleteDocument(EmployeeDocument $document): void
    {
        Storage::disk('local')->delete($document->file_path);
        $document->delete();
    }
}
