<?php

namespace App\Livewire\Studio\Information;

use App\Enums\PriceRequestStatus;
use App\Jobs\StorePushNotification;
use App\Models\PriceRequest as PriceRequestModel;
use App\Models\PushNotification;
use App\Traits\Notification\WithSubscribeNotification;
use App\Traits\WithAuthorization;
use App\Traits\WithConfirmation;
use App\Traits\WithToast;
use Flux\Flux;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Title('Permintaan Harga')]
class PriceRequest extends Component
{
    use WithAuthorization, WithConfirmation, WithSubscribeNotification, WithToast;

    public function approve(PriceRequestModel $priceRequest)
    {
        $this->canOrAbort('approve price request');

        $priceRequest->update([
            'status' => PriceRequestStatus::APPROVED->value,
            'finalized_at' => now(),
        ]);

        StorePushNotification::dispatch(
            PushNotification::where('user_id', $priceRequest->user_id)->get(),
            [
                'title' => 'Permintaan Harga Disetujui ✅',
                'body' => "Selamat! Permintaan untuk melihat harga beli {$priceRequest->module} sudah disetujui 🎉",
            ],
        );

        $this->dispatch('refreshDatatable');

        $this->toast('Permintaan harga berhasil disetujui.');

        Flux::modals()->close();
    }

    public function reject(PriceRequestModel $priceRequest)
    {
        $this->canOrAbort('reject price request');

        $priceRequest->update([
            'status' => PriceRequestStatus::REJECTED->value,
            'finalized_at' => now(),
        ]);

        StorePushNotification::dispatch(
            PushNotification::where('user_id', $priceRequest->user_id)->get(),
            [
                'title' => 'Permintaan Harga Ditolak ❌',
                'body' => "Maaf, permintaan untuk melihat harga beli {$priceRequest->module} tidak dapat dipenuhi 🙏",
            ],
        );

        $this->dispatch('refreshDatatable');

        $this->toast('Permintaan harga berhasil ditolak.');

        Flux::modals()->close();
    }

    public function render()
    {
        return view('livewire.studio.information.price-requests', [
            'pageTitle' => 'Permintaan Harga',
        ]);
    }
}
