<?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;
use Illuminate\Validation\Rule;

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

    public function index(Request $request)
    {
        try {

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

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

                $query = Company::query();
                if (!empty($input_search)) {
                    $query->where('name', 'LIKE', "%{$input_search}%");
                }

                if ($input_user != 'all') {
                    $query->where('user_id', $input_user);
                }

                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('user')->latest()->get();

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

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

                        $delete_company = __('label.delete_company');

                        $delete = '<form onsubmit="return confirm(\'' . $delete_company . '\');" method="POST" action="' . route('company.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('company.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('register_date', function ($row) {
                        $date = date("Y-m-d", strtotime($row->created_at));
                        return $date;
                    })
                    ->make(true);
            }
            return view('admin.company.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.company.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',
                'name' => 'required|min:2',
                'country_code' => 'required',
                'mobile_number' => [
                    'required',
                    'numeric',
                    Rule::unique('tbl_company')->where(function ($query) use ($request) {
                        return $query->where('country_code', $request->country_code)
                            ->where('mobile_number', $request->mobile_number);
                    }),
                ],
                'logo' => 'required|image|mimes:jpeg,png,jpg|max:5120',
            ]);
            if ($validator->fails()) {
                $errs = $validator->errors()->all();
                return response()->json(['status' => 400, 'errors' => $errs]);
            }

            $company = new Company();
            $company['user_id'] = $request['user_id'];
            $company['name'] = $request['name'];
            $files = $request['logo'];
            $company['logo'] = $this->common->saveImage($files, $this->folder, 'company_');
            $company['country_code'] = $request['country_code'];
            $company['mobile_number'] = $request['mobile_number'];
            $company['address'] = $request['address'] ?? "";
            $company['area'] = $request['area'] ?? "";
            $company['city'] = $request['city'] ?? "";
            $company['state'] = $request['state'] ?? "";
            $company['country'] = $request['country'] ?? "";
            $company['pincode'] = $request['pincode'] ?? "";
            $company['latitude'] = $request['latitude'] ?? "";
            $company['longitude'] = $request['longitude'] ?? "";
            $company['activity'] = $request['activity'] ?? "";
            $company['position'] = $request['position'] ?? "";
            $company['status'] = 1;

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

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

                $params['user'] = User::latest()->get();
                $this->common->imageNameToUrl(array($params['result']), 'logo', $this->folder);
                return view('admin.company.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',
                'name' => 'required|min:2',
                'country_code' => 'required',
                'mobile_number' => [
                    'required',
                    'numeric',
                    Rule::unique('tbl_company')->where(function ($query) use ($request, $id) {
                        return $query->where('country_code', $request->country_code)
                            ->where('mobile_number', $request->mobile_number)
                            ->where("id", "!=", $id);
                    }),
                ],
                'logo' => 'image|mimes:jpeg,png,jpg|max:5120',
            ]);
            if ($validator->fails()) {
                $errs = $validator->errors()->all();
                return response()->json(['status' => 400, 'errors' => $errs]);
            }

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

                $company['user_id'] = $request['user_id'];
                $company['name'] = $request['name'];
                $files = $request['logo'];
                if (isset($request['logo'])) {
                    $files = $request['logo'];
                    $company['logo'] = $this->common->saveImage($files, $this->folder, 'company_');

                    $this->common->deleteImageToFolder($this->folder, basename($request->old_logo));
                }
                $company['mobile_number'] = $request['mobile_number'];
                $company['address'] = $request['address'] ?? "";
                $company['area'] = $request['area'] ?? "";
                $company['city'] = $request['city'] ?? "";
                $company['state'] = $request['state'] ?? "";
                $company['country'] = $request['country'] ?? "";
                $company['pincode'] = $request['pincode'] ?? "";
                $company['latitude'] = $request['latitude'] ?? "";
                $company['longitude'] = $request['longitude'] ?? "";
                $company['activity'] = $request['activity'] ?? "";
                $company['position'] = $request['position'] ?? "";

                if ($company->save()) {

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

            $data = Company::where('id', $id)->first();
            if (isset($data)) {
                $this->common->deleteImageToFolder($this->folder, $data['logo']);
                Vacancy::where('company_id', $id)->delete();
                $data->delete();
            }
            return redirect()->route('company.index')->with('success', __('label.company_delete'));
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
}
