<?php

namespace App\Http\Controllers\Website;

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

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

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

            $data = JobApplication::when(!empty($search_query), function ($query) use ($search_query) {
                            return $query->where('job_applications.application_no', 'like', '%'.$search_query.'%');
                        })

                        ->paginate($sort_by);

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

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $vacancies = CareerVacancy::Select('id','position')->get();
        return view('job-application.create', compact('vacancies'));
    }

    /**
     * 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(), [
            'candidate_name' => 'required:job_applications',
            'candidate_email' => 'required:job_applications',
            'candidate_phone' => 'required:job_applications',
        ]);

        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['applied_at'] = $request->start_date ? date('Y-m-d', strtotime($request->applied_at)) : null;
        $data['reviewed_at'] = $request->reviewed_at? date('Y-m-d', strtotime($request->reviewed_at)) : null;
        $data['reviewed_by'] = Auth()->id();

        $data = JobApplication::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Job Application created successfully',
                'data'    => $data
            ]);
        }
        return redirect()->route('job-application.index')
            ->with('success','Job Application created successfully');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $application = JobApplication::find($id);
        $vacancy = CareerVacancy::Select('position')->where('id',$application->vacancy_id)->first();
        $reviewed_by = Account::select('name')->where('id',$application->reviewed_by)->first();

        return view('job-application.show',compact('application','vacancy','reviewed_by'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $application = JobApplication::find($id);
        $vacancies = CareerVacancy::Select('id','position')->get();
        return view('job-application.edit',compact('application','vacancies'));
    }

    /**
     * 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(), [
            'application_no' => 'required|unique:job_applications,application_no,'.$id,
            'candidate_name' => 'required:job_applications,candidate_name',
            'candidate_email' => 'required:job_applications,candidate_email',
            'candidate_phone' => 'required:job_applications,candidate_phone',
        ]);

        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['reviewed_at'] = $request->reviewed_at ? date('Y-m-d', strtotime($request->reviewed_at)) : null;
        $data['applied_at'] = $request->applied_at ? date('Y-m-d', strtotime($request->applied_at)) : null;;

        $application = JobApplication::find($id);

        $application->update($data);

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

        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 = JobApplication::find($request->id);

        $vacancy->delete();

        $Redirect = 'job-application';

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

}
