<?php

namespace App\Http\Controllers\Admin;

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

class FlashSaleController extends Controller
{
    public function index()
    {
        $flashSales = FlashSale::orderBy('order')->paginate(20);
        return view('admin.flash-sales.index', compact('flashSales'));
    }

    public function create()
    {
        return view('admin.flash-sales.create');
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'title'              => 'required|string|max:255',
            'description'        => 'nullable|string',
            'discount_percentage'=> 'nullable|integer|min:0|max:100',
            'badge_text'         => 'nullable|string|max:50',
            'btn_text'           => 'nullable|string|max:100',
            'btn_link'           => 'nullable|string|max:255',
            'start_date'         => 'nullable|date',
            'end_date'           => 'nullable|date|after_or_equal:start_date',
            'order'              => 'nullable|integer|min:0',
            'is_active'          => 'nullable|boolean',
        ]);

        $data['is_active'] = $request->boolean('is_active', true);

        FlashSale::create($data);
        return redirect()->route('admin.flash-sales.index')->with('success', 'Flash sale created successfully.');
    }

    public function edit(FlashSale $flashSale)
    {
        return view('admin.flash-sales.edit', compact('flashSale'));
    }

    public function update(Request $request, FlashSale $flashSale)
    {
        $data = $request->validate([
            'title'              => 'required|string|max:255',
            'description'        => 'nullable|string',
            'discount_percentage'=> 'nullable|integer|min:0|max:100',
            'badge_text'         => 'nullable|string|max:50',
            'btn_text'           => 'nullable|string|max:100',
            'btn_link'           => 'nullable|string|max:255',
            'start_date'         => 'nullable|date',
            'end_date'           => 'nullable|date|after_or_equal:start_date',
            'order'              => 'nullable|integer|min:0',
            'is_active'          => 'nullable|boolean',
        ]);

        $data['is_active'] = $request->boolean('is_active', true);

        $flashSale->update($data);
        return redirect()->route('admin.flash-sales.index')->with('success', 'Flash sale updated successfully.');
    }

    public function destroy(FlashSale $flashSale)
    {
        $flashSale->delete();
        return redirect()->route('admin.flash-sales.index')->with('success', 'Flash sale deleted successfully.');
    }
}
