<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Common;
use App\Models\Company;
use App\Models\User;
use App\Models\Vacancy;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Exception;

class VacancyController extends Controller
{
    private $folder = "company";
    public $common;
    public function __construct()
    {
        $this->common = new Common;
    }

    public function index(Request $request)
    {
        try {

            $params['data'] = [];
            $params['company'] = Company::latest()->get();
            if ($request->ajax()) {

                $input_search = $request['input_search'];
                $input_type = $request['input_type'];
                $input_company = $request['input_company'];

                $query = Vacancy::query();
                if (!empty($input_search)) {
                    $query->where(function ($q) use ($input_search) {
                        $q->where('position', 'LIKE', "%{$input_search}%")->orWhere('salary', 'LIKE', "%{$input_search}%")->orWhere('weekly_workload', 'LIKE', "%{$input_search}%")->orWhere('work_days', 'LIKE', "%{$input_search}%");
                    });
                }
               
                if($input_company != 'all'){
                    $query->where('company_id', $input_company);
                }

                if ($input_type == "today") {
                    $query->whereDay('created_at', date('d'))->whereMonth('created_at', date('m'))->whereYear('created_at', date('Y'));
                } elseif ($input_type == "month") {
                    $query->whereMonth('created_at', date('m'))->whereYear('created_at', date('Y'));
                } elseif ($input_type == "year") {
                    $query->whereYear('created_at', date('Y'));
                }
                $data = $query->with('company')->latest()->get();

                $this->common->imageNameToUrl($data, 'logo', $this->folder);

                return DataTables()::of($data)
                    ->addIndexColumn()
                    ->addColumn('action', function ($row) {

                        $vacancy_delete = __('label.delete_vacancy');

                        $delete = '<form onsubmit="return confirm(\'' . $vacancy_delete . '\');" method="POST" action="' . route('vacancy.destroy', [$row->id]) . '">
                        <input type="hidden" name="_token" value="' . csrf_token() . '">
                        <input type="hidden" name="_method" value="DELETE">
                        <button type="submit" class="edit-delete-btn" style="outline: none;"><i class="fa-solid fa-trash-can fa-xl"></i></button></form>';

                        $btn = '<div class="d-flex justify-content-around">';
                        $btn .= '<a href="' . route('vacancy.edit', [$row->id]) . '" class="edit-delete-btn">';
                        $btn .= '<i class="fa-solid fa-pen-to-square fa-xl"></i>';
                        $btn .= '</a>';
                        $btn .= $delete;
                        $btn .= '</div>';
                        return $btn;
                    })
                    ->addColumn('status', function ($row) {
                        if ($row->status == 1) {
                            return "<button type='button' id='$row->id' onclick='change_status($row->id)' class='show-btn'>" . __('label.show') . "</button>";
                        } else {
                            return "<button type='button' id='$row->id' onclick='change_status($row->id)' class='hide-btn'>" . __('label.hide') . "</button>";
                        }
                    })
                    ->addColumn('register_date', function ($row) {
                        $date = date("Y-m-d", strtotime($row->created_at));
                        return $date;
                    })
                    ->rawColumns(['action', 'status'])
                    ->make(true);
            }
            return view('admin.vacancy.index', $params);
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function create()
    {
        try {
            $params['user'] = User::latest()->get();

            return view('admin.vacancy.add', $params);
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function store(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'user_id' => 'required',
                'company_id' => 'required',
                'position' => 'required|min:2',
                'weekly_workload' => 'required',
                'work_days' => 'required',
                'schedule' => 'required',
                'requirements' => 'required',
                'job_description' => 'required',
                'type' => 'required',
            ]);
            if ($validator->fails()) {
                $errs = $validator->errors()->all();
                return response()->json(['status' => 400, 'errors' => $errs]);
            }

            $vacancy = new Vacancy();
            $vacancy['user_id'] = $request['user_id'];
            $vacancy['company_id'] = $request['company_id'];
            $vacancy['position'] = $request['position'];
            $vacancy['salary'] = $request['salary'] ?? "";
            $vacancy['weekly_workload'] = $request['weekly_workload'];
            $vacancy['work_days'] = $request['work_days'];
            $vacancy['schedule'] = $request['schedule'];
            $vacancy['requirements'] = $request['requirements'];
            $vacancy['job_description'] = $request['job_description'];
            $vacancy['type'] = $request['type'];
            $vacancy['status'] = 1;

            if ($vacancy->save()) {
                return response()->json(['status' => 200, 'success' => __('label.success_add_vacancy')]);
            } else {
                return response()->json(['status' => 400, 'errors' => __('label.error_add_vacancy')]);
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function show($id)
    {
        try {

            $data = Vacancy::where('id', $id)->first();
            if (isset($data)) {

                $data->status = $data->status === 1 ? 0 : 1;
                $data->save();
                return response()->json(['status' => 200, 'success' => __('label.status_changed'), 'status_code' => $data->status]);
            } else {
                return response()->json(['status' => 400, 'errors' => __('label.data_not_found')]);
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function edit($id)
    {
        try {

            $params['result'] = Vacancy::where('id', $id)->first();
            if (isset($params['result']['id'])) {

                $params['user'] = User::latest()->get();
                $params['company'] = Company::where('user_id', $params['result']['user_id'])->latest()->get();

                return view('admin.vacancy.edit', $params);
            } else {
                return redirect()->back()->with('error', __('label.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function update($id, Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'user_id' => 'required',
                'company_id' => 'required',
                'position' => 'required|min:2',
                'weekly_workload' => 'required',
                'work_days' => 'required',
                'schedule' => 'required',
                'requirements' => 'required',
                'job_description' => 'required',
                'type' => 'required',
            ]);
            if ($validator->fails()) {
                $errs = $validator->errors()->all();
                return response()->json(['status' => 400, 'errors' => $errs]);
            }

            $vacancy = Vacancy::where('id', $request['id'])->first();
            if (isset($vacancy['id'])) {

                $vacancy['user_id'] = $request['user_id'];
                $vacancy['company_id'] = $request['company_id'];
                $vacancy['position'] = $request['position'];
                $vacancy['salary'] = $request['salary'] ?? "";
                $vacancy['weekly_workload'] = $request['weekly_workload'];
                $vacancy['work_days'] = $request['work_days'];
                $vacancy['schedule'] = $request['schedule'];
                $vacancy['requirements'] = $request['requirements'];
                $vacancy['job_description'] = $request['job_description'];
                $vacancy['type'] = $request['type'];
                $vacancy['status'] = 1;

                if ($vacancy->save()) {

                    return response()->json(['status' => 200, 'success' => __('label.success_edit_vacancy')]);
                } else {
                    return response()->json(['status' => 400, 'errors' => __('label.error_edit_vacancy')]);
                }
            } else {
                return response()->json(['status' => 400, 'errors' => __('label.error_edit_vacancy')]);
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function destroy($id)
    {
        try {

            $data = Vacancy::where('id', $id)->first();
            if (isset($data)) {
                $data->delete();
            }
            return redirect()->route('vacancy.index')->with('success', __('label.vacancy_delete'));
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function get_comapny(Request $request)
    {
        try {
            $user_id = $request->userId;
            $comapny = [];
            $comapny = Company::where('user_id', $user_id)->latest()->get();

            return response()->json($comapny);
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }

}
