<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\FlashSale;
use App\Models\Product;
use Carbon\Carbon;
use Illuminate\Http\Request;

class FlashSaleController extends Controller
{
    public function index()
    {
        $flashSales = FlashSale::with('product.game')
            ->orderBy('start_time', 'desc')
            ->get();

        return view('admin.flash-sales.index', compact('flashSales'));
    }

    public function create()
    {
        $products = Product::with('game')
            ->where('is_active', true)
            ->orderBy('game_id')
            ->orderBy('name')
            ->get();

        return view('admin.flash-sales.create', compact('products'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
            'flash_price' => 'required|numeric|min:0',
            'flash_stock' => 'required|integer|min:1',
            'start_time' => 'required|date',
            'end_time' => 'required|date|after:start_time',
        ], [
            'product_id.required' => 'Pilih produk untuk flash sale',
            'flash_price.required' => 'Harga flash sale wajib diisi',
            'flash_price.min' => 'Harga flash sale tidak boleh negatif',
            'flash_stock.required' => 'Stok flash sale wajib diisi',
            'flash_stock.min' => 'Stok minimal 1',
            'start_time.required' => 'Waktu mulai wajib diisi',
            'end_time.required' => 'Waktu berakhir wajib diisi',
            'end_time.after' => 'Waktu berakhir harus setelah waktu mulai',
        ]);

        // Check if product already has active flash sale in overlapping time
        $existingFlashSale = FlashSale::where('product_id', $request->product_id)
            ->where('is_active', true)
            ->where(function ($query) use ($request) {
                $query
                    ->whereBetween('start_time', [$request->start_time, $request->end_time])
                    ->orWhereBetween('end_time', [$request->start_time, $request->end_time])
                    ->orWhere(function ($q) use ($request) {
                        $q
                            ->where('start_time', '<=', $request->start_time)
                            ->where('end_time', '>=', $request->end_time);
                    });
            })
            ->exists();

        if ($existingFlashSale) {
            return back()
                ->withInput()
                ->with('error', 'Produk ini sudah memiliki flash sale aktif di waktu yang sama');
        }

        FlashSale::create([
            'product_id' => $request->product_id,
            'flash_price' => $request->flash_price,
            'flash_stock' => $request->flash_stock,
            'sold' => 0,
            'start_time' => $request->start_time,
            'end_time' => $request->end_time,
            'is_active' => $request->has('is_active'),
        ]);

        return redirect()
            ->route('admin.flash-sales.index')
            ->with('success', 'Flash Sale berhasil dibuat');
    }

    public function edit(FlashSale $flashSale)
    {
        $products = Product::with('game')
            ->where('is_active', true)
            ->orderBy('game_id')
            ->orderBy('name')
            ->get();

        return view('admin.flash-sales.edit', compact('flashSale', 'products'));
    }

    public function update(Request $request, FlashSale $flashSale)
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
            'flash_price' => 'required|numeric|min:0',
            'flash_stock' => 'required|integer|min:1',
            'start_time' => 'required|date',
            'end_time' => 'required|date|after:start_time',
        ], [
            'product_id.required' => 'Pilih produk untuk flash sale',
            'flash_price.required' => 'Harga flash sale wajib diisi',
            'flash_price.min' => 'Harga flash sale tidak boleh negatif',
            'flash_stock.required' => 'Stok flash sale wajib diisi',
            'flash_stock.min' => 'Stok minimal 1',
            'start_time.required' => 'Waktu mulai wajib diisi',
            'end_time.required' => 'Waktu berakhir wajib diisi',
            'end_time.after' => 'Waktu berakhir harus setelah waktu mulai',
        ]);

        // Check if product already has active flash sale in overlapping time (excluding current)
        $existingFlashSale = FlashSale::where('product_id', $request->product_id)
            ->where('id', '!=', $flashSale->id)
            ->where('is_active', true)
            ->where(function ($query) use ($request) {
                $query
                    ->whereBetween('start_time', [$request->start_time, $request->end_time])
                    ->orWhereBetween('end_time', [$request->start_time, $request->end_time])
                    ->orWhere(function ($q) use ($request) {
                        $q
                            ->where('start_time', '<=', $request->start_time)
                            ->where('end_time', '>=', $request->end_time);
                    });
            })
            ->exists();

        if ($existingFlashSale) {
            return back()
                ->withInput()
                ->with('error', 'Produk ini sudah memiliki flash sale aktif di waktu yang sama');
        }

        $flashSale->update([
            'product_id' => $request->product_id,
            'flash_price' => $request->flash_price,
            'flash_stock' => $request->flash_stock,
            'start_time' => $request->start_time,
            'end_time' => $request->end_time,
            'is_active' => $request->has('is_active'),
        ]);

        return redirect()
            ->route('admin.flash-sales.index')
            ->with('success', 'Flash Sale berhasil diupdate');
    }

    public function destroy(FlashSale $flashSale)
    {
        $flashSale->delete();

        return redirect()
            ->route('admin.flash-sales.index')
            ->with('success', 'Flash Sale berhasil dihapus');
    }
}
