<?php

namespace App\Http\Controllers;

use App\Models\Cart;
use App\Models\Order;
use App\Models\Address;
use App\Models\OrderItem;
use App\Models\ShippingRate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\{Log, Auth, DB};
use Midtrans\{Snap, Config};

class CheckoutController extends Controller
{
    public function index()
    {
        $userId = Auth::id();

        $cartItems = Cart::where('user_id', $userId)
            ->where('is_selected', true)
            ->with(['product.images', 'variant.images', 'product.category'])
            ->get();

        if ($cartItems->isEmpty()) {
            return redirect()->route('cart.index')->with('error', 'Pilih produk di keranjang terlebih dahulu.');
        }

        $addresses = Address::where('user_id', $userId)
            ->with('city_rel')
            ->orderBy('is_default', 'desc')
            ->get();

        $shippingRates = ShippingRate::all();
        $total = $cartItems->sum(fn($item) => $item->quantity * $item->price_at_add);

        return view('checkout.index', compact('cartItems', 'addresses', 'total', 'shippingRates'));
    }

    public function generateSnapToken(Request $request)
    {
        // Validasi input agar data notes tidak hilang
        $request->validate([
            'address_id'       => 'required|exists:addresses,id',
            'shipping_rate_id' => 'required|exists:shipping_rates,id',
            'notes'            => 'nullable|string|max:500',
        ]);

        try {
            Config::$serverKey    = config('midtrans.server_key');
            Config::$isProduction = config('midtrans.is_production');
            Config::$isSanitized  = true;
            Config::$is3ds        = true;

            $userId    = Auth::id();
            $cartItems = Cart::where('user_id', $userId)
                            ->where('is_selected', true)
                            ->with('product')
                            ->get();

            if ($cartItems->isEmpty()) {
                return response()->json(['error' => 'Keranjang kosong.'], 400);
            }

            $shipping  = ShippingRate::findOrFail($request->shipping_rate_id);
            $address   = Address::with(['city_rel', 'province_rel'])->findOrFail($request->address_id);

            $subtotal   = $cartItems->sum(fn($item) => $item->quantity * $item->price_at_add);
            $grandTotal = $subtotal + $shipping->cost; // Total Produk + Ongkir
            $orderId    = 'LOKA-' . time() . '-' . $userId;

            // Database Transaction: Simpan Order, Item, dan Catatan
            $order = DB::transaction(function () use ($cartItems, $userId, $address, $shipping, $grandTotal, $orderId, $request) {
                $fullAddress = "{$address->recipient_name} | {$address->phone} | {$address->address}, " . ($address->city_rel->name ?? $address->city);

                // SIMPAN KE TABEL ORDERS
                $newOrder = Order::create([
                    'user_id'          => $userId,
                    'address_id'       => $address->id,
                    'order_number'     => $orderId,
                    'shipping_cost'    => $shipping->cost,
                    'shipping_method'  => $shipping->name,
                    'total_price'      => $grandTotal,
                    'status'           => 'waiting_payment',
                    'payment_method'   => 'midtrans',
                    'payment_type'     => 'midtrans',
                    'shipping_address' => $fullAddress,
                    'notes'            => $request->notes, // <--- CATATAN DISIMPAN DI SINI
                ]);

                // SIMPAN KE TABEL ORDER_ITEMS
                foreach ($cartItems as $item) {
                    OrderItem::create([
                        'order_id'           => $newOrder->id,
                        'product_id'         => $item->product_id,
                        'product_variant_id' => $item->product_variant_id,
                        'quantity'           => $item->quantity,
                        'price'              => $item->price_at_add,
                        'subtotal'           => $item->quantity * $item->price_at_add,
                    ]);
                }

                // Hapus item di keranjang karena sudah jadi order
                Cart::where('user_id', $userId)->where('is_selected', true)->delete();

                return $newOrder;
            });

            // Persiapkan Data untuk Midtrans (Item Details)
            $midtrans_items = $cartItems->map(fn($item) => [
                'id'       => (string) ($item->product_variant_id ?? $item->product_id),
                'price'    => (int) $item->price_at_add,
                'quantity' => (int) $item->quantity,
                'name'     => substr($item->product->name, 0, 50),
            ])->toArray();

            // Masukkan Ongkir ke detail Midtrans agar harga sinkron
            $midtrans_items[] = [
                'id'       => 'SHIPPING_FEE',
                'price'    => (int) $shipping->cost,
                'quantity' => 1,
                'name'     => 'Ongkir: ' . $shipping->name,
            ];

            $params = [
                'transaction_details' => [
                    'order_id'     => $orderId,
                    'gross_amount' => (int) $grandTotal, // Total Akhir
                ],
                'customer_details' => [
                    'first_name' => Auth::user()->name,
                    'email'      => Auth::user()->email,
                ],
                'item_details' => $midtrans_items,
            ];

            $snapToken = Snap::getSnapToken($params);

            Cart::where('user_id', $userId)->where('is_selected', true)->delete();

            return response()->json([
                'snap_token' => $snapToken,
                'order_id'   => $orderId,
            ]);

        } catch (\Exception $e) {
            Log::error('Snap Token Error: ' . $e->getMessage());
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }
}