<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use App\Models\Category;
use App\Models\Products;
use App\Models\GiftOffers;
use Yajra\DataTables\Facades\DataTables;

class GiftOffersController extends Controller
{
    // Add Offer
    public function addOffer(Request $request)
    {
        $request->validate([
            'title'       => 'required|string|max:255',
            'category_id' => 'required|exists:categories,id',
            'product_id'  => 'nullable|exists:products,id',
            'discount_percentage' => 'nullable|numeric|min:0|max:100',
            'discount_amount'     => 'nullable|numeric|min:0',
            'start_date'  => 'nullable|date',
            'end_date'    => 'nullable|date|after_or_equal:start_date',
        ]);

        GiftOffers::create([
            'title'       => ucfirst($request->title),
            'category_id' => $request->category_id,
            'product_id'  => $request->product_id ?? null,
            'discount_percentage' => $request->discount_percentage,
            'discount_amount'     => $request->discount_amount,
            'start_date'  => $request->start_date,
            'end_date'    => $request->end_date,
            'is_active'   => 1,
        ]);

        return response()->json(['success' => 'Gift offer added successfully!']);
    }

    // List Offers (DataTables)
    public function getOffers()
    {
        $offers = GiftOffers::with(['category', 'product'])->orderBy('id', 'DESC')->get();

        return DataTables::of($offers)
            ->addIndexColumn()
            ->addColumn('title', fn($o) => $o->title)
            ->addColumn('category', fn($o) => $o->category?->name ?? '-')
            ->addColumn('product', fn($o) => $o->product?->name ?? '-')
            ->addColumn('discount', fn($o) => $o->discount_percentage ? $o->discount_percentage.'%' : '₹'.$o->discount_amount)
            ->addColumn('date_range', fn($o) => ($o->start_date ?? '-') . ' to ' . ($o->end_date ?? '-'))
            ->addColumn('status', function ($o) {
                $btnClass = $o->is_active ? 'btn-success' : 'btn-danger';
                $btnText = $o->is_active ? 'Active' : 'Inactive';
                return '<button class="btn btn-sm toggleStatusBtn '.$btnClass.'" data-id="'.$o->id.'">'.$btnText.'</button>';
            })
            ->addColumn('action', function ($row) {
                return '
                    <a href="#" class="btn btn-sm btn-purple editOfferBtn" data-id="'.$row->id.'">Edit</a>
                    <a href="#" class="btn btn-sm btn-danger deleteoffer" data-id="'.$row->id.'">Delete</a>
                ';
            })
            ->escapeColumns([])
            ->make(true);
    }

    // Delete Offer
    public function destroy($id)
    {
        $offer = GiftOffers::findOrFail($id);
        $offer->delete();
        return response()->json(['success' => 'Gift offer deleted successfully.']);
    }

    // Update Offer
    // public function update(Request $request, $id)
    // {
    //     $offer = GiftOffers::findOrFail($id);

    //     $request->validate([
    //         'title'       => 'required|string|max:255',
    //         'category_id' => 'required|exists:categories,id',
    //         'product_id'  => 'nullable|exists:products,id',
    //         'discount_percentage' => 'nullable|numeric|min:0|max:100',
    //         'discount_amount'     => 'nullable|numeric|min:0',
    //         'start_date'  => 'nullable|date',
    //         'end_date'    => 'nullable|date|after_or_equal:start_date',
    //     ]);

    //     $offer->update([
    //         'title'       => ucfirst($request->title),
    //         'category_id' => $request->category_id,
    //         'product_id'  => $request->product_id ?? null,
    //         'discount_percentage' => $request->discount_percentage,
    //         'discount_amount'     => $request->discount_amount,
    //         'start_date'  => $request->start_date,
    //         'end_date'    => $request->end_date,
    //     ]);

    //     return response()->json(['success' => 'Gift offer updated successfully!']);
    // }

    // Toggle Status
    public function changeStatus($id)
    {
        $offer = GiftOffers::findOrFail($id);
        $offer->is_active = !$offer->is_active;
        $offer->save();

        return response()->json([
            'success' => true,
            'status'  => $offer->is_active,
            'message' => 'Gift offer status updated successfully!',
        ]);
    }

      // Fetch offer data for edit modal
    public function edit($id)
    {
        $offer = GiftOffers::findOrFail($id);
        $categories = Category::all();
        $products = Products::all();

        return response()->json([
            'offer' => $offer,
            'categories' => $categories,
            'products' => $products,
        ]);
    }

   // Update offer via AJAX
    public function update(Request $request, $id)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'category_id' => 'required|exists:categories,id',
            'product_id' => 'nullable|exists:products,id',
            'discount_percentage' => 'nullable|numeric|min:0',
            'discount_amount' => 'nullable|numeric|min:0',
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date|after_or_equal:start_date',
            'is_active' => 'boolean',
        ]);

        $offer = GiftOffers::findOrFail($id);
        $offer->update($request->all());

        return response()->json(['success' => true, 'message' => 'Offer updated successfully!']);
    }
}
