<?php

namespace App\Http\Controllers\Website;

use App\Http\Controllers\Controller;
use App\Models\Website\CareerVacancy;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class CareerVacancyController extends Controller
{
    function __construct()
    {
        // $this->middleware('permission:career-vacancy-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = CareerVacancy::orderBy('priority', 'ASC')->paginate(10);

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = CareerVacancy::when(!empty($search_query), function ($query) use ($search_query) {

                            return $query->where('career_vacancies.position', 'like', '%'.$search_query.'%');

                        })
                        ->orderBy('priority', 'ASC')
                        ->paginate($sort_by);

            return view('career-vacancy.table', compact('data'));
        }
        else
        {
            return view('career-vacancy.index',compact('data'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $priority = CareerVacancy::max('priority');
        $priority = $priority != '' ? $priority : 0;

        return view('career-vacancy.create', compact('priority'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'position' => 'required|unique:career_vacancies'
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method',
            'start_date',
            'end_date',
        ]);
        $data['start_date'] = $request->start_date ? date('Y-m-d', strtotime($request->start_date)) : null;
        $data['end_date'] = $request->end_date ? date('Y-m-d', strtotime($request->end_date)) : null;
        $data['created_by'] = Auth()->id();

        $quality = CareerVacancy::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Career Vacancy created successfully',
                'data'    => $quality
            ]);
        }
        return redirect()->route('career-vacancy.index')
            ->with('success','Career Vacancy created successfully');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $vacancy = CareerVacancy::find($id);

        return view('career-vacancy.edit',compact('vacancy'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'position' => 'required|unique:career_vacancies,position,'.$id,
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method'
        ]);


        $data['start_date'] = $request->start_date ? date('Y-m-d', strtotime($request->start_date)) : null;
        $data['end_date'] = $request->end_date ? date('Y-m-d', strtotime($request->end_date)) : null;;

        $vacancy = CareerVacancy::find($id);

        if (!$vacancy) {
            return redirect()->route('career-vacancy.index')
                ->with('error','Career Vacancy not found!');
        }

        $vacancy->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Career Vacancy updated successfully',
                'data'    => $vacancy
            ]);
        }

        return redirect()->route('career-vacancy.index')
            ->with('success','Career Vacancy updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $vacancy = CareerVacancy::find($request->id);
        $vacancy->delete();

        $Redirect = 'career-vacancy';

        if ($vacancy->is_default == '1') {
            return response()->json([
                'success' => false,
                'message' => ['Default record can not be deleted.']
            ]);
        }

        $vacancy->delete();

        $Redirect = 'career-vacancies';

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data'    => [
                'redirect' => $Redirect,
            ]
        ]);
    }

    public function changeStatus(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('status' => $request->status );
            $Update = CareerVacancy::where('id', '=', $request->id)->update($data);

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Career Vacancy status successfully change'],
                    'data'=>[
                       'redirect'=>'/users/',
                       'reload'=>true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
                ]);
            }
        }
    }


}
