<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Midtrans\Config;
use Midtrans\Snap;
use App\Models\Order;
use App\Models\OrderItem;
use Kreait\Firebase\Factory;
use Illuminate\Support\Facades\Log;

class PaymentController extends Controller
{
    public function __construct()
    {
        // Konfigurasi Midtrans
        Config::$serverKey = config('services.midtrans.server_key');
        Config::$isProduction = config('services.midtrans.is_production');
        Config::$isSanitized = true;
        Config::$is3ds = true;
    }

    public function show($midtrans_transaction_id)
    {
        try {
            // Ambil order_id berdasarkan transaction_id
            $order = Order::where('midtrans_transaction_id', $midtrans_transaction_id)->firstOrFail();

            // 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) $midtrans_transaction_id,
                    'gross_amount' => $total,
                ],
                'customer_details' => $customerDetails,
                'item_details' => $itemDetails,
                'enabled_payments' => ['credit_card', 'bca_va', 'bni_va', 'bri_va'],
            ];

            // Dapatkan Snap Token
            $snapToken = Snap::getSnapToken($params);

            return view('payment.show', [
                'snapToken' => $snapToken,
                'transactionId' => $midtrans_transaction_id,
                'orderId' => $order->id,
                'order' => $order
            ]);

        } catch (\Exception $e) {
            \Log::error('Error generating payment token: ' . $e->getMessage());
            return redirect()->back()->withErrors('Terjadi kesalahan saat memproses pembayaran.');
        }
    }

    public function handleCallback(Request $request)
    {
        try {
            // Ambil data dari request
            $transactionId = $request->input('order_id');
            $transactionStatus = $request->input('transaction_status');
            $fraudStatus = $request->input('fraud_status');

            \Log::info('Midtrans callback received:', $request->all());

            // Cari order berdasarkan transaction_id
            $order = Order::where('midtrans_transaction_id', $transactionId)->first();

            if (!$order) {
                \Log::error('Order tidak ditemukan untuk transaction_id: ' . $transactionId);
                return response('Order not found', 404);
            }

            // Tentukan status berdasarkan response Midtrans
            if ($transactionStatus == 'capture') {
                if ($fraudStatus == 'challenge') {
                    $status = 'pending';
                } else if ($fraudStatus == 'accept') {
                    $status = 'confirmed';
                }
            } else if ($transactionStatus == 'settlement') {
                $status = 'confirmed';
            } else if ($transactionStatus == 'pending') {
                $status = 'pending';
            } else if (in_array($transactionStatus, ['deny', 'expire', 'cancel'])) {
                $status = 'cancelled';
            } else {
                $status = 'pending';
            }

            // Update status order
            $order->update([
                'transaction_status' => $status,
                'payment_type' => $request->input('payment_type'),
                'transaction_time' => $request->input('transaction_time'),
            ]);

            \Log::info("Order {$order->id} status updated to: {$status}");

            return response('OK', 200);

        } catch (\Exception $e) {
            \Log::error('Error handling Midtrans callback: ' . $e->getMessage());
            return response('Error', 500);
        }
    }

        public function updateStatus(Request $request)
    {
        try {
            // Validasi atau debugging awal
            \Log::info('Update status masuk:', $request->all());

            $orderId = $request->input('order_id');
            $transactionStatus = $request->input('transaction_status');
            $transactionId = $request->input('transaction_id');

            // Contoh update tabel order
            $order = Order::where('id', $orderId)->first();

            if (!$order) {
                return response()->json(['message' => 'Order not found'], 404);
            }

            $order->transaction_status = $transactionStatus;
            $order->transaction_id = $transactionId;
            $order->save();

            return response()->json(['message' => 'Status updated']);
        } catch (\Exception $e) {
            \Log::error('Update gagal:', ['error' => $e->getMessage()]);
            return response()->json(['error' => 'Gagal update status'], 500);
        }
    }

    public function success($order_id)
    {
        \Log::info('Pembayaran sukses dari frontend: ' . $order_id);

        $order = Order::where('midtrans_transaction_id', $order_id)->first();

        if ($order) {
            $order->transaction_status = 'confirmed';
            $order->save();

            try {
                // Inisialisasi Firebase
                $factory = (new Factory)
                    ->withServiceAccount(config('services.firebase.credentials'))
                    ->withDatabaseUri(config('services.firebase.database_url'));

                $firebase = $factory->createDatabase();

                // Update ke Firebase RTDB
                $firebase->getReference($order->table_id)->update([
                    'reserved_by' => $order->customer_name,
                    'sensors/table_activation_sensor_active' => 1,
                    'table_occupied' => 1,
                ]);

                Log::info("Firebase: Meja {$order->table_id} diupdate untuk order {$order->id}");
            } catch (\Exception $e) {
                Log::error('Gagal update Firebase dari controller success(): ' . $e->getMessage());
            }

            return redirect()->route('home')->with('success', 'Pembayaran berhasil.');
        }

        return redirect()->route('home')->withErrors('Order tidak ditemukan.');
    }

    public function pending(Request $request)
    {
        dd('Masuk ke pending', $request->all());
        $transactionId = $request->input('order_id');

        \Log::info('Pembayaran pending dari frontend:', $request->all());

        $order = Order::where('midtrans_transaction_id', $transactionId)->first();

        return redirect()->route('home')->withErrors('Order tidak ditemukan.');
    }

    public function error(Request $request)
    {
        dd('Masuk ke error', $request->all());
        $transactionId = $request->input('order_id');

        \Log::error('Pembayaran error dari frontend:', $request->all());

        $order = Order::where('midtrans_transaction_id', $transactionId)->first();


        return redirect()->route('home')->withErrors('Order tidak ditemukan.');
    }
}
