<?php

namespace App\Livewire\Studio\Setting;

use App\Models\Whatsapp as WhatsappModel;
use App\Traits\WithToast;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Title('Whatsapp')]
class Whatsapp extends Component
{
    use WithToast;

    public array $whatsapp = [];

    public function mount(): void
    {
        $whatsapp = WhatsappModel::first();

        $this->whatsapp = [
            'id' => $whatsapp?->id,
            'zawa_id' => $whatsapp?->zawa_id,
            'session_id' => $whatsapp?->session_id,
            'qr_code' => $whatsapp?->qr_code,
        ];
    }

    public function createSession(): void
    {
        try {
            $response = Http::post(config('services.zawa.url').'/authorize');

            if ($response->successful()) {
                $data = $response->json();

                WhatsappModel::updateOrCreate(
                    ['zawa_id' => $data['id']],
                    [
                        'session_id' => $data['sessionId'],
                    ]
                );

                $this->whatsapp['zawa_id'] = $data['id'];
                $this->whatsapp['session_id'] = $data['sessionId'];

                $this->toast('Berhasil membuat sesi WhatsApp');
            } else {
                $this->toast('Gagal membuat sesi WhatsApp', 'Gagal', 'danger');
            }
        } catch (\Throwable $e) {
            Log::error($e);
            $this->toast('Gagal membuat sesi WhatsApp, silakan coba lagi.', 'Gagal', 'danger');
        }
    }

    public function generateQrCode(): void
    {
        try {
            $response = Http::withHeaders([
                'id' => $this->whatsapp['zawa_id'],
                'session-id' => $this->whatsapp['session_id'],
            ])->get(config('services.zawa.url').'/qrcode');

            if ($response->successful()) {
                $data = $response->json();

                $qrBase64 = 'data:image/png;base64,'.$data['qrcode'];

                WhatsappModel::updateOrCreate(
                    ['zawa_id' => $this->whatsapp['zawa_id']],
                    [
                        'session_id' => $this->whatsapp['session_id'],
                        'qr_code' => $qrBase64,
                    ]
                );

                $this->whatsapp['qr_code'] = $qrBase64;

                $this->toast('Berhasil generate QR Code WhatsApp');
            } else {
                $this->toast('Gagal generate QR Code, silakan coba lagi.', 'Gagal', 'danger');
            }
        } catch (\Throwable $e) {
            Log::error($e);
            $this->toast('Terjadi kesalahan saat generate QR Code,silakan hubungi Administrator.', 'Gagal', 'danger');
        }
    }

    public function render()
    {
        return view('livewire.studio.setting.whatsapp', [
            'pageTitle' => 'Whatsapp',
        ]);
    }
}
