<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Address;
use App\Models\Order;
use App\Models\Jasa;
use App\Models\StockHistory;

class OrderController extends Controller
{
    public function buyNow(Request $request, $id)
{
    $product  = \App\Models\Product::findOrFail($id);
    $quantity = $request->input('quantity', 1);

    if ($product->stock < $quantity) {
        return redirect()->back()->with('error', 'Stok tidak mencukupi!');
    }

    $userId    = auth()->id();
    $addresses = Address::where('user_id', $userId)->get();
    $provinces = DB::table('provinces')->get();

    // Tambah ini supaya view tidak error
    $items = collect();

    return view('orders.checkout', compact('product', 'addresses', 'quantity', 'provinces', 'items'));
}

    public function store(Request $request)
{
    $userId = auth()->id();
    $user   = auth()->user();

    // ===== ALUR DARI CART =====
    if ($request->has('cart_item_ids') && $request->cart_item_ids) {

        $ids   = explode(',', $request->cart_item_ids);
        $items = \App\Models\Cart::whereIn('id', $ids)
                    ->where('user_id', $userId)
                    ->with('product')
                    ->get();

        if ($items->isEmpty()) {
            return response()->json(['success' => false, 'message' => 'Item tidak ditemukan!'], 404);
        }

        $addressId  = (int) $request->address_id;
        $totalHarga = (int) $items->sum(function($i) { return $i->harga * $i->jumlah; });

        $result = DB::transaction(function () use ($userId, $addressId, $items, $totalHarga, $user) {

            // 1. Buat Order
            $order = \App\Models\Order::create([
                'user_id'     => $userId,
                'address_id'  => $addressId,
                'total_harga' => $totalHarga,
                'status'      => 'menunggu',
            ]);

            // 2. Buat Order Items (semua item dari cart)
            $itemDetails = [];
            foreach ($items as $item) {
                $subtotal = (int) ($item->harga * $item->jumlah);

                \App\Models\OrderItem::create([
                    'order_id'   => $order->id,
                    'product_id' => $item->product_id,
                    'harga'      => (int) $item->harga,
                    'jumlah'     => $item->jumlah,
                    'subtotal'   => $subtotal,
                ]);

                // 3. Kurangi stok tiap produk & Catat Riwayat
                $stokSebelum = $item->product->stock;
                $item->product->decrement('stock', $item->jumlah);
                $stokSesudah = $item->product->stock;

                StockHistory::create([
                    'product_id'   => $item->product_id,
                    'nama_produk'  => $item->product->name,
                    'status'       => 'keluar',
                    'jumlah'       => $item->jumlah,
                    'stok_sebelum' => $stokSebelum,
                    'stok_sesudah' => $stokSesudah,
                    'keterangan'   => 'Dibeli oleh ' . $user->name . ' sebanyak ' . $item->jumlah . ' unit via Cart (Order #' . $order->id . ')',
                ]);

                $itemDetails[] = [
                    'id'       => $item->product_id,
                    'price'    => (int) $item->harga,
                    'quantity' => $item->jumlah,
                    'name'     => substr($item->product->name, 0, 50),
                ];
            }

            // 4. Hapus item dari cart setelah order dibuat
            \App\Models\Cart::whereIn('id', $items->pluck('id'))->delete();

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

            $params = [
                'transaction_details' => [
                    'order_id'     => 'ORDER-' . $order->id . '-' . time(),
                    'gross_amount' => $totalHarga,
                ],
                'customer_details' => [
                    'first_name' => $user->name,
                    'email'      => $user->email,
                    'phone'      => $user->phone ?? '',
                ],
                'item_details' => $itemDetails,
            ];

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

            // 6. Simpan Payment
            \App\Models\Payment::create([
                'order_id'      => $order->id,
                'metode'        => 'midtrans',
                'snap_token'    => $snapToken,
                'status'        => 'menunggu',
                'tanggal_bayar' => now(),
            ]);

            return [
                'snap_token'   => $snapToken,
                'order_id'     => $order->id,
                'redirect_url' => route('order.success', $order->id),
            ];
        });

        return response()->json($result);
    }

    // ===== ALUR DIRECT BUY (kode lama, tetap jalan) =====
    $request->validate([
        'address_id'        => 'required',
        'direct_product_id' => 'required',
    ]);

    $productId  = (int) $request->input('direct_product_id');
    $addressId  = (int) $request->input('address_id');
    $qty        = (int) $request->input('quantity', 1);
    $product    = \App\Models\Product::findOrFail($productId);
    $totalHarga = (int) ($product->price * $qty);

    $result = DB::transaction(function () use ($userId, $productId, $addressId, $product, $qty, $totalHarga, $user) {

        $order = \App\Models\Order::create([
            'user_id'     => $userId,
            'address_id'  => $addressId,
            'total_harga' => $totalHarga,
            'status'      => 'menunggu',
        ]);

        \App\Models\OrderItem::create([
            'order_id'   => $order->id,
            'product_id' => $product->id,
            'harga'      => (int) $product->price,
            'jumlah'     => $qty,
            'subtotal'   => $totalHarga,
        ]);

        $stokSebelumDirect = $product->stock;
        $product->decrement('stock', $qty);
        $stokSesudahDirect = $product->stock;

        StockHistory::create([
            'product_id'   => $product->id,
            'nama_produk'  => $product->name,
            'status'       => 'keluar',
            'jumlah'       => $qty,
            'stok_sebelum' => $stokSebelumDirect,
            'stok_sesudah' => $stokSesudahDirect,
            'keterangan'   => 'Dibeli oleh ' . $user->name . ' sebanyak ' . $qty . ' unit via Beli Langsung (Order #' . $order->id . ')',
        ]);

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

        $params = [
            'transaction_details' => [
                'order_id'     => 'ORDER-' . $order->id . '-' . time(),
                'gross_amount' => $totalHarga,
            ],
            'customer_details' => [
                'first_name' => $user->name,
                'email'      => $user->email,
                'phone'      => $user->phone ?? '',
            ],
            'item_details' => [[
                'id'       => $product->id,
                'price'    => (int) $product->price,
                'quantity' => $qty,
                'name'     => substr($product->name, 0, 50),
            ]],
        ];

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

        \App\Models\Payment::create([
            'order_id'      => $order->id,
            'metode'        => 'midtrans',
            'snap_token'    => $snapToken,
            'status'        => 'menunggu',
            'tanggal_bayar' => now(),
        ]);

        return [
            'snap_token'   => $snapToken,
            'order_id'     => $order->id,
            'redirect_url' => route('order.success', $order->id),
        ];
    });

    return response()->json($result);
}

    public function updateStatus(Request $request, $orderId)
    {
        $order = \App\Models\Order::where('id', $orderId)
                    ->where('user_id', auth()->id())
                    ->firstOrFail();

        $order->update(['status' => 'diproses']);

        if ($order->payment) {
            $order->payment->update(['status' => 'lunas']);
        }

        return response()->json(['success' => true]);
    }

    public function storeAddress(Request $request)
    {
        $request->validate([
            'nama_penerima'  => 'required',
            'nomor_telepon'  => 'required',
            'province_id'    => 'required',
            'regency_id'     => 'required',
            'district_id'    => 'required',
            'village_id'     => 'required',
            'alamat_lengkap' => 'required',
        ]);

        $prov = DB::table('provinces')->where('id', $request->province_id)->first();
        $kab  = DB::table('regencies')->where('id', $request->regency_id)->first();
        $kec  = DB::table('districts')->where('id', $request->district_id)->first();
        $desa = DB::table('villages')->where('id', $request->village_id)->first();

        $alamatLengkap = $request->alamat_lengkap
            . ', Desa '   . ($desa->name ?? '')
            . ', Kec. '   . ($kec->name  ?? '')
            . ', '        . ($kab->name  ?? '')
            . ', '        . ($prov->name ?? '');

        $address = Address::create([
            'user_id'        => auth()->id(),
            'nama_penerima'  => $request->nama_penerima,
            'no_hp'          => $request->nomor_telepon,
            'province_id'    => $request->province_id,
            'regency_id'     => $request->regency_id,
            'district_id'    => $request->district_id,
            'village_id'     => $request->village_id,
            'alamat_lengkap' => $alamatLengkap,
        ]);

        return response()->json([
            'success'    => true,
            'message'    => 'Alamat berhasil disimpan!',
            'address_id' => $address->id,
        ]);
    }

    public function deleteAddress($id)
    {
        $address = Address::where('id', $id)
                        ->where('user_id', auth()->id())
                        ->firstOrFail();
        $address->delete();

        return redirect()->back()->with('success', 'Alamat berhasil dihapus');
    }

    public function success($orderId)
    {
        $order = \App\Models\Order::with(['items.product', 'address', 'payment'])
                    ->where('id', $orderId)
                    ->where('user_id', auth()->id())
                    ->firstOrFail();

        return view('orders.success', compact('order'));
    }
    
    // ===== ADMIN =====
public function adminIndex()
{
    $orders = \App\Models\Order::with(['user', 'items.product', 'payment', 'address'])
                ->latest()
                ->get();

    return view('admin.orders.index', compact('orders'));
}

public function adminUpdateStatus(Request $request, $id)
{
    $order = \App\Models\Order::findOrFail($id);
    $order->update(['status' => $request->status]);

    return redirect()->back()->with('success', 'Status pesanan berhasil diupdate!');
}

// ===== USER (UNIFIED HISTORY) =====
public function myOrders()
{
    $userId = auth()->id();

    // 1. Ambil Pesanan Produk (E-commerce)
    $orders = Order::with(['items.product.category', 'payment', 'reviews'])
                ->where('user_id', $userId)
                ->latest()
                ->get();

    // 2. Ambil Riwayat Jasa Service
    $jasas = Jasa::with('address')
                ->where('user_id', $userId)
                ->latest()
                ->get();

    return view('orders.history', compact('orders', 'jasas'));
}

    public function myOrderDetail($id)
    {
        $order = \App\Models\Order::with(['items.product', 'address', 'payment'])
                    ->where('id', $id)
                    ->where('user_id', auth()->id())
                    ->firstOrFail();

        return view('orders.detail', compact('order'));
    }

    public function cancel(Request $request, $id)
    {
        $order = \App\Models\Order::where('id', $id)
                    ->where('user_id', auth()->id())
                    ->firstOrFail();

        // Hanya bisa batal jika status masih 'menunggu' atau 'diproses'
        if (!in_array($order->status, ['menunggu', 'diproses'])) {
            return redirect()->back()->with('error', 'Pesanan yang sudah diproses tidak dapat dibatalkan.');
        }

        $request->validate([
            'cancel_reason' => 'required'
        ]);

        $order->update([
            'status' => 'dibatalkan',
            'cancel_reason' => $request->cancel_reason
        ]);

        // Opsional: Balikin stok produk
        foreach ($order->items as $item) {
            $item->product->increment('stock', $item->jumlah);
        }

        return redirect()->back()->with('success', 'Pesanan berhasil dibatalkan.');
    }
}