<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use App\Models\StockLog;
use Midtrans\Config;
use Midtrans\Snap;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class PaymentController extends Controller
{
    /**
     * Fitur Beli Langsung
     */
    public function buyNow(Request $request, $id)
    {
        $product = Product::findOrFail($id);

        $cart = [
            $id => [
                "name"     => $product->name,
                "quantity" => 1,
                "price"    => $product->price,
                "image"    => $product->image
            ]
        ];

        session()->put('cart', $cart);

        return redirect()->route('user.cart.checkout');
    }

    public function process(Request $request)
    {
        $mode = session()->get('checkout_mode', 'cart');
        $cart = $mode === 'buy_now'
            ? session()->get('buy_now', [])
            : session()->get('cart', []);

        if (empty($cart)) {
            return response()->json(['error' => 'Keranjang kosong!'], 400);
        }

        $shippingFee = $request->shipping_fee ?? session()->get('shipping_fee', 0);

        if (!$request->address || !$request->phone) {
            return response()->json(['error' => 'Alamat pengiriman belum lengkap!'], 422);
        }

        try {
            return DB::transaction(function () use ($request, $cart, $shippingFee, $mode) {
                $subtotal = 0;
                foreach ($cart as $item) {
                    $subtotal += $item['price'] * $item['quantity'];
                }
                $totalPrice = $subtotal + $shippingFee;

                $order = Order::create([
                    'user_id'        => Auth::id(),
                    'order_number'   => 'VOGUE-' . strtoupper(uniqid()),
                    'receiver_name'  => Auth::user()->name,
                    'phone'          => $request->phone,
                    'full_address'   => $request->address,
                    'note'           => $request->note ?? null,   // ← TAMBAHAN
                    'total_price'    => $totalPrice,
                    'shipping_fee'   => $shippingFee,
                    'payment_method' => 'midtrans',
                    'payment_status' => 'pending',
                    'status'         => 'pending',
                ]);

                foreach ($cart as $id => $item) {
                    OrderItem::create([
                        'order_id'   => $order->id,
                        'product_id' => $id,
                        'quantity'   => $item['quantity'],
                        'price'      => $item['price'],
                    ]);
                }

                if ($mode === 'buy_now') {
                    session()->forget(['buy_now', 'checkout_mode']);
                } else {
                    session()->forget(['cart', 'shipping_fee', 'checkout_mode']);
                }

                Config::$serverKey    = env('MIDTRANS_SERVER_KEY');
                Config::$isProduction = env('MIDTRANS_IS_PRODUCTION', false);
                Config::$isSanitized  = true;
                Config::$is3ds        = true;

                $itemDetails = [
                    [
                        'id'       => 'shipping',
                        'price'    => (int) $shippingFee,
                        'quantity' => 1,
                        'name'     => 'Ongkos Kirim'
                    ]
                ];

                foreach ($cart as $id => $item) {
                    $itemDetails[] = [
                        'id'       => $id,
                        'price'    => (int) $item['price'],
                        'quantity' => (int) $item['quantity'],
                        'name'     => $item['name']
                    ];
                }

                $params = [
                    'transaction_details' => [
                        'order_id'     => $order->order_number,
                        'gross_amount' => (int) $totalPrice,
                    ],
                    'customer_details' => [
                        'first_name' => Auth::user()->name,
                        'email'      => Auth::user()->email,
                        'phone'      => $request->phone,
                    ],
                    'item_details' => $itemDetails,
                ];

                $snapToken = Snap::getSnapToken($params);
                $order->update(['snap_token' => $snapToken]);

                return response()->json([
                    'success'    => true,
                    'method'     => 'midtrans',
                    'snap_token' => $snapToken,
                    'order_id'   => $order->id,
                ]);
            });
        } catch (\Exception $e) {
            return response()->json(['error' => 'Gagal memproses: ' . $e->getMessage()], 500);
        }
    }
}