<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\Order;
use Illuminate\Support\Collection;
use Kreait\Firebase\Factory;
use Kreait\Firebase\Database;
use Illuminate\Support\Facades\Log;

class Orders extends Component
{
    public Collection $orders;
    public string $filterStatus = 'pending';
    public ?int $selectedOrderId = null;
    public ?Order $selectedOrder = null;

    protected $listeners = ['orderStatusUpdated' => '$refresh'];

    private ?Database $firebaseDatabase = null;

    public function boot()
    {
        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 initialization failed: ' . $e->getMessage());
            $this->dispatch('notify', message: 'Gagal menghubungkan ke Firebase.', type: 'error');
        }
    }

    public function mount()
    {
        $this->loadOrders();
    }

    public function loadOrders()
    {
        $query = Order::with('items');

        if ($this->filterStatus && $this->filterStatus !== 'all') {
            switch ($this->filterStatus) {
                case 'pending':
                    // Tampilkan hanya pending dari metode manual (cash/qris)
                    $query->where('transaction_status', 'pending');
                    break;
                case 'pending_manual':
                    // Tampilkan hanya pending dari metode manual (cash/qris)
                    $query->where('transaction_status', 'pending')
                        ->whereIn('payment_method', ['cash', 'qris']);
                    break;

                case 'pending_midtrans':
                    // Tampilkan hanya pending dari metode manual (cash/qris)
                    $query->where('transaction_status', 'pending')
                        ->where('payment_method', 'midtrans')
                        ->whereNotNull('midtrans_transaction_id');
                    break;

                case 'confirmed':
                    // Tampilkan yang confirmed manual + settlement Midtrans
                    $query->where(function ($q) {
                        $q->where('transaction_status', 'confirmed')
                        ->orWhere('transaction_status', 'settlement');
                    });
                    break;

                case 'confirmed_manual':
                    $query->where('transaction_status', 'confirmed')
                        ->whereIn('payment_method', ['cash', 'qris']);
                    break;

                case 'settlement_midtrans':
                    $query->where(function ($q) {
                        $q->where('transaction_status', 'confirmed')
                        ->orWhere('transaction_status', 'settlement');
                    })
                    ->where('payment_method', 'midtrans')
                    ->whereNotNull('midtrans_transaction_id');
                    break;

                default:
                    // Filter status seperti biasa
                    $query->where('transaction_status', $this->filterStatus);
                    break;
            }
        }

        $this->orders = $query->latest()->get();
    }

    public function updatedFilterStatus()
    {
        $this->loadOrders();
    }

    public function showOrderDetails(int $orderId)
    {
        $this->selectedOrder = Order::with('items')->find($orderId);
        $this->selectedOrderId = $orderId;
        $this->dispatch('openOrderDetailsModal');
    }

    public function updateOrderStatus(int $orderId, string $newStatus)
    {
        $order = Order::find($orderId);

        if (!$order) {
            $this->dispatch('notify', message: 'Pesanan tidak ditemukan.', type: 'error');
            return;
        }

        $oldStatus = $order->transaction_status;

        $order->transaction_status = $newStatus;
        $order->save();

        if ($this->firebaseDatabase) {
            $tableId = $order->table_id;
            $tableRef = $this->firebaseDatabase->getReference($tableId);

            try {
                if ($newStatus === 'settlement' || $newStatus === 'confirmed') {
                    $tableRef->update([
                        'reserved_by' => $order->customer_name,
                        'sensors/table_activation_sensor_active' => 1,
                        'table_occupied' => 1,
                    ]);
                    Log::info("Firebase: Meja {$tableId} diperbarui ke occupied oleh pesanan {$order->id}.");
                } elseif ($newStatus === 'cancel' || $newStatus === 'expire') {
                    $tableRef->update([
                        'reserved_by' => 'N/A',
                        'sensors/table_activation_sensor_active' => 0,
                        'table_occupied' => 0,
                    ]);
                    Log::info("Firebase: Meja {$tableId} dibebaskan karena pesanan {$order->id} {$newStatus}.");
                }
            } catch (\Exception $e) {
                Log::error('Gagal memperbarui status meja di Firebase: ' . $e->getMessage(), [
                    'order_id' => $order->id,
                    'table_id' => $tableId,
                    'new_status' => $newStatus
                ]);
                $this->dispatch('notify', message: 'Gagal memperbarui status meja di Firebase.', type: 'error');
            }
        } else {
            Log::warning('Firebase Database instance not available. Cannot update table status.');
            $this->dispatch('notify', message: 'Tidak dapat memperbarui status meja (Firebase tidak terhubung).', type: 'warning');
        }

        $this->loadOrders();
        $this->dispatch('notify', message: 'Status pesanan ' . $order->id . ' berhasil diperbarui menjadi ' . $newStatus . '.', type: 'success');

        if ($this->selectedOrderId === $orderId) {
            $this->dispatch('closeOrderDetailsModal');
            $this->selectedOrderId = null;
            $this->selectedOrder = null;
        }
    }

    public function render()
    {
        return view('livewire.orders');
    }
}
