<?php

namespace App\Livewire;

use Livewire\Component;
use Midtrans\Config;
use Midtrans\Snap;
use App\Models\Order;
use App\Models\OrderItem;

class MidtransPayment extends Component
{
    public $snapToken;
    public $transactionId;
    public $orderId;

    protected $listeners = [
        'midtransSuccess' => 'handleSuccess',
        'midtransPending' => 'handlePending',
        'midtransError' => 'handleError',
    ];

    public function mount($midtrans_transaction_id)
    {
        $this->transactionId = $midtrans_transaction_id;

        // Ambil order_id berdasarkan transaction_id
        $order = Order::where('midtrans_transaction_id', $this->transactionId)->firstOrFail();
        $this->orderId = $order->id;

        // Konfigurasi Midtrans
        Config::$serverKey = config('services.midtrans.server_key');
        Config::$isProduction = config('services.midtrans.is_production');
        Config::$isSanitized = true;
        Config::$is3ds = true;

        // Detail customer
        $customerDetails = [
            'first_name' => substr($order->customer_name ?? 'Customer', 0, 50),
            'email' => $order->customer_email ?? 'guest@gmail.com',
            'phone' => '08123456789',
        ];

        // Ambil item pesanan
        $orderItems = OrderItem::where('order_id', $order->id)->get();
        $itemDetails = $orderItems->map(function ($item) {
            return [
                'id' => $item->id,
                'price' => intval($item->item_price),
                'quantity' => intval($item->quantity),
                'name' => substr($item->item_name, 0, 50),
            ];
        })->toArray();

        // Hitung total manual
        $total = array_reduce($itemDetails, function ($carry, $item) {
            return $carry + ($item['price'] * $item['quantity']);
        }, 0);

        $params = [
            'transaction_details' => [
                'order_id' => (string) $this->transactionId,
                'gross_amount' => $total,
            ],
            'customer_details' => $customerDetails,
            'item_details' => $itemDetails,
            'enabled_payments' => ['credit_card', 'bca_va', 'bni_va', 'bri_va'],
        ];

        // Dapatkan Snap Token
        $this->snapToken = Snap::getSnapToken($params);
    }

    public function handleSuccess($result)
    {
        \Log::info('Pembayaran sukses:', $result);

        Order::where('midtrans_transaction_id', $this->transactionId)->update([
            'transaction_status' => 'confirmed',
        ]);

        session()->flash('message', 'Pembayaran berhasil!');
    }

    public function handlePending($result)
    {
        \Log::info('Pembayaran pending:', $result);

        // Jika ingin disimpan sementara
        Order::where('midtrans_transaction_id', $this->transactionId)->update([
            'transaction_status' => 'pending',
        ]);

        session()->flash('message', 'Pembayaran sedang diproses.');
    }

    public function handleError($result)
    {
        \Log::error('Pembayaran error:', $result);

        Order::where('midtrans_transaction_id', $this->transactionId)->update([
            'transaction_status' => 'cancelled',
        ]);

        session()->flash('message', 'Terjadi kesalahan saat pembayaran.');
    }

    public function render()
    {
        return view('livewire.midtrans-payment')->layout('components.layouts.base');
    }
}
