<?php

namespace App\Http\Controllers;

use App\Models\FlashSale;
use App\Models\Game;
use App\Models\Order;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ProductController extends Controller
{
    /**
     * Display products for a specific game
     */
    public function index(Game $game)
    {
        // Check if game is active
        if (!$game->is_active) {
            abort(404);
        }

        // Load relationships
        $game->load(['category', 'activeProducts']);

        // Get active flash sales for this game's products
        $flashSales = FlashSale::with('product')
            ->whereHas('product', function ($query) use ($game) {
                $query->where('game_id', $game->id);
            })
            ->currentlyRunning()
            ->get()
            ->keyBy('product_id');

        return view('products.index', compact('game', 'flashSales'));
    }

    /**
     * Process order/checkout
     */
    public function checkout(Request $request, Game $game)
    {
        // Check if game is active
        if (!$game->is_active) {
            abort(404);
        }

        // Validate request
        $validated = $request->validate([
            'product_id' => 'required|exists:products,id',
            'user_id' => 'required|string|max:100',
            'zone_id' => 'nullable|string|max:50',
            'whatsapp' => 'required|string|max:20',
            'flash_sale_id' => 'nullable|exists:flash_sales,id',
        ], [
            'product_id.required' => 'Pilih produk terlebih dahulu',
            'user_id.required' => 'ID Game wajib diisi',
            'whatsapp.required' => 'Nomor WhatsApp wajib diisi',
        ]);

        // Get product
        $product = Product::findOrFail($validated['product_id']);

        // Verify product belongs to this game
        if ($product->game_id !== $game->id) {
            return back()->with('error', 'Produk tidak valid untuk game ini');
        }

        // Check product stock
        if ($product->stock <= 0) {
            return back()->with('error', 'Stok produk habis');
        }

        // Initialize price variables
        $originalPrice = $product->price;
        $finalPrice = $product->price;
        $discount = 0;
        $flashSaleId = null;

        // Check if flash sale is selected and valid
        if (!empty($validated['flash_sale_id'])) {
            $flashSale = FlashSale::find($validated['flash_sale_id']);

            if ($flashSale &&
                    $flashSale->product_id === $product->id &&
                    $flashSale->isCurrentlyActive()) {
                // Use flash sale price
                $finalPrice = $flashSale->flash_price;
                $discount = $originalPrice - $finalPrice;
                $flashSaleId = $flashSale->id;
            }
        }

        // Create order within transaction
        try {
            $order = DB::transaction(function () use ($product, $validated, $originalPrice, $finalPrice, $discount, $flashSaleId) {
                // Create order
                $order = Order::create([
                    'product_id' => $product->id,
                    'flash_sale_id' => $flashSaleId,
                    'game_user_id' => $validated['user_id'],
                    'game_server_id' => $validated['zone_id'] ?? null,
                    'whatsapp' => $validated['whatsapp'],
                    'original_price' => $originalPrice,
                    'final_price' => $finalPrice,
                    'discount_amount' => $discount,
                    'status' => 'pending',
                ]);

                // Update flash sale sold count if applicable
                if ($flashSaleId) {
                    FlashSale::where('id', $flashSaleId)->increment('sold');
                }

                return $order;
            });

            // Redirect to checkout/payment page
            return redirect()->route('order.checkout', $order->order_id);
        } catch (\Exception $e) {
            return back()->with('error', 'Terjadi kesalahan saat membuat pesanan. Silakan coba lagi.');
        }
    }
}
