<?php

namespace App\Services;

use App\Models\User;
use App\Models\Role;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class StaffService
{
    public function createStaff(array $data)
    {
        $data['password'] = Hash::make($data['password']);
        $data['username'] = $this->generateUsername($data['firstname']);

        $staff = User::create($data);

        if (isset($data['role_id'])) {
            $staff->roles()->attach($data['role_id']);
        }

        return $staff;
    }

    private function generateUsername($firstname)
    {
        do {
            $randomNumber = rand(1, 9999);
            $username = strtolower($firstname) . $randomNumber;
            // remove spaces
            $username = str_replace(' ', '', $username);
        } while (User::where('username', $username)->exists());

        return $username;
    }

    public function updateStaff(User $staff, array $data)
    {
        if (isset($data['password']) && !empty($data['password'])) {
            $data['password'] = Hash::make($data['password']);
        } else {
            unset($data['password']);
        }

        $staff->update($data);

        if (isset($data['role_id'])) {
            $staff->roles()->sync([$data['role_id']]);
        }

        return $staff;
    }

    public function deleteStaff(User $staff)
    {
        $staff->roles()->detach();
        $staff->delete();

        return true;
    }
}
