<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Cities;
use App\Models\Company;
use App\Models\Country;
use App\Models\Emirates;
use App\Models\EventType;
use App\Models\Whychooseus;
use App\Models\SliderButton;
use App\Models\User;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use Yajra\DataTables\Facades\DataTables;
use Illuminate\Http\JsonResponse;
class WhyChooseusController extends Controller
{
    public function index()
    {
        $sliders = Whychooseus::orderBy('created_at', 'desc')->get();
        
        return view('admin.chooseus.index', compact('sliders'));

    }
    public function create(){
        $today = date("Y-m-d");
        $slider = "";
        $title       = "";
        return view('admin.chooseus.create', compact('today', 'slider'));

    }

    public function store(Request $request)
    {
        $rules = [
            'name' => 'required|string|max:255',
            'status' => 'required|in:0,1',
            'content' => 'required|string|min:10',
            'image' => $request->id ? 'nullable|image|mimes:jpg,jpeg,png,gif|max:2048' : 'required|image|mimes:jpg,jpeg,png,gif|max:2048',
            
        ];

        $validator = Validator::make($request->all(), $rules);

        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'errors' => $validator->errors(),
            ], 422);
        }

        if ($request->id) {
            $slider = Whychooseus::find($request->id);

            if (!$slider) {
                return response()->json(['status' => 'error', 'message' => 'Slider not found'], 404);
            }

            // Check for duplicate slider name
            $existingSlider = Whychooseus::where('name', $request->name)
                ->where('id', '!=', $request->id)
                ->first();

            if ($existingSlider) {
                return response()->json([
                    'status' => 'error',
                    'errors' => [
                        'name' => ['The slider name already exists.']
                    ]
                ], 422);
            }

            $slider->name = $request->name;
            $slider->status = $request->status;
            $slider->content = $request->content;

            // Handle image upload
           
            $disk = Config::get('global.disk');
            if ($request->hasFile('image')) {

                $imagePath = Config::get('global.slider_directory');

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

                // Generate a unique file name
                $fileName = time() . uniqid() . ".".$file->getClientOriginalExtension();

                // Save the file to the specified disk and path
                $file->storeAs($imagePath, $fileName, $disk);

                // Save the file name to the database
                $slider->image = $fileName;
                

            }

            $slider->save();

          

            return response()->json(['status' => 'success', 'message' => 'Why Choose Us updated successfully']);
        } else {
            // Check for duplicate slider name
            $existingSlider = Whychooseus::where('name', $request->name)->first();

            if ($existingSlider) {
                return response()->json([
                    'status' => 'error',
                    'errors' => [
                        'name' => ['The Why Choose Us name already exists.']
                    ]
                ], 422);
            }

            // Create slider
        
            $disk = Config::get('global.disk');
            if ($request->hasFile('image')) {

                $imagePath = Config::get('global.slider_directory');

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

                // Generate a unique file name
                $fileName = time() . uniqid() . ".".$file->getClientOriginalExtension();

                // Save the file to the specified disk and path
                $file->storeAs($imagePath, $fileName, $disk);

                // Save the file name to the database
                
                

            }
            $slider = Whychooseus::create([
                'name' => $request->name,
                'status' => $request->status,
                'content' => $request->content,
                'image' => $fileName,
            ]);

            

            return response()->json([
                'status' => 'success',
                'message' => 'Why Choose Us added successfully',
                'slider' => $slider,
            ]);
        }
    }

    


  
    public function edit($id) {
        $slider = Whychooseus::findOrFail($id);
        return view('admin.chooseus.create', compact('slider'));
    }

    public function destroy($id): JsonResponse
    {
        try {
            $slider = Whychooseus::findOrFail($id);
            
            $slider->delete();
            return response()->json([
                'status' => 'success',
                'message' => 'Why Choose Us deleted successfully.'
            ], 200);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Why Choose Us not found.'
            ], 404);
        } catch (Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'An error occurred while deleting the Slider.'
            ], 500);
        }
    }

    public function statusChange(Request $request, $id) {
        $slider = Whychooseus::find($id);

        if (!$slider) {
            return response()->json([
                'status' => 'error',
                'message' => 'Why Choose Us not found.'
            ], 404);
        }
    
        $slider->status = $request->status;
        $slider->save();
    
        return response()->json([
            'status' => 'success',
            'message' => 'Why Choose Us status updated successfully.'
        ]);
    }
}
