<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Banner;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Validator;

class BannerController extends Controller
{
    public function index()
    {
        $banners = Banner::with(['category:id,name', 'product:id,name'])
            ->orderBy('display_order')
            ->paginate(20);

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

    public function show($id)
    {
        $banner = Banner::with(['category', 'product'])
            ->findOrFail($id);

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

    public function store(Request $request)
    { 

$validator = Validator::make($request->all(), [
    'title' => 'required|max:255',
    'image' => 'required|image',
    'category_id' => 'nullable|exists:categories,id',
    'product_id' => 'nullable|exists:products,id',
    'status' => 'required|boolean',
    'display_order' => 'nullable|integer'
]);

if ($validator->fails()) {
    return response()->json([
        'success' => false,
        'message' => 'Validation failed',
        'errors' => $validator->errors()
    ], 422);
}
 
        $imageName = null;

        if ($request->hasFile('image')) {

            $image = $request->file('image');

            $imageName = time().'_'.Str::random(10).'.'.$image->getClientOriginalExtension();

            $image->move(
                public_path('uploads/banners'),
                $imageName
            );
        }

        $banner = Banner::create([
            'title' => $request->title,
            'category_id' => $request->category_id,
            'product_id' => $request->product_id,
            'image' => $imageName,
            'status' => $request->status,
            'display_order' => $request->display_order ?? 0,
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Banner created successfully',
            'data' => $banner
        ]);
    }

    public function update(Request $request, $id)
    {
        $banner = Banner::findOrFail($id);

        $request->validate([
            'title' => 'required|max:255',
            'category_id' => 'nullable|exists:categories,id',
            'product_id' => 'nullable|exists:products,id',
            'status' => 'required|boolean',
            'display_order' => 'nullable|integer'
        ]);

        if ($request->hasFile('image')) {

            if (
                $banner->image &&
                File::exists(
                    public_path('uploads/banners/'.$banner->image)
                )
            ) {
                File::delete(
                    public_path('uploads/banners/'.$banner->image)
                );
            }

            $image = $request->file('image');

            $imageName = time().'_'.Str::random(10).'.'.$image->getClientOriginalExtension();

            $image->move(
                public_path('uploads/banners'),
                $imageName
            );

            $banner->image = $imageName;
        }

        $banner->update([
            'title' => $request->title,
            'category_id' => $request->category_id,
            'product_id' => $request->product_id,
            'status' => $request->status,
            'display_order' => $request->display_order ?? 0,
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Banner updated successfully',
            'data' => $banner->fresh()
        ]);
    }

    public function destroy($id)
    {
        $banner = Banner::findOrFail($id);

        if (
            $banner->image &&
            File::exists(
                public_path('uploads/banners/'.$banner->image)
            )
        ) {
            File::delete(
                public_path('uploads/banners/'.$banner->image)
            );
        }

        $banner->delete();

        return response()->json([
            'success' => true,
            'message' => 'Banner deleted successfully'
        ]);
    }


    //  ===============================  APP BANNER =============================



public function appBanners()
{
    $banners = Banner::where('status', 1)
        ->orderBy('display_order')
        ->get()
        ->map(function ($banner) {

            return [
                'id' => $banner->id,
                'title' => $banner->title,
                'image' => asset('storage/' . $banner->image),
                'category_id' => $banner->category_id,
                'product_id' => $banner->product_id,
            ];
        });

    return response()->json([
        'success' => true,
        'message' => 'Banner list fetched successfully',
        'data' => $banners
    ]);
}
}