<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\ProductCategory;
use App\Models\Banner;
use App\Models\Cart;
use App\Models\Order;
use App\Models\OrderItem;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ProductApiController extends Controller
{
    /**
     * Get all products
     */
    public function index(Request $request)
    {
        $query = Product::with('category')->where('is_active', true);

        if ($request->has('kategori_id')) {
            $query->where('kategori_id', $request->kategori_id);
        }

        $products = $query->paginate(20);

        return response()->json([
            'success' => true,
            'data' => $products
        ]);
    }

    /**
     * Get product detail
     */
    public function show($id)
    {
        $product = Product::with('category')->findOrFail($id);

        return response()->json([
            'success' => true,
            'data' => $product
        ]);
    }

    /**
     * Get product categories
     */
    public function categories()
    {
        $categories = ProductCategory::orderBy('urutan')->get();

        return response()->json([
            'success' => true,
            'data' => $categories
        ]);
    }

    /**
     * Search products
     */
    public function search(Request $request)
    {
        $keyword = $request->q;

        $products = Product::with('category')
            ->where('is_active', true)
            ->where(function ($query) use ($keyword) {
                $query->where('nama', 'like', "%{$keyword}%")
                    ->orWhere('deskripsi', 'like', "%{$keyword}%")
                    ->orWhere('kode_produk', 'like', "%{$keyword}%");
            })
            ->paginate(20);

        return response()->json([
            'success' => true,
            'data' => $products
        ]);
    }

    /**
     * Get banners
     */
    public function banners()
    {
        $banners = Banner::where('is_active', true)
            ->orderBy('urutan')
            ->get();

        return response()->json([
            'success' => true,
            'data' => $banners
        ]);
    }

    /**
     * Get cart
     */
    public function getCart(Request $request)
    {
        $cart = Cart::where('user_id', $request->user()->id)
            ->with('product')
            ->get();

        $total = $cart->sum(function ($item) {
            return $item->quantity * $item->product->harga;
        });

        return response()->json([
            'success' => true,
            'data' => [
                'items' => $cart,
                'total' => $total
            ]
        ]);
    }

    /**
     * Add to cart
     */
    public function addToCart(Request $request)
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
            'quantity' => 'required|integer|min:1',
            'catatan' => 'nullable|string'
        ]);

        $product = Product::findOrFail($request->product_id);

        if ($product->stok < $request->quantity) {
            return response()->json([
                'success' => false,
                'message' => 'Stok tidak mencukupi'
            ], 422);
        }

        $cart = Cart::updateOrCreate(
            [
                'user_id' => $request->user()->id,
                'product_id' => $request->product_id
            ],
            [
                'quantity' => DB::raw("quantity + {$request->quantity}"),
                'catatan' => $request->catatan
            ]
        );

        return response()->json([
            'success' => true,
            'message' => 'Produk berhasil ditambahkan ke keranjang',
            'data' => $cart->load('product')
        ]);
    }

    /**
     * Update cart
     */
    public function updateCart($id, Request $request)
    {
        $request->validate([
            'quantity' => 'required|integer|min:1'
        ]);

        $cart = Cart::where('id', $id)
            ->where('user_id', $request->user()->id)
            ->firstOrFail();

        if ($cart->product->stok < $request->quantity) {
            return response()->json([
                'success' => false,
                'message' => 'Stok tidak mencukupi'
            ], 422);
        }

        $cart->update(['quantity' => $request->quantity]);

        return response()->json([
            'success' => true,
            'message' => 'Keranjang berhasil diupdate',
            'data' => $cart->load('product')
        ]);
    }

    /**
     * Remove from cart
     */
    public function removeFromCart($id, Request $request)
    {
        $cart = Cart::where('id', $id)
            ->where('user_id', $request->user()->id)
            ->firstOrFail();

        $cart->delete();

        return response()->json([
            'success' => true,
            'message' => 'Produk berhasil dihapus dari keranjang'
        ]);
    }

    /**
     * Checkout
     */
    public function checkout(Request $request)
    {
        $request->validate([
            'metode_pembayaran' => 'required|in:tunai,transfer,potong_simpanan',
            'alamat_pengiriman' => 'required|string',
            'catatan' => 'nullable|string'
        ]);

        $cart = Cart::where('user_id', $request->user()->id)
            ->with('product')
            ->get();

        if ($cart->isEmpty()) {
            return response()->json([
                'success' => false,
                'message' => 'Keranjang kosong'
            ], 422);
        }

        DB::beginTransaction();
        try {
            // Generate order number
            $noOrder = 'ORD-' . date('Ymd') . '-' . strtoupper(uniqid());

            // Calculate total
            $totalHarga = $cart->sum(function ($item) {
                return $item->quantity * $item->product->harga;
            });

            // Create order
            $order = Order::create([
                'no_order' => $noOrder,
                'user_id' => $request->user()->id,
                'total_harga' => $totalHarga,
                'metode_pembayaran' => $request->metode_pembayaran,
                'status' => 'pending',
                'alamat_pengiriman' => $request->alamat_pengiriman,
                'catatan' => $request->catatan
            ]);

            // Create order items and update stock
            foreach ($cart as $item) {
                OrderItem::create([
                    'order_id' => $order->id,
                    'product_id' => $item->product_id,
                    'quantity' => $item->quantity,
                    'harga_satuan' => $item->product->harga,
                    'subtotal' => $item->quantity * $item->product->harga
                ]);

                // Update stock
                $item->product->decrement('stok', $item->quantity);
            }

            // Clear cart
            Cart::where('user_id', $request->user()->id)->delete();

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'Checkout berhasil',
                'data' => $order->load('orderItems.product')
            ], 201);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => 'Checkout gagal: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get orders
     */
    public function getOrders(Request $request)
    {
        $orders = Order::where('user_id', $request->user()->id)
            ->orderBy('created_at', 'desc')
            ->paginate(15);

        return response()->json([
            'success' => true,
            'data' => $orders
        ]);
    }

    /**
     * Get order detail
     */
    public function getOrderDetail($id, Request $request)
    {
        $order = Order::where('id', $id)
            ->where('user_id', $request->user()->id)
            ->with('orderItems.product')
            ->firstOrFail();

        return response()->json([
            'success' => true,
            'data' => $order
        ]);
    }
}
