<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Common;
use App\Models\Department;
use App\Models\Department_Working_Time;
use App\Models\In_Charge;
use App\Models\Service;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Exception;
use Illuminate\Validation\Rule;

class DepartmentController extends Controller
{
    private $folder = "department";
    private $folder_service = "service";
    public $common;
    public function __construct()
    {
        $this->common = new Common;
    }

    public function index(Request $request)
    {
        try {

            $params['data'] = Department::orderby('name', 'asc')->latest()->get();
            $params['in_charge'] = In_Charge::where('department_id', 0)->orderby('full_name', 'asc')->get();

            $input_search = $request['input_search'];
            if (isset($input_search)) {
                $params['data'] = Department::where('name', 'LIKE', "%{$input_search}%")->orderby('name', 'asc')->latest()->get();
            } else {
                $params['data'] = Department::orderby('name', 'asc')->latest()->get();
            }

            $this->common->imageNameToUrl($params['data'], 'department_icon', $this->folder);

            return view('admin.department.index', $params);
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function create()
    {
        try {
            $params['in_charge'] = In_Charge::where('department_id', 0)->orderby('full_name', 'asc')->get();
            return view('admin.department.add', $params);
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function store(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'name' => 'required',
                'in_charge_id' => 'required',
                'country_code' => 'required',
                'mobile_number' => [
                    'required',
                    'numeric',
                    Rule::unique('tbl_department')->where(function ($query) use ($request) {
                        return $query->where('country_code', $request->country_code)
                            ->where('mobile_number', $request->mobile_number);
                    }),
                ],
                'department_color' => 'required',
                'description' => 'required',
                'department_icon' => 'required|image|mimes:jpeg,png,jpg|max:5120',
            ]);
            if ($validator->fails()) {
                $errs = $validator->errors()->all();
                return response()->json(['status' => 400, 'errors' => $errs]);
            }

            $department = new Department();
            $department['name'] = $request['name'];
            $department['description'] = $request['description'];
            $department['country_code'] = $request['country_code'];
            $department['mobile_number'] = $request['mobile_number'];
            $department['telephone_number'] = $request['telephone_number'] ?? "";
            $department['department_color'] = $request['department_color'];
            $files = $request['department_icon'];
            $department['department_icon'] = $this->common->saveImage($files, $this->folder, 'dep_');
            $department['address'] = $request['address'] ?? '';
            $department['area'] = $request['area'] ?? '';
            $department['city'] = $request['city'] ?? '';
            $department['state'] = $request['state'] ?? '';
            $department['country'] = $request['country'] ?? '';
            $department['pincode'] = $request['pincode'] ?? '';
            $department['latitude'] = $request['latitude'] ?? '';
            $department['longitude'] = $request['longitude'] ?? '';
            $department['sort_order'] = 0;
            $department['status'] = 1;

            if ($department->save()) {

                // Working Time
                $working_times = [];
                foreach (range(1, 7) as $day) {
                    $working_times[] = [
                        'department_id' => $department['id'],
                        'week_day' => $day,
                        'start_time' => $request->input("start_time_{$day}") ?? '00:00',
                        'end_time' => $request->input("end_time_{$day}") ?? '00:00',
                        'status' => $request->input("day_{$day}") ?? 0,
                    ];
                }
                Department_Working_Time::insert($working_times);
                In_Charge::where('id', $request['in_charge_id'])->update(['department_id' => $department->id]);

                return response()->json(['status' => 200, 'success' => __('label.success_add_department')]);
            } else {
                return response()->json(['status' => 400, 'errors' => __('label.error_add_department')]);
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function show($id)
    {
        try {
            $data = Department::where('id', $id)->first();
            if ($data->status == 0) {
                $data->status = 1;
            } elseif ($data->status == 1) {
                $data->status = 0;
            } else {
                $data->status = 0;
            }
            $data->save();
            return response()->json(array('status' => 200, 'success' => __('label.status_changed'), 'id' => $data->id, 'Status' => $data->status));
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function edit($id)
    {
        try {

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

                $this->common->imageNameToUrl(array($params['result']), 'department_icon', $this->folder);

                $params['work_time'] = Department_Working_Time::where('department_id', $id)->orderby('week_day', 'asc')->get()->toArray();

                return view('admin.department.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(), [
                'name' => 'required',
                'country_code' => 'required',
                'mobile_number' => [
                    'required',
                    'numeric',
                    Rule::unique('tbl_department')->where(function ($query) use ($request, $id) {
                        return $query->where('country_code', $request->country_code)
                            ->where('mobile_number', $request->mobile_number)
                            ->where('id', '!=', $id);
                    }),
                ],
                'department_color' => 'required',
                'description' => 'required',
                'department_icon' => 'image|mimes:jpeg,png,jpg|max:5120',
            ]);
            if ($validator->fails()) {
                $errs = $validator->errors()->all();
                return response()->json(['status' => 400, 'errors' => $errs]);
            }

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

                $department['name'] = $request['name'];
                $department['description'] = $request['description'];
                $department['country_code'] = $request['country_code'];
                $department['mobile_number'] = $request['mobile_number'];
                $department['telephone_number'] = $request['telephone_number'] ?? "";
                $department['department_color'] = $request['department_color'];
                if (isset($request['department_icon'])) {
                    $files = $request['department_icon'];
                    $department['department_icon'] = $this->common->saveImage($files, $this->folder, 'dep_');

                    $this->common->deleteImageToFolder($this->folder, basename($request['old_department_icon']));
                }
                $department['address'] = $request['address'] ?? '';
                $department['area'] = $request['area'] ?? '';
                $department['city'] = $request['city'] ?? '';
                $department['state'] = $request['state'] ?? '';
                $department['country'] = $request['country'] ?? '';
                $department['pincode'] = $request['pincode'] ?? '';
                $department['latitude'] = $request['latitude'] ?? '';
                $department['longitude'] = $request['longitude'] ?? '';
                $department['status'] = 1;

                if ($department->save()) {

                    // Working Time
                    foreach (range(1, 7) as $day) {
                        $data = [
                            'start_time' => $request->input("start_time_{$day}") ?? '00:00',
                            'end_time' => $request->input("end_time_{$day}") ?? '00:00',
                            'status' => $request->input("day_{$day}") ?? 0,
                        ];

                        Department_Working_Time::updateOrCreate(
                            [
                                'department_id' => $department['id'],
                                'week_day' => $day,
                            ],
                            $data
                        );
                    }
                    return response()->json(['status' => 200, 'success' => __('label.success_edit_department')]);
                } else {
                    return response()->json(['status' => 400, 'errors' => __('label.error_edit_department')]);
                }
            } else {
                return response()->json(['status' => 400, 'errors' => __('label.error_edit_sub_in_charge')]);
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function destroy($id)
    {
        try {

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

                $this->common->deleteImageToFolder($this->folder, $data['department_icon']);
                Department_Working_Time::where('department_id', $id)->delete();
                In_Charge::where('department_id', $id)->update(['department_id' => 0]);
                $data->delete();
            }
            return redirect()->route('department.index')->with('success', __('label.department_delete'));
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function SortOrder(Request $request)
    {
        try {

            $ids = $request['ids'];
            if (isset($ids) && $ids != "") {

                $id_array = explode(',', $ids);
                for ($i = 0; $i < count($id_array); $i++) {
                    Department::where('id', $id_array[$i])->update(['sort_order' => $i + 1]);
                }
            }
            return response()->json(['status' => 200, 'success' => __('label.department_sortorder_successfully')]);
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function service_index($department_id, Request $request)
    {
        try {

            $params['department_id'] = $department_id;

            $params['data'] = Service::where('department_id', $department_id)->where('department_id', '!=', 0)->orderby('sort_order', 'asc')->latest()->get();

            if ($request->ajax()) {

                $input_search = $request['input_search'];
                if (isset($input_search)) {
                    $data = Service::where('department_id', $department_id)->where('department_id', '!=', 0)->where('name', 'LIKE', "%{$input_search}%")->orderby('sort_order', 'asc')->latest()->get();
                } else {
                    $data = Service::where('department_id', $department_id)->where('department_id', '!=', 0)->orderby('sort_order', 'asc')->latest()->get();
                }

                $this->common->imageNameToUrl($data, 'image', $this->folder_service);

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

                        $service_delete = __('label.delete_service');

                        $delete = '<form onsubmit="return confirm(\'' . $service_delete . '\');" method="POST" action="' . route('department.service.delete', [$row->department_id, $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 class="edit-delete-btn edit_service" data-toggle="modal" href="#EditModel" data-id="' . $row->id . '" data-name="' . $row->name . '" data-description="' . $row->description . '" data-department_id="' . $row->department_id . '" data-image="' . $row->image . '">';
                        $btn .= '<i class="fa-solid fa-pen-to-square fa-xl"></i>';
                        $btn .= '</a>';
                        $btn .= $delete;
                        $btn .= '</a></div>';
                        return $btn;
                    })
                    ->rawColumns(['action'])
                    ->make(true);
            }
            return view('admin.department.service_index', $params);
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function service_store(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'name' => 'required',
                'description' => 'required',
                'department_id' => 'required',
                'image' => 'image|mimes:jpeg,png,jpg|max:5120',
            ]);
            if ($validator->fails()) {
                $errs = $validator->errors()->all();
                return response()->json(['status' => 400, 'errors' => $errs]);
            }
            
            $requestData = $request->all();
            if (isset($requestData['image'])) {
                $files = $requestData['image'];
                $requestData['image'] = $this->common->saveImage($files, $this->folder, 'service_');
            } else {
                $requestData['image'] = "";
            }
            $requestData['sort_order'] = 0;
            $requestData['status'] = 1;

            $data = Service::updateOrCreate(['id' => $requestData['id']], $requestData);
            if (isset($data->id)) {
                return response()->json(['status' => 200, 'success' => __('label.success_add_service')]);
            } else {
                return response()->json(['status' => 400, 'errors' => __('label.error_add_service')]);
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function service_update(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'name' => 'required',
                'description' => 'required',
                'department_id' => 'required',
                'image' => 'image|mimes:jpeg,png,jpg|max:5120',
            ]);
            if ($validator->fails()) {
                $errs = $validator->errors()->all();
                return response()->json(['status' => 400, 'errors' => $errs]);
            }
            
            $requestData = $request->all();
            if (isset($requestData['image'])) {
                $files = $requestData['image'];
                $requestData['image'] = $this->common->saveImage($files, $this->folder, 'service_');

                $this->common->deleteImageToFolder($this->folder, basename($requestData['old_image']));
            }
            unset($requestData['old_image']);

            $data = Service::updateOrCreate(['id' => $requestData['id']], $requestData);
            if (isset($data->id)) {
                return response()->json(['status' => 200, 'success' => __('label.success_edit_service')]);
            } else {
                return response()->json(['status' => 400, 'errors' => __('label.error_edit_service')]);
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function service_delete($department_id, $id)
    {
        try {

            $data = Service::where('id', $id)->first();
            if (isset($data)) {
                $this->common->deleteImageToFolder($this->folder_service, $data['image']);
                $data->delete();
            }
            return redirect()->route("department.service.index", [$department_id])->with('success', __('label.service_delete'));
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
}
