<?php

namespace App\Http\Controllers;

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


class OrderController extends Controller
{
    public function createSnapToken(Request $request)
    {
        Config::$serverKey = config('services.midtrans.server_key');
        Config::$isProduction = config('services.midtrans.is_production', false);
        Config::$isSanitized = true;
        Config::$is3ds = true;

        // Simpan data order ke session
        Session::put('order_data', [
            'customer_name' => $request->name,
            'customer_email' => $request->email,
            'table_id' => $request->table_id,
            'table_device_id' => $request->table_device_id,
            'total_amount' => $request->amount,
            'payment_method' => 'midtrans',
            'cart_items' => $request->cart_items, // array dari frontend
        ]);

        // Tambahkan item_details untuk Snap
        $items = [];
        foreach ($request->cart_items as $item) {
            $items[] = [
                'id' => $item['id'],
                'price' => $item['price'],
                'quantity' => $item['qty'],
                'name' => $item['name'],
            ];
        }

        $params = [
            'transaction_details' => [
                'order_id' => 'ORDER-' . time(),
                'gross_amount' => $request->amount,
            ],
            'item_details' => $items,
            'customer_details' => [
                'first_name' => $request->name,
                'email' => $request->email,
            ],
        ];

        $snapToken = Snap::getSnapToken($params);
        return response()->json(['token' => $snapToken]);
    }

    public function handleNotification(Request $request)
    {
        // Konfigurasi Midtrans
        Config::$serverKey = config('services.midtrans.server_key');
        Config::$isProduction = config('services.midtrans.is_production', false);
        Config::$isSanitized = true;
        Config::$is3ds = true;

        // Ambil isi notifikasi mentah
        $rawNotification = $request->getContent();
        Log::info('RAW MIDTRANS NOTIFICATION:', ['body' => $rawNotification]);

        $notification = json_decode($rawNotification);

        if (!$notification || !isset($notification->order_id)) {
            Log::error('Invalid Midtrans notification payload.', ['raw' => $rawNotification]);
            return response()->json(['message' => 'Invalid payload'], 400);
        }

        try {
            $midtransNotif = new Notification();

            $orderId = $midtransNotif->order_id;
            $transactionStatus = $midtransNotif->transaction_status;

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

            Log::info('Order ditemukan:', ['order' => $order]);
            // if (!$order) {
            //     Log::warning('Order not found: ' . $orderId);
            //     return response()->json(['message' => 'Order not found'], 404);
            // }

            // Ubah status jadi hanya 2 kondisi: confirmed / canceled
            if (in_array($transactionStatus, ['capture', 'settlement'])) {
                $order->transaction_status = 'confirmed';
            } else {
                $order->transaction_status = 'canceled';
            }

            $order->save();

            Log::info('Order updated:', [
                'order_id' => $orderId,
                'transaction_status' => $order->transaction_status,
            ]);

            return response()->json(['message' => 'Notification handled'], 200);

        } catch (\Exception $e) {
            Log::error('Midtrans Notification Error', ['error' => $e->getMessage()]);
            return response()->json(['message' => 'Notification failed'], 500);
        }
    }


    public function saveOrder(Request $request)
    {
        $snapResult = $request->input('snap_result');
        $orderData = Session::get('order_data');

        if (!$orderData) {
            return response()->json([
                'success' => false,
                'message' => 'Data order tidak ditemukan di session.',
            ]);
        }

        try {
            \DB::beginTransaction();

            $order = Order::create([
                'customer_name' => $orderData['customer_name'],
                'customer_email' => $orderData['customer_email'],
                'table_id' => $orderData['table_id'],
                'midtrans_transaction_id' => $snapResult['order_id'] ?? null,
                'total_amount' => $orderData['total_amount'],
                'payment_method' => $orderData['payment_method'],
                'transaction_status' => 'confirmed',
            ]);

            foreach ($orderData['cart_items'] as $item) {
                \App\Models\OrderItem::create([
                    'order_id' => $order->id,
                    'item_id' => $item['id'],
                    'item_name' => $item['name'],
                    'item_price' => $item['price'],
                    'quantity' => $item['qty'],
                    'total_price' => $item['total_price'],
                ]);
            }

            // Firebase update
            $firebase = (new \Kreait\Firebase\Factory)
                ->withServiceAccount(storage_path('app/firebase/.firebase_credentials.json'))
                ->createDatabase();

            $firebase->getReference($orderData['table_id'])->update([
                'sensors/table_activation_sensor_active' => 1,
                'reserved_by' => $orderData['customer_name'],
            ]);

            \DB::commit();
            Session::forget('order_data');

            return response()->json([
                'success' => true,
                'message' => 'Pesanan berhasil disimpan dan meja terupdate!',
            ]);
        } catch (\Exception $e) {
            \DB::rollBack();
            \Log::error('Gagal menyimpan pesanan: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Gagal menyimpan pesanan: ' . $e->getMessage(),
            ]);
        }
    }

    public function confirmOrder(Request $request)
    {
        $request->validate([
            'order_id' => 'required|string',
        ]);

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

        Log::info('Order ditemukan:', ['order' => $order]);

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

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

        return response()->json(['message' => 'Order status updated to confirmed'], 200);
    }


    public function index()
    {
        $order = Order::all();
        return view('pages.back.orders.index', compact('order'));
    }
}
