<?php

namespace App\Http\Controllers\API\Dashboard;

use App\Models\Banner;
use App\Models\Slider;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;


class SliderCardController extends Controller
{
    // Get all sliders without pagination
    public function getSliders(Request $request)
    {
        try {
            $sliders = Slider::where('home', 1)->select('id', 'name', 'image', 'link', 'created_at')
                ->get();

            return response()->json([
                'success' => true,
                'data' => $sliders
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error fetching sliders: ' . $e->getMessage()
            ], 500);
        }
    }

    // Create a new slider
    public function createSlider(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'nullable|string|max:255',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
            'link' => 'nullable',
            'home' => 'nullable',
            'is_active' => 'nullable|boolean'
        ]);

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

        try {
            $adminId = auth('admin')->id();
            if (!\App\Models\Admin::find($adminId)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Authenticated admin does not exist'
                ], 403);
            }

            $imagePath = null;
            if ($request->hasFile('image')) {
                $imagePath = $request->file('image')->store('sliders', 'public');
            }

            $slider = Slider::create([
                'name' => $request->name,
                'image' => $imagePath,
                'link' => $request->link,
                'home' => $request->home,
                'is_active' => $request->input('is_active', true)
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Slider created successfully',
                'data' => [
                    'id' => $slider->id,
                    'name' => $slider->name,
                    'image' => $imagePath ? Storage::url($imagePath) : null,
                    'link' => $slider->link,
                    'home' => $slider->home,
                    'created_at' => $slider->created_at
                ]
            ], 201);
        } catch (\Exception $e) {
            // Clean up uploaded image if creation fails
            if ($imagePath && Storage::disk('public')->exists($imagePath)) {
                Storage::disk('public')->delete($imagePath);
            }
            return response()->json([
                'success' => false,
                'message' => 'Error creating slider: ' . $e->getMessage()
            ], 500);
        }
    }

    // Delete a slider
    public function deleteSlider($id)
    {
        $validator = Validator::make(['id' => $id], [
            'id' => 'required|exists:sliders,id'
        ]);

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

        try {
            $adminId = auth('admin')->id();
            if (!\App\Models\Admin::find($adminId)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Authenticated admin does not exist'
                ], 403);
            }

            $slider = Slider::findOrFail($id);
            if ($slider->image && Storage::disk('public')->exists($slider->image)) {
                Storage::disk('public')->delete($slider->image);
            }
            $slider->delete();

            return response()->json([
                'success' => true,
                'message' => 'Slider deleted successfully'
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error deleting slider: ' . $e->getMessage()
            ], 500);
        }
    }

    // Get all banners without pagination
    public function getBanners(Request $request)
    {
        try {
            $banners = Banner::select('id', 'image', 'product_id', 'created_at')
                ->orderBy('created_at', 'desc')
                ->get();

            return response()->json([
                'success' => true,
                'data' => $banners
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error fetching banners: ' . $e->getMessage()
            ], 500);
        }
    }

    // Create a new banner
    public function createBanner(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
            'product_id' => 'nullable|exists:products,id'
        ]);

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

        try {
            $adminId = auth('admin')->id();
            if (!\App\Models\Admin::find($adminId)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Authenticated admin does not exist'
                ], 403);
            }

            $imagePath = null;
            if ($request->hasFile('image')) {
                $imagePath = $request->file('image')->store('banners', 'public');
            }

            $banner = Banner::create([
                'image' => $imagePath,
                'product_id' => $request->product_id
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Banner created successfully',
                'data' => [
                    'id' => $banner->id,
                    'image' => $imagePath ? Storage::url($imagePath) : null,
                    'product_id' => $banner->product_id,
                    'created_at' => $banner->created_at
                ]
            ], 201);
        } catch (\Exception $e) {
            // Clean up uploaded image if creation fails
            if ($imagePath && Storage::disk('public')->exists($imagePath)) {
                Storage::disk('public')->delete($imagePath);
            }
            return response()->json([
                'success' => false,
                'message' => 'Error creating banner: ' . $e->getMessage()
            ], 500);
        }
    }

    // Delete a banner
    public function deleteBanner($id)
    {
        $validator = Validator::make(['id' => $id], [
            'id' => 'required|exists:banners,id'
        ]);

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

        try {
            $adminId = auth('admin')->id();
            if (!\App\Models\Admin::find($adminId)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Authenticated admin does not exist'
                ], 403);
            }

            $banner = Banner::findOrFail($id);
            if ($banner->image && Storage::disk('public')->exists($banner->image)) {
                Storage::disk('public')->delete($banner->image);
            }
            $banner->delete();

            return response()->json([
                'success' => true,
                'message' => 'Banner deleted successfully'
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error deleting banner: ' . $e->getMessage()
            ], 500);
        }
    }
}