<?php

namespace App\Livewire\Forms\Studio\Master;

use App\Enums\Gender;
use App\Enums\UserStatus;
use App\Models\Employee;
use App\Models\User;
use App\Rules\PhoneNumber;
use App\Rules\UnsignedInteger;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
use Livewire\Form;

class UserForm extends Form
{
    public ?User $user = null;

    public string $full_name = '';

    public string $username = '';

    public string $email = '';

    public string $phone_number = '';

    public string $base_salary = '';

    public string $birthdate = '';

    public string $hire_date = '';

    public string $address = '';

    public string $gender = '';

    public string $status = '1';

    public array $outlet_ids = [];

    public function rules(): array
    {
        return [
            'full_name' => ['required', 'string', 'max:100'],
            'username' => ['required', 'alpha_num', 'min:5', 'max:20', Rule::unique('users', 'username')->ignore($this->user)],
            'email' => ['required', 'email', 'max:100', Rule::unique('users', 'email')->ignore($this->user)],
            'phone_number' => ['required', 'string', new PhoneNumber],
            'base_salary' => ['required', new UnsignedInteger],
            'birthdate' => ['required', 'date', 'before:'.Carbon::now()->subYears(18)->format('Y-m-d')],
            'hire_date' => ['required', 'date'],
            'address' => ['required', 'string'],
            'gender' => ['required', Rule::in(Gender::cases())],
            'status' => ['required', Rule::in(UserStatus::cases())],
            'outlet_ids' => ['required', 'array', 'min:1'],
            'outlet_ids.*' => Rule::exists('outlets', 'id'),
        ];
    }

    public function validationAttributes(): array
    {
        return [
            'full_name' => 'nama lengkap',
            'username' => 'nama pengguna',
            'phone_number' => 'nomor telepon',
            'base_salary' => 'gaji pokok',
            'birthdate' => 'tanggal lahir',
            'hire_date' => 'tanggal bergabung',
            'address' => 'alamat',
            'gender' => 'jenis kelamin',
            'outlet_ids' => 'outlet',
        ];
    }

    public function setUser(User $user)
    {
        $user->load(['employee', 'outlets']);

        $this->user = $user;
        $employee = $user->employee;

        $this->full_name = $employee->full_name;
        $this->username = $user->username;
        $this->email = $user->email;
        $this->phone_number = $employee->phone_number;
        $this->base_salary = $employee->base_salary;
        $this->birthdate = $employee->birthdate;
        $this->hire_date = $employee->hire_date;
        $this->address = $employee->address;
        $this->gender = $employee->gender->value;
        $this->status = $user->status->value;
        $this->outlet_ids = $user->outlets->pluck('id')->toArray();
    }

    public function store()
    {
        $this->validate();

        $data = $this->all();

        if ($data['status'] != UserStatus::ACTIVE) {
            $data['resign_date'] = now();
        } else {
            $data['resign_date'] = null;
        }

        DB::transaction(function () use ($data) {
            $user = User::create([
                ...$data,
                'password' => Hash::make(config('myconfig.password_default')),
                'referral_code' => generateReferralCode($data['username'], User::max('id') + 1),
                'status' => $data['status'],
            ]);

            Employee::create([
                'user_id' => $user->id,
                'full_name' => $data['full_name'],
                'code' => Employee::generateEmployeeCode(),
                'phone_number' => $data['phone_number'],
                'base_salary' => replaceCurrency($data['base_salary']),
                'birthdate' => $data['birthdate'],
                'hire_date' => $data['hire_date'],
                'address' => $data['address'],
                'gender' => $data['gender'],
            ]);

            $user->outlets()->attach($this->outlet_ids);
        });
    }

    public function update()
    {
        $this->validate();

        $data = $this->all();

        if ($data['status'] == UserStatus::SUSPENDED->value) {
            $data['closed_date'] = now()->toDateString();
        } else {
            $data['closed_date'] = null;
        }

        DB::transaction(function () use ($data) {
            $this->user->update([
                ...$data,
                'status' => $data['status'],
            ]);

            $this->user->employee->update([
                'user_id' => $this->user->id,
                'full_name' => $data['full_name'],
                'phone_number' => $data['phone_number'],
                'base_salary' => replaceCurrency($data['base_salary']),
                'birthdate' => $data['birthdate'],
                'hire_date' => $data['hire_date'],
                'address' => $data['address'],
                'gender' => $data['gender'],
            ]);

            $this->user->outlets()->sync($this->outlet_ids);
        });
    }
}
