<?php
namespace App\Livewire;

use Livewire\Component;
use Kreait\Firebase\Factory;
use Kreait\Firebase\Database;
use Illuminate\Support\Facades\Log;

class AdminTables extends Component
{
    public $tables = [];
    public $errorMessage = null;
    private ?Database $firebaseDatabase = null;

    public function mount()
    {
        try {
            $factory = (new Factory)
                ->withServiceAccount(config('services.firebase.credentials'))
                ->withDatabaseUri(config('services.firebase.database_url'));

            $this->firebaseDatabase = $factory->createDatabase();
        } catch (\Exception $e) {
            Log::error('Firebase init failed: ' . $e->getMessage());
            $this->dispatch('notify', message: 'Firebase tidak terhubung.', type: 'error');
        }

        $this->loadTables();
    }

    public function loadTables()
    {
        if (!$this->firebaseDatabase) {
            $this->tables = [];
            return;
        }

        try {
            $data = $this->firebaseDatabase->getReference()->getValue();
            $this->tables = $data ?? [];

            // Kirim data ke console log
            $this->dispatch('logToConsole', message: json_encode($this->tables));
        } catch (\Exception $e) {
            $this->tables = [];
            $this->dispatch('notify', message: 'Gagal mengambil data meja.', type: 'error');
        }
    }
    public function clearTable($tableId)
    {
        if (!$this->firebaseDatabase) return;

        try {
            $this->firebaseDatabase->getReference($tableId)->update([
                'reserved_by' => 'N/A',
                'sensors/table_activation_sensor_active' => 0,
                'table_occupied' => 0,
            ]);

            $this->dispatch('notify', message: 'Meja ' . $tableId . ' berhasil dikosongkan.', type: 'success');
            $this->loadTables();
        } catch (\Exception $e) {
            Log::error("Gagal kosongkan meja {$tableId}: " . $e->getMessage());
            $this->dispatch('notify', message: 'Gagal mengosongkan meja.', type: 'error');
        }
    }

    public function render()
    {
        $this->dispatch('logToConsole', message: json_encode($this->tables));
        return view('livewire.admin-tables');
    }
}
