<?php

namespace App\Services;

use App\Models\Branch;
use App\Models\StaffProfile;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;

class StaffService
{
    public function generateEmployeeCode(): string
    {
        $last = StaffProfile::orderByDesc('id')->first();
        $num = $last ? (int) Str::after($last->employee_code, 'EMP') + 1 : 1;
        return 'EMP' . str_pad((string) $num, 4, '0', STR_PAD_LEFT);
    }

    public function paginate(array $filters = [], ?int $branchId = null, int $perPage = 15): LengthAwarePaginator
    {
        $query = StaffProfile::query()->with(['branch', 'user']);

        if ($branchId) {
            $query->where('branch_id', $branchId);
        }

        $query->when(Arr::get($filters, 'search'), function (Builder $q, $search) {
            $q->where(function (Builder $q2) use ($search) {
                $q2->where('first_name', 'like', "%{$search}%")
                    ->orWhere('last_name', 'like', "%{$search}%")
                    ->orWhere('full_name', 'like', "%{$search}%")
                    ->orWhere('employee_code', 'like', "%{$search}%")
                    ->orWhere('mobile', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%");
            });
        })
            ->when(Arr::get($filters, 'branch_id'), fn (Builder $q, $id) => $q->where('branch_id', $id))
            ->when(Arr::get($filters, 'status'), fn (Builder $q, $s) => $q->where('status', $s))
            ->when(Arr::get($filters, 'designation'), fn (Builder $q, $d) => $q->where('designation', 'like', "%{$d}%"))
            ->orderBy('full_name');

        return $query->paginate($perPage)->withQueryString();
    }

    public function create(array $data): StaffProfile
    {
        $data['employee_code'] = $data['employee_code'] ?? $this->generateEmployeeCode();
        $data['full_name'] = trim(($data['first_name'] ?? '') . ' ' . ($data['last_name'] ?? ''));
        $staff = StaffProfile::create($data);
        if (!empty($data['service_ids'])) {
            $staff->services()->sync($data['service_ids']);
        }
        return $staff->fresh();
    }

    public function update(StaffProfile $staff, array $data): StaffProfile
    {
        $data['full_name'] = trim(($data['first_name'] ?? '') . ' ' . ($data['last_name'] ?? ''));
        $staff->update($data);
        if (array_key_exists('service_ids', $data)) {
            $staff->services()->sync($data['service_ids'] ?? []);
        }
        return $staff->fresh();
    }
}
