<?php

namespace App\Traits;

use App\Jobs\StorePushNotification;
use App\Models\PriceRequest;
use App\Models\PushNotification;
use App\Models\User;
use Flux\Flux;
use Illuminate\Support\Facades\DB;

trait WithShowPrice
{
    public function requestPrice(string $module)
    {
        $recentRequest = PriceRequest::where('user_id', auth()->id())
            ->where('module', $module)
            ->pending()
            ->exists();

        if ($recentRequest) {
            $this->toast('Permohonan kamu sedang di proses oleh owner, mohon tunggu dan kami akan memberi tahu Anda jika prosesnya sudah selesai.', 'Peringatan', 'warning');
            Flux::modal('show-price')->close();

            return;
        }

        $owner = User::role(['owner', 'Developer'])->with('employee')->first();

        if (! $owner) {
            $this->toast('Owner belum terdaftar, silakan hubungi Admin.', 'Gagal', 'danger');
            Flux::modal('show-price')->close();

            return;
        }

        $causerName = auth()->user()->employee?->full_name;

        DB::transaction(function () use ($module, $owner, $causerName) {
            PriceRequest::create([
                'user_id' => auth()->id(),
                'module' => $module,
            ]);

            StorePushNotification::dispatch(
                PushNotification::all(),
                [
                    'title' => 'Permintaan Persetujuan Harga Beli',
                    'body' => "Haloo {$owner->employee?->full_name}, saya {$causerName}, saya ingin mengajukan permintaan persetujuan untuk mengakses data harga beli {$module}.",
                    'route' => route('studio.information.price_request.index'),
                ],
            );
        });

        $this->toast('Permintaan persetujuan berhasil dikirim.');

        Flux::modal('show-price')->close();
    }
}
