<?php

namespace App\Services\Admin\Users;

use App\Models\User;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class AdministratorService
{
    public function paginated(int $perPage = 25, string $search = '', ?string $gender = null): LengthAwarePaginator
    {
        return User::select(['id', 'username', 'email', 'is_active'])
            ->with([
                'profile:id,user_id,full_name,phone_number,gender',
                'roles:id,name',
            ])
            ->whereHas('roles', fn ($q) => $q->whereIn('name', ['staff-admin', 'staff-keuangan']))
            ->when($search, fn ($q) => $q->where(function ($query) use ($search) {
                $query->where('username', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%")
                    ->orWhereHas('profile', fn ($q) => $q->where('full_name', 'like', "%{$search}%"));
            }))
            ->when($gender, fn ($q) => $q->whereHas('profile', fn ($q) => $q->where('gender', $gender)))
            ->latest()
            ->paginate($perPage);
    }

    public function create(array $data): User
    {
        return DB::transaction(function () use ($data) {
            $user = User::create([
                'username' => $data['username'],
                'email' => $data['email'],
                'password' => Hash::make(config('app.default_password')),
            ]);

            $user->assignRole($data['role']);

            $user->profile()->create([
                'full_name' => $data['full_name'],
                'phone_number' => $data['phone_number'],
                'address' => $data['address'],
                'gender' => $data['gender'],
                'birth_date' => $data['birth_date'],
                'birth_place' => $data['birth_place'],
            ]);

            return $user;
        });
    }

    public function update(User $user, array $data): User
    {
        DB::transaction(function () use ($user, $data) {
            $user->update([
                'username' => $data['username'],
                'email' => $data['email'],
            ]);

            $user->syncRoles($data['role']);

            $user->profile()->updateOrCreate([], [
                'full_name' => $data['full_name'],
                'phone_number' => $data['phone_number'],
                'address' => $data['address'],
                'gender' => $data['gender'],
                'birth_date' => $data['birth_date'],
                'birth_place' => $data['birth_place'],
            ]);
        });

        return $user->fresh(['profile', 'roles']);
    }

    public function delete(User $user): void
    {
        DB::transaction(function () use ($user) {
            $user->profile()->delete();
            $user->delete();
        });
    }

    public function resetPassword(User $user): void
    {
        $user->update([
            'password' => Hash::make(config('app.default_password')),
        ]);
    }

    public function updateUserStatus(User $user, bool $isActive): void
    {
        $user->update(['is_active' => $isActive]);
    }
}
