<?php

namespace App\Http\Controllers\Website;

use App\Http\Controllers\Controller;
use App\Models\Website\GalleryType;
use App\Models\Website\TblPhotoGallery;
use App\Models\Website\TblPhotoGalleryImage;
use Illuminate\Http\Request;
use Validator;

class PhotoGalleryController extends Controller
{

    function __construct()
    {
        $this->middleware('permission:website-photo-gallery-list|website-photo-gallery-create|website-photo-gallery-edit|website-photo-gallery-delete', ['only' => ['index','store','list']]);
    }
    public function index(Request $request)
    {
      $TblPhotoGallerys = TblPhotoGallery::select([
            'id',
            'title',
            'details',
            'cover_pic',
            'date',
            'priority',
            'status'
        ]);

            $sort_by        = $request->get('sortby') ?? 10;
            $sort_type      = $request->get('sorttype');
            $query          = $request->get('query');
            if(!empty($query) && !empty($sort_by) && $query!=" ")
            {

              $TblPhotoGallerys->where('title', 'like', '%'.$query.'%')
              ->orWhere('details', 'like', '%'.$query.'%');
            }
            $TblPhotoGallery =$TblPhotoGallerys->orderBy('priority','asc')->paginate($sort_by);
        if ($request->ajax()) {
          return view('website-setting.photo-gallery.table', compact('TblPhotoGallery'));
        }
        else
        {
            return view('website-setting.photo-gallery.index',compact('TblPhotoGallery'));
        }

    }


    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $priority    = TblPhotoGallery::max('priority');
        $priority    = $priority != '' ? $priority : 0;
        $types       = GalleryType::select(['id','type_of_gallery'])->where('status','1')->get();

        return view('website-setting.photo-gallery.create',compact('priority','types'));
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        if($request->isMethod('post'))
        {
           // return $request;
            $validator =  Validator::make($request->all(),[
                'title' => 'required',
                'cover_pic' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            ]);
            if($validator->fails())
            {
                return response()->json(['success'=>false,'message'=>$validator->errors()->all()]);
            }
            else{

                if ($request->hasFile('cover_pic')) {
                    $url        =\Str::slug($request->title);
                    $path       ="upload/photo_gallery/".$url.'/'.date('Y').'/'.date('m');
                    $response = uploadImage($path,$request->cover_pic);

                    if ($response['status'] == true)
                    {
                        $image = $response['file_name'];
                    }
                    else
                    {
                        return response()->json([
                            'success' => false,
                            'message' => $response['message'],
                            'data'    => []
                        ]);
                    }
                }
                else
                {
                    $image='';
                }

                $Category = TblPhotoGallery::create([
                                'title'             => $request->title,
                                'sub_title'         => $request->sub_title,
                                'company_id'         => auth()->user()->company_id,
                                'cover_pic'         => $image,
                                'date'              => date('Y-m-d', strtotime($request->date)),
                                'gallery_keywords'  =>$request->gallery_keywords,
                                'priority'          =>$request->priority,
                                'details'           =>$request->details,
                                'gallery_type'      =>$request->gallery_type,
                            ]);
                //
                $Redirect = route('photos-gallery.index');
                return response()->json([
                    'success'=>true,
                    'message'=>['Photo Gallery successfully created'],
                    'data'=>[
                    'redirect'=>$Redirect,
                    'reload'=>true,
                    ]
                ]);
            }
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id,Request $request)
    {
        $TblPhotoGallery = TblPhotoGallery::where(['id'=>$id])->first();
        //
        $types       = GalleryType::select(['id','type_of_gallery'])->where('status','1')->get();
        return view('website-setting.photo-gallery.edit')->with(['TblPhotoGallery'=>$TblPhotoGallery,'types'=>$types]);
    }


     /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id,Request $request)
    {
        $TblPhotoGallery = TblPhotoGallery::with('getImagesAll')->where(['id'=>$id])->first();
        //
        return view('website-setting.photo-gallery.show')->with(['TblPhotoGallery'=>$TblPhotoGallery]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update($id,Request $request)
    {
        $validator =  Validator::make($request->all(),[
            'title' => 'required',
        ]);
        if($validator->fails())
        {
            return response()->json(['success'=>false,'message'=>$validator->errors()->all()]);
        }
        else{
            $TblPhotoGallery=TblPhotoGallery::find($id);

            if ($request->hasFile('cover_pic')) {
                $url        =\Str::slug($request->title);
                $path       ="upload/photo_gallery/".$url.'/'.date('Y').'/'.date('m');
                $response = uploadImage($path,$request->cover_pic,$TblPhotoGallery->cover_pic);

                if ($response['status'] == true)
                {
                    $image = $response['file_name'];
                }
                else
                {
                    return response()->json([
                        'success' => false,
                        'message' => $response['message'],
                        'data'    => []
                    ]);
                }
            }
            else
            {
                $image=$TblPhotoGallery->cover_pic;
            }

            $data = array(
                    'title'            => $request->title,
                    'sub_title'        => $request->sub_title,
                    'cover_pic'        => $image,
                    'company_id'       => auth()->user()->company_id,
                    'date'             => date('Y-m-d', strtotime($request->date)),
                    'gallery_keywords' =>$request->gallery_keywords,
                    'priority'         =>$request->priority,
                    'details'          =>$request->details,
                    'gallery_type'     =>$request->gallery_type,
                    );
                    TblPhotoGallery::whereId($id)->update($data);
            //
            $Redirect = '';
            return response()->json([
                'success'=>true,
                'message'=>['Photo Gallery successfully Update'],
                'data'=>[
                'redirect'=>route('photos-gallery.index'),
                'reload'=>false,
                ]
            ]);
        }
    }




    /**
     * change service status.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function changestatus(Request $request)
    {
        if ($request->ajax())
        {
            $data = array('status' => $request->status );
            $Update = TblPhotoGallery::where('id', '=', $request->id)->update($data);

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Status successfully change'],
                    'data'=>[
                        'redirect'=>route('photos-gallery.index'),
                        'reload'=>true,
                    ]
                ]);
            }
            else{
                return response()->json([
                    'success'=>false,
                    'message'=>['Error for change status'],
                    'data'=>[
                        'redirect'=>'',
                    ]
                ]);
            }
        }
    }
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $Delete = TblPhotoGallery::where(['id'=>$request->id])->delete();
        $Redirect = '/photos-gallery';
        return response()->json([
            'success'=>true,
            'message'=>['Deleted successfully'],
            'data'=>[
            'redirect'=>$Redirect,
            ]
        ]);
    }

    public function storeitem(Request $request)
    {
        if($request->isMethod('post'))
        {
            $validator =  Validator::make($request->all(),[
                'priority' => 'required',
                'image.*'  => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
            ]);
            if($validator->fails()) {
                return response()->json(['success'=>false,'message'=>$validator->errors()->all()]);
            } else {
                if ($request->hasFile('image')) {
                    foreach ($request->image as $key => $value) {
                        if ($value != '') {
                            $url      = \Str::slug($request->image_name ?? 'photo_gallery');
                            $path     = "upload/photo_gallery/".$url.'/'.date('Y').'/'.date('m');
                            $response = uploadImage($path, $value);

                            if ($response['status'] == true)
                            {
                                $image = $response['file_name'];

                                $Category = TblPhotoGalleryImage::create([
                                    'photo_gallery_id' => $request->mid,
                                    'image_name'       => $request->image_name,
                                    'priority'         => ($request->priority + $key),
                                    'image'            => $image,
                                ]);
                            }

                            $Redirect = route('photos-gallery.index');
                        }
                    }

                    return response()->json([
                        'success' => true,
                        'message' => ['Photo Gallery successfully created'],
                        'data'    => [
                            'redirect' => $Redirect,
                            'reload'   => true,
                        ]
                    ]);
                } else {
                    return response()->json([
                        'success' => false,
                        'message' => ["Please select a valid file!"]
                    ]);
                }
            }
        }
    }

    public function deleteitem(Request $request)
    {
        $Delete = TblPhotoGalleryImage::where(['id'=>$request->id])->delete();
        $Redirect = '/photos-gallery';
        return response()->json([
            'success'=>true,
            'message'=>['Deleted successfully'],
            'data'=>[
            'redirect'=>$Redirect,
            ]
        ]);
    }
}
