<?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\WorkProcess;
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 WorkProcessController extends Controller
{
    public function index()
    {
        $sliders = WorkProcess::orderBy('created_at', 'desc')->get();
        
        return view('admin.workprocess.index', compact('sliders'));

    }
    public function create(){
        $today = date("Y-m-d");
        $slider = "";
        $title       = "";
        return view('admin.workprocess.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 = WorkProcess::find($request->id);

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

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

            if ($existingSlider) {
                return response()->json([
                    'status' => 'error',
                    'errors' => [
                        'name' => ['The Work Process title 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' => 'Work Process updated successfully']);
        } else {
            // Check for duplicate slider name
            $existingSlider = WorkProcess::where('name', $request->name)->first();

            if ($existingSlider) {
                return response()->json([
                    'status' => 'error',
                    'errors' => [
                        'name' => ['The Work Process 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 = WorkProcess::create([
                'name' => $request->name,
                'status' => $request->status,
                'content' => $request->content,
                'image' => $fileName,
            ]);

            

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

    


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

    public function destroy($id): JsonResponse
    {
        try {
            $slider = WorkProcess::findOrFail($id);
            
            $slider->delete();
            return response()->json([
                'status' => 'success',
                'message' => 'Work Process deleted successfully.'
            ], 200);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Work Process 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 = WorkProcess::find($id);

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