<?php

namespace App\Traits;

use App\Models\Bottle;
use App\Models\Perfume;
use App\Models\PriceRequest;
use App\Models\Product;
use App\Models\User;
use App\Models\Whatsapp;
use Flux\Flux;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\URL;

trait WithShowPrice
{
    public function requestPrice(string $module)
    {
        switch ($module) {
            case 'perfume':
                $label = 'parfum';
                $model = Perfume::class;
                break;

            case 'product':
                $label = 'produk';
                $model = Product::class;
                break;

            default:
                $label = 'botol';
                $model = Bottle::class;
                break;
        }

        $recentRequest = PriceRequest::where('user_id', auth()->id())
            ->where('model', $model)
            ->where('created_at', '>', now()->subMinutes(30))
            ->exists();

        if ($recentRequest) {
            $this->toast('Kamu baru saja mengajukan permintaan, tautan persetujuan masih berlaku selama 30 menit.', 'Peringatan', 'warning');
            Flux::modal('show-price')->close();

            return;
        }

        $whatsapp = Whatsapp::first();
        $owner = User::role('owner')->with('employee')->first();

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

            return;
        }

        $phoneNumber = formatPhoneNumber($owner->employee?->phone_number, '62');

        try {
            $priceRequest = PriceRequest::create([
                'user_id' => auth()->id(),
                'model' => $model,
                'expires_at' => now()->addMinutes(30),
            ]);

            $signedUrl = URL::temporarySignedRoute(
                'price-request.approve',
                $priceRequest->expires_at,
                ['priceRequest' => $priceRequest->hash]
            );

            $priceRequest->update([
                'signature' => hash('sha256', $signedUrl),
            ]);

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

            $response = Http::withHeaders([
                'id' => $whatsapp->zawa_id,
                'session-id' => $whatsapp->session_id,
                'Content-Type' => 'application/json',
            ])->post(config('services.zawa.url').'/message', [
                'phone' => $phoneNumber,
                'type' => 'text',
                'text' => "Haloo {$owner->employee?->full_name}, saya {$causerName}, "
                    ."saya ingin mengajukan permintaan persetujuan untuk mengakses data harga beli {$label}."
                    ."\n\nSilakan klik tautan berikut untuk menyetujui:\n\n{$signedUrl}",
            ]);

            if ($response->successful()) {
                $this->toast('Permintaan persetujuan berhasil dikirim.');
            } else {
                $this->toast('Permintaan persetujuan gagal dikirim, silakan coba lagi.', 'Gagal', 'danger');
            }
        } catch (\Throwable $th) {
            Log::error($th->getMessage());
            $this->toast('Opps, terjadi kesalahan. Silakan coba lagi dan jika masih terjadi, hubungi Administrator.', 'Gagal', 'danger');
        }

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