<?php

namespace App\Http\Controllers\Website;

use App\Http\Controllers\Controller;
use App\Models\Website\ContentSubCategory;
use App\Models\Website\PublicContent;
use App\Models\Website\PublicContentCategory;
use Illuminate\Http\Request;
use Validator;
class PublicContentController extends Controller
{

    function __construct()
    {
        $this->middleware('permission:website-content-list|website-content-create|website-content-edit|website-content-delete', ['only' => ['index','store','list']]);
    }

    public function index(Request $request)
    {
      $contents   = PublicContent::with(['getsubCategory','getCategory'])
      ->select(['id','title','description','link','prority_status','new_tag',
      'status','public_content_category_id','sub_category_id']);
      $sort_by    = $request->get('sortby') ?? 10;
      $sort_type  = $request->get('sorttype');
      $query      = $request->get('query');
      if(!empty($query) && !empty($sort_by) && $query!=" ")
      {
         $contents->where('title', 'like', '%'.$query.'%')
                ->orWhere('description', 'like', '%'.$query.'%');
      }
      $content =$contents->orderBy('id','desc')->paginate($sort_by);
        if ($request->ajax()) {
          return view('website-setting.contents.table', compact('content'));
        }
        else
        {
            return view('website-setting.contents.index',compact('content'));
        }

    }


    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $category=PublicContentCategory::select(['id','name'])->where('status','1')->get();
        return view('website-setting.contents.create')->with(['category'=>$category]);
    }


    /**
     * 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',
                'public_content_category_id' => 'required',
            ]);
            if($validator->fails())
            {
                return response()->json(['success'=>false,'message'=>$validator->errors()->all()]);
            }
            else{

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

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


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

                        if ($response['status'] == true)
                        {
                            $pdf_file = $response['file_name'];
                        }
                        else
                        {
                            return response()->json([
                                'success' => false,
                                'message' => [$response['message']],
                                'data'    => []
                            ]);
                        }
                    }
                    else
                    {
                        $pdf_file='';
                    }
                $Content = PublicContent::create([
                                'title'                      => $request->title,
                                'company_id'                 => auth()->user()->company_id,
                                'description'                => $request->description,
                                'link'                       => $request->link,
                                'files'                      => $files,
                                'pdf_file'                   => $pdf_file,
                                'prority_status'             => $request->priority_status,
                                'public_content_category_id' => $request->public_content_category_id,
                                'new_tag'                    => $request->new_tag,
                                'sub_category_id'            => $request->sub_category_id,
                            ]);
                //

                if(isset($request->redirect))
                {
                    $Redirect = route('content-sub-category.show',$request->sub_category_id).'?category_id='.$request->public_content_category_id;
                }
                else
                {
                    $Redirect = route('public-content.index');
                }
                
                return response()->json([
                    'success' =>true,
                    'message' =>['Content 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)
    {
        $category     = PublicContentCategory::select(['id','name'])->where('status','1')->get();
        $content      = PublicContent::find($id);
        $SubaCategory = ContentSubCategory::where('status',1)->get();

        return view('website-setting.contents.edit')->with(['category'=>$category,'content'=>$content,'SubaCategory'=>$SubaCategory]);
    }

    /**
     * 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',
            'public_content_category_id' => 'required',
        ]);

        if($validator->fails())
        {
            return response()->json(['success'=>false,'message'=>$validator->errors()->all()]);
        }
        else{
            $Content=PublicContent::find($id);

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

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


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

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


                    $data = array(
                        'title' => $request->title,
                        'description' => $request->description,
                        'link' => $request->link,
                        'files' => $files,
                        'pdf_file'  => $pdf_file,
                        'prority_status' => $request->priority_status,
                        'public_content_category_id'=>$request->public_content_category_id,
                        'new_tag' => $request->new_tag,
                        'sub_category_id'=>$request->sub_category_id,
                            );
                    $Content->update($data);
            //

            if(isset($request->redirect))
            {
                $Redirect = route('content-sub-category.show',$request->sub_category_id).'?category_id='.$request->public_content_category_id;
            }
            else
            {
                $Redirect = route('public-content.index');
            }

            return response()->json([
                'success'=>true,
                'message'=>['Content successfully Update'],
                'data'=>[
                'redirect'=>$Redirect,
                '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 = PublicContent::where('id', '=', $request->id)->update($data);

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Content successfully change'],
                    'data'=>[
                        'redirect'=>'',
                        '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 = PublicContent::where(['id'=>$request->id])->delete();
        $Redirect = '/public-content';
        return response()->json([
            'success'=>true,
            'message'=>['Deleted successfully'],
            'data'=>[
            'redirect'=>$Redirect,
            ]
        ]);
    }

    public function getSubCategory(Request $request)
    {
        $SubaCategory=ContentSubCategory::where(['category_id'=>$request->category_id])->get();
        echo '<option value=" ">--Select Sub Category--</option>';
        foreach($SubaCategory as $list)
        {   
            if(isset($request->subcategory_id) && $request->subcategory_id==$list->id)
            {
                echo '<option value="'.$list->id.'" selected>'.$list->sub_category_name.'</option>';
            }
            else
            {
                echo '<option value="'.$list->id.'" >'.$list->sub_category_name.'</option>';
            }
           
        }
    }
}
