<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Common;
use App\Models\Complaint;
use App\Models\Complaint_Img;
use App\Models\Department;
use App\Models\In_Charge;
use App\Models\Notification;
use App\Models\Page;
use App\Models\Read_Notification;
use App\Models\Service;
use App\Models\Story;
use App\Models\Sub_In_Charge;
use App\Models\User;
use Exception;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class SubInChargeController extends Controller
{
    private $folder_sub_in_charge = "sub_in_charge";
    private $folder_in_charge = "in_charge";
    private $folder_department = "department";
    private $folder_service = "service";
    private $folder_complaint = "complaint";
    private $folder_user = "user";
    private $folder_notification = "notification";
    private $folder_story = "story";
    private $folder_page = "page";
    public $common;
    public $page_limit;
    public function __construct()
    {
        try {
            $this->common = new Common();
            $this->page_limit = env('PAGE_LIMIT');
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function login(Request $request) // Type 1- In-Charge
    {
        try {

            $validation = Validator::make(
                $request->all(),
                [
                    'username' => 'required',
                    'password' => 'required|min:6',
                ],
                [
                    'username.required' => __('api_msg.username_is_required'),
                    'password.required' => __('api_msg.password_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $username = $request->username;
            $type = isset($request->type) ? $request->type : 0;
            if ($type == 1) {

                $email = In_Charge::where('email', $username)->where('status', 1)->latest()->first();
                $user_name = In_Charge::where('user_name', $username)->where('status', 1)->latest()->first();
            } else {
                $email = Sub_In_Charge::where('email', $username)->where('status', 1)->latest()->first();
                $user_name = Sub_In_Charge::where('user_name', $username)->where('status', 1)->latest()->first();
            }

            $user = $email ?? $user_name;
            $device_token = $request->device_token ?? "";
            $device_type = $request->device_type ?? 0;

            if (isset($user)) {

                if (Hash::check($request->password, $user->password)) {

                    if ($type == 1) {

                        In_Charge::where('id', $user['id'])->update(['device_token' => $device_token]);
                        In_Charge::where('id', $user['id'])->update(['device_type' => $device_type]);
                        $user['device_type'] = $device_type;
                        $user['device_token'] = $device_token;
                        $user['is_in_charge'] = 1;

                        $this->common->imageNameToUrl(array($user), 'image', $this->folder_in_charge);

                        return $this->common->API_Response(200, __('api_msg.login_successfully'), array($user));
                    } else {

                        if ($user->department_id != 0 && $user->service_id != null) {

                            Sub_In_Charge::where('id', $user['id'])->update(['device_token' => $device_token]);
                            Sub_In_Charge::where('id', $user['id'])->update(['device_type' => $device_type]);
                            $user['device_type'] = $device_type;
                            $user['device_token'] = $device_token;
                            $user['is_in_charge'] = 0;

                            $this->common->imageNameToUrl(array($user), 'image', $this->folder_sub_in_charge);

                            return $this->common->API_Response(200, __('api_msg.login_successfully'), array($user));
                        } else {
                            return $this->common->API_Response(400, __('api_msg.you_are_inactive_contact_department'));
                        }
                    }
                } else {
                    return $this->common->API_Response(400, __('api_msg.email_pass_worng'));
                }
            } else {
                return $this->common->API_Response(400, __('api_msg.email_pass_worng'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function get_profile(Request $request)
    {
        try {
            $validation = Validator::make(
                $request->all(),
                [
                    'sub_incharge_id' => 'required|numeric',
                ],
                [
                    'sub_incharge_id.required' => __('api_msg.sub_incharge_id_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $sub_incharge_id = $request['sub_incharge_id'];
            $type = isset($request->type) ? $request->type : 0;

            if ($type == 1) {

                $user = In_Charge::where('id', $sub_incharge_id)->where('department_id', '!=', 0)->with('department')->first();
            } else {
                $user = Sub_In_Charge::where('id', $sub_incharge_id)->where('department_id', '!=', 0)->where('service_id', '!=', "")->with('department')->first();
            }

            if (!empty($user) && isset($user) && $user != null) {

                if ($type == 1) {
                    $this->common->imageNameToUrl(array($user), 'image', $this->folder_in_charge);
                    $user['is_in_charge'] = 1;
                } else {
                    $this->common->imageNameToUrl(array($user), 'image', $this->folder_sub_in_charge);
                    // if ($user['service'] != null) {

                    //     $user['service_name'] = $user['service']['name'];
                    // }
                    // unset($user['service']);
                    $user['is_in_charge'] = 0;
                }

                if ($user['department'] != null) {
                    $user['department_name'] = $user['department']['name'];
                }
                unset($user['department']);

                return $this->common->API_Response(200, __('api_msg.get_record_successfully'), array($user));
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function update_profile(Request $request)
    {
        try {

            $validation = Validator::make(
                $request->all(),
                [
                    'sub_incharge_id' => 'required|numeric',
                ],
                [
                    'sub_incharge_id.required' => __('api_msg.sub_incharge_id_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }
            $type = isset($request->type) ? $request->type : 0;
            if ($type == 1) {

                $data = In_Charge::where('id', $request->sub_incharge_id)->where('department_id', '!=', 0)->first();
            } else {
                $data = Sub_In_Charge::where('id', $request->sub_incharge_id)->where('department_id', '!=', 0)->where('service_id', '!=', "")->first();
            }

            $array = array();
            if (!empty($data) && isset($data) && $data != null) {

                if ($type == 1) {

                    if (isset($request->user_name) && $request->user_name != '') {

                        $check = In_Charge::where('user_name', $request->user_name)->first();
                        if (isset($check) && $check != null) {
                            if ($check->id == $data->id) {
                                $array['user_name'] = $request->user_name;
                            } else {
                                return $this->common->API_Response(400, __('api_msg.user_name_exists'));
                            }
                        } else {
                            $array['user_name'] = $request->user_name;
                        }
                    }
                    if (isset($request->email) && $request->email != '') {

                        $check_email = In_Charge::where('id', '!=', $request->sub_incharge_id)->where('email', $request['email'])->first();
                        if (isset($check_email) && $check_email != null) {
                            return $this->common->API_Response(400, __('api_msg.email_address_already_exists'));
                        }

                        $array['email'] = $request['email'];
                    }
                    if (isset($request['country_code']) && $request['country_code'] != '' && isset($request['mobile_number']) && $request['mobile_number'] != '') {

                        $check_mobile = In_Charge::where('id', '!=', $request->sub_incharge_id)->where('country_code', $request['country_code'])->where('mobile_number', $request['mobile_number'])->first();
                        if (isset($check_mobile) && $check_mobile != null) {
                            return $this->common->API_Response(400, __('api_msg.mobile_number_already_exists'));
                        }

                        $array['country_code'] = $request['country_code'];
                        $array['mobile_number'] = $request['mobile_number'];
                    }
                    if (isset($request->country_name) && $request->country_name != '') {
                        $array['country_name'] = $request->country_name;
                    }
                    if (isset($request->image) && $request->file('image') != '') {

                        $image = $request->file('image');
                        $old_image = $data['image'];

                        $array['image'] = $this->common->saveImage($image, $this->folder_in_charge, 'in_charge_');
                        $this->common->deleteImageToFolder($this->folder_in_charge, $old_image);
                    }
                } else {
                    if (isset($request->user_name) && $request->user_name != '') {

                        $check = Sub_In_Charge::where('user_name', $request->user_name)->first();
                        if (isset($check) && $check != null) {
                            if ($check->id == $data->id) {
                                $array['user_name'] = $request->user_name;
                            } else {
                                return $this->common->API_Response(400, __('api_msg.user_name_exists'));
                            }
                        } else {
                            $array['user_name'] = $request->user_name;
                        }
                    }
                    if (isset($request->email) && $request->email != '') {

                        $check_email = Sub_In_Charge::where('id', '!=', $request->sub_incharge_id)->where('email', $request['email'])->first();
                        if (isset($check_email) && $check_email != null) {
                            return $this->common->API_Response(400, __('api_msg.email_address_already_exists'));
                        }

                        $array['email'] = $request['email'];
                    }
                    if (isset($request['country_code']) && $request['country_code'] != '' && isset($request['mobile_number']) && $request['mobile_number'] != '') {

                        $check_mobile = Sub_In_Charge::where('id', '!=', $request->sub_incharge_id)->where('country_code', $request['country_code'])->where('mobile_number', $request['mobile_number'])->first();
                        if (isset($check_mobile) && $check_mobile != null) {
                            return $this->common->API_Response(400, __('api_msg.mobile_number_already_exists'));
                        }

                        $array['country_code'] = $request['country_code'];
                        $array['mobile_number'] = $request['mobile_number'];
                    }
                    if (isset($request->image) && $request->file('image') != '') {

                        $image = $request->file('image');
                        $old_image = $data['image'];

                        $array['image'] = $this->common->saveImage($image, $this->folder_sub_in_charge, 'sub_inch_');
                        $this->common->deleteImageToFolder($this->folder_sub_in_charge, $old_image);
                    }
                    if (isset($request->bio) && $request->bio != '') {
                        $array['bio'] = $request->bio;
                    }
                }
                if (isset($request->full_name) && $request->full_name != '') {
                    $array['full_name'] = $request->full_name;
                }
                if (isset($request->password) && $request->password != '') {
                    $array['password'] = hash::make($request->password);
                }
                if (isset($request->device_type) && $request->device_type != '') {
                    $array['device_type'] = $request->device_type;
                }
                if (isset($request->device_token) && $request->device_token != '') {
                    $array['device_token'] = $request->device_token;
                }
                if (isset($request->status) && $request->status != '') {
                    $array['status'] = $request->status;
                }

                if ($type == 1) {

                    In_Charge::where('id', $request->sub_incharge_id)->update($array);
                    $sub_incharge = In_Charge::where('id', $request->sub_incharge_id)->first();
                    $this->common->imageNameToUrl(array($sub_incharge), 'image', $this->folder_in_charge);
                } else {
                    Sub_In_Charge::where('id', $request->sub_incharge_id)->update($array);
                    $sub_incharge = Sub_In_Charge::where('id', $request->sub_incharge_id)->first();
                    $this->common->imageNameToUrl(array($sub_incharge), 'image', $this->folder_sub_in_charge);
                }
                return $this->common->API_Response(200, __('api_msg.profile_update_successfully'), array($sub_incharge));
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function get_complaint_by_status(Request $request) // 0-All, 1- Open, 2- In Progress,3-Archived, 4- Completed	
    {
        try {
            $validation = Validator::make(
                $request->all(),
                [
                    'sub_incharge_id' => 'required|numeric',
                    'status' => 'required',
                ],
                [
                    'sub_incharge_id.required' => __('api_msg.sub_incharge_id_is_required'),
                    'status.required' => __('api_msg.status_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $sub_incharge_id = $request->sub_incharge_id;
            $status = $request->status;
            $type = isset($request->type) ? $request->type : 0;

            $page_size = 0;
            $current_page = 0;
            $more_page = false;


            $data = Complaint::query();
            if ($status != 0) {
                $data->where('status', $status);
            }

            if ($type == 1) {

                $in_charge = $this->common->get_in_charge($sub_incharge_id);
                if ($in_charge != null) {

                    $data->where('department_id', $in_charge['department_id'])->with('department', 'service', 'user')->orderBy('id', 'DESC');
                } else {
                    return $this->common->API_Response(400, __('api_msg.data_not_found'));
                }
            } else {
                $data->where('sub_in_charge_id', $sub_incharge_id)->orderBy('id', 'DESC');
            }

            $total_rows = $data->count();
            $total_page = $this->page_limit;
            $page_size = ceil($total_rows / $total_page);
            $current_page = $request->page_no ?? 1;
            $offset = $current_page * $total_page - $total_page;

            $more_page = $this->common->more_page($current_page, $page_size);
            $pagination = $this->common->pagination_array($total_rows, $page_size, $current_page, $more_page);

            $data->take($total_page)->offset($offset);
            $data = $data->get();

            if (count($data) > 0) {

                foreach ($data as $value) {

                    $value['department_name'] = "";
                    $value['department_color'] = "";
                    $value['department_image'] = asset('assets/imgs/no_img.png');
                    $value['service_name'] = "";
                    $value['service_image'] = asset('assets/imgs/no_img.png');
                    $value['user_name'] = "";
                    $value['user_country_code'] = "";
                    $value['user_mobile_number'] = "";
                    $value['user_image'] = asset('assets/imgs/default.png');
                    $value['complaint_content'] = $this->common->get_complaint_content($value['id']);

                    if ($value['department'] != null && $value['department']['status'] == 1) {

                        $value['department_name'] = $value['department']['name'];
                        $value['department_color'] = $value['department']['department_color'];
                        $value['department_image'] = $this->common->getImage($this->folder_department, $value['department']['department_icon']);
                    }
                    if ($value['service'] != null && $value['service']['status'] == 1) {

                        $value['service_name'] = $value['service']['name'];
                        $value['service_image'] = $this->common->getImage($this->folder_service, $value['service']['image']);
                    }

                    if ($value['user'] != null) {

                        $value['user_name'] = $value['user']['full_name'];
                        $value['user_country_code'] = $value['user']['country_code'];
                        $value['user_mobile_number'] = $value['user']['mobile_number'];
                        $value['user_image'] = $this->common->getImage($this->folder_user, $value['user']['image']);
                    }
                    unset($value['department'], $value['service'], $value['user']);
                }
                return $this->common->API_Response(200, __('api_msg.get_record_successfully'), $data, $pagination);
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function content_upload(Request $request)
    {
        try {
            $rules = [
                'content_type' => 'required',
                'content' => 'required',
            ];

            if ($request->content_type == 2) {
                $rules['thumbnail_image'] = 'required|image|mimes:jpeg,png,jpg|max:10240';
            }
            $validation = Validator::make($request->all(), $rules);
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $file = $request->file('content');
            $file2 = $request->file('thumbnail_image');
            $content_type = $request->content_type;
            $thumbnail_image_name = "";

            $file_name = $this->common->saveImage($file, $this->folder_complaint, "complaint_");
            if ($content_type == 2) {
                $thumbnail_image_name = $this->common->saveImage($file2, $this->folder_complaint, "complaint_");
            }
            if (isset($file_name)) {

                $data = [];
                $data['content_type'] = $content_type;
                $data['content_name'] = $file_name;
                $data['thumbnail_image_name'] = $thumbnail_image_name;
                $data['thumbnail_image_url'] = "";
                if ($content_type == 1) {

                    $data['content_url'] = $this->common->getImage($this->folder_complaint, $file_name);
                } else {
                    $data['content_url'] = $this->common->getVideo($this->folder_complaint, $file_name);
                    $data['thumbnail_image_url'] = $this->common->getVideo($this->folder_complaint, $thumbnail_image_name);
                }

                return $this->common->API_Response(200, __('api_msg.content_upload_success'), array($data));
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_save'), []);
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function update_complaint_status(Request $request)   // Status:- 1- Open, 2- In Progress, 3-Archived, 4- Completed
    {
        try {
            $validation = Validator::make(
                $request->all(),
                [
                    'sub_incharge_id' => 'required',
                    'complaint_id' => 'required',
                    'status' => 'required',
                ],
                [
                    'sub_incharge_id.required' => __('api_msg.sub_incharge_id_is_required'),
                    'complaint_id.required' => __('api_msg.complaint_id_is_required'),
                    'status.required' => __('api_msg.status_is_required'),
                ]
            );
            if ($request->status == 4) {
                $validation = Validator::make(
                    $request->all(),
                    [
                        'complaint_reply' => 'required',
                    ],
                    [
                        'complaint_reply.required' => __('api_msg.complaint_reply_is_required'),
                    ]
                );
            }
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }
            $sub_incharge_id = $request->sub_incharge_id;
            $complaint_id = $request->complaint_id;
            $status = $request->status;
            $type = isset($request->type) ? $request->type : 0;

            if ($type == 1) {

                $in_charge = $this->common->get_in_charge($sub_incharge_id);
                if ($in_charge != null) {

                    $complaint = Complaint::where('id', $complaint_id)->where('department_id', $in_charge['department_id'])->first();
                } else {
                    return $this->common->API_Response(400, __('api_msg.data_not_save'));
                }
            } else {

                // $complaint = Complaint::where('id', $complaint_id)->where('sub_in_charge_id', $sub_incharge_id)->first();
                $complaint = Complaint::where('id', $complaint_id)->first();
            }

            if ($complaint != null) {

                $complaint->status = $status;
                if ($status == 4) {

                    $complaint->complaint_reply = $request->complaint_reply;
                    $hashtag_id = $this->common->checkHashTag($request['hashtag']);
                    $hashtagId = "";
                    if (count($hashtag_id) > 0) {
                        $hashtagId = implode(',', $hashtag_id);
                    }
                    $complaint['hashtag_id'] = $hashtagId;

                    $complaint_content = $request->complaint_content;

                    $complaint_images = json_decode($complaint_content, true);
                    if ($complaint_images != null) {

                        foreach ($complaint_images as $value) {

                            if ($value['content_url'] != null) {
                                $Insert = new Complaint_Img();
                                $Insert->complaint_id = $complaint->id;
                                $Insert->type = 2;
                                $Insert->content_type = $value['content_type'];
                                $Insert->content_url = $value['content_url'];
                                $Insert->thumbnail_image = $value['thumbnail_image'] != null ? $value['thumbnail_image'] : "";
                                $Insert->save();
                            }
                        }
                    }
                }

                $complaint->save();

                $user = User::where('id', $complaint->user_id)->first();
                $check = $this->common->BasicNotiConfiguration('request-status-updated');
                if ($user != null) {

                    if ($request['status'] == 2) {
                        // Send Mail
                        if ($check['status'] == 1 && $check['send_mail'] == 1) {
                            $this->common->Send_Mail(4, $user->email);
                        }

                        if ($check['status'] == 1 && $check['send_notification'] == 1) {
                            $title = __('label.work_on_your_raised_request_has_started');
                            $this->common->save_notification(1, $complaint->user_id, $complaint->id, $title);
                        }
                    } elseif ($request['status'] == 3) {
                        // Send Mail
                        if ($check['status'] == 1 && $check['send_mail'] == 1) {
                            $this->common->Send_Mail(5, $user->email);
                        }

                        if ($check['status'] == 1 && $check['send_notification'] == 1) {
                            $title = __('label.the_issue_request_you_raised_has_been_archived');
                            $this->common->save_notification(1, $complaint->user_id, $complaint->id, $title);
                        }
                    } elseif ($request['status'] == 4) {
                        // Send Mail
                        if ($check['status'] == 1 && $check['send_mail'] == 1) {
                            $this->common->Send_Mail(6, $user->email);
                        }

                        if ($check['status'] == 1 && $check['send_notification'] == 1) {
                            $title = __('label.your_raised_request_has_been_completed');
                            $this->common->save_notification(1, $complaint->user_id, $complaint->id, $title);
                        }
                    }
                }

                $in_charge = In_Charge::where('department_id', $complaint->department_id)->first();
                if ($check['status'] == 1 && $check['send_notification'] == 1 && $in_charge != null) {

                    if ($request['status'] == 2) {

                        $title = __('label.work_on_the_request_has_started');
                        $this->common->save_notification(4, $in_charge->id, $complaint->id, $title);
                    } elseif ($request['status'] == 3) {

                        $title = __('label.request_archived_no_further_action_needed');
                        $this->common->save_notification(4, $in_charge->id, $complaint->id, $title);
                    } elseif ($request['status'] == 4) {

                        $title = __('label.your_departments_request_has_been_completed');
                        $this->common->save_notification(4, $in_charge->id, $complaint->id, $title);
                    }
                }

                return $this->common->API_Response(200, __('api_msg.status_update_successfully'));
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_save'));
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function get_complaint_detail(Request $request)
    {
        try {
            $validation = Validator::make(
                $request->all(),
                [
                    'complaint_id' => 'required|numeric',
                    'status' => 'required|numeric',
                ],
                [
                    'complaint_id.required' => __('api_msg.complaint_id_is_required'),
                    'status.required' => __('api_msg.status_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $complaint_id = $request->complaint_id;
            $status = $request->status;

            $data = Complaint::where('id', $complaint_id)->where('status', $status)->with('department', 'service', 'user')->first();

            if ($data != null) {

                $data['department_name'] = "";
                $data['department_color'] = "";
                $data['department_image'] = asset('assets/imgs/no_img.png');
                $data['service_name'] = "";
                $data['service_image'] = asset('assets/imgs/no_img.png');
                $data['user_name'] = "";
                $data['user_country_code'] = "";
                $data['user_mobile_number'] = "";
                $data['user_image'] = asset('assets/imgs/default.png');
                $data['complaint_content'] = $this->common->get_complaint_content($data['id']);

                if ($data['department'] != null && $data['department']['status'] == 1) {

                    $data['department_name'] = $data['department']['name'];
                    $data['department_color'] = $data['department']['department_color'];
                    $data['department_image'] = $this->common->getImage($this->folder_department, $data['department']['department_icon']);
                }
                if ($data['service'] != null && $data['service']['status'] == 1) {

                    $data['service_name'] = $data['service']['name'];
                    $data['service_image'] = $this->common->getImage($this->folder_service, $data['service']['image']);
                }

                if ($data['user'] != null) {

                    $data['user_name'] = $data['user']['full_name'];
                    $data['user_country_code'] = $data['user']['country_code'];
                    $data['user_mobile_number'] = $data['user']['mobile_number'];
                    $data['user_image'] = $this->common->getImage($this->folder_user, $data['user']['image']);
                }
                unset($data['department'], $data['service'], $data['user']);

                return $this->common->API_Response(200, __('api_msg.get_record_successfully'), array($data));
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function get_sub_incharge_history(Request $request)
    {
        try {

            $validation = Validator::make(
                $request->all(),
                [
                    'sub_incharge_id' => 'required|numeric',
                    'start_date' => 'required',
                    'end_date' => 'required',
                ],
                [
                    'sub_incharge_id.required' => __('api_msg.sub_incharge_id_is_required'),
                    'start_date.required' => __('api_msg.start_date_is_required'),
                    'end_date.required' => __('api_msg.end_date_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $page_size = 0;
            $current_page = 0;
            $more_page = false;

            $sub_incharge_id = $request->sub_incharge_id;
            $start_date =  $request->start_date . ' 00:00:00';
            $end_date = $request->end_date . ' 23:59:59';

            $data = Complaint::whereBetween('updated_at', [$start_date, $end_date])->where('sub_in_charge_id', $sub_incharge_id)->where('status', 4)->with('user', 'service');

            $total_rows = $data->count();
            $total_page = $this->page_limit;
            $page_size = ceil($total_rows / $total_page);
            $current_page = $request->page_no ?? 1;
            $offset = $current_page * $total_page - $total_page;

            $more_page = $this->common->more_page($current_page, $page_size);
            $pagination = $this->common->pagination_array($total_rows, $page_size, $current_page, $more_page);

            $data->take($total_page)->offset($offset);
            $data = $data->get();

            if (count($data) > 0) {

                foreach ($data as $value) {

                    $value['user_full_name'] = "";
                    $value['user_mobile_number'] = "";
                    $value['user_email'] = "";
                    $value['user_image'] = asset('assets/imgs/no_img.png');
                    $value['service_name'] = "";
                    $value['service_image'] = asset('assets/imgs/no_img.png');
                    if ($value['user'] != null) {

                        $value['user_full_name'] = $value['user']['full_name'];
                        $value['user_mobile_number'] = $value['user']['mobile_number'];
                        $value['user_email'] = $value['user']['email'];
                        $value['user_image'] = $this->common->getImage($this->folder_user, $value['user']['image']);
                    }
                    if ($value['service'] != null) {

                        $value['service_name'] = $value['service']['name'];
                        $value['service_image'] = $this->common->getImage($this->folder_service, $value['service']['image']);
                    }
                    unset($value['user'], $value['service']);
                }

                return $this->common->API_Response(200, __('api_msg.get_record_successfully'), $data, $pagination);
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function get_sub_incharge_data(Request $request)
    {
        try {
            $validation = Validator::make(
                $request->all(),
                [
                    'sub_incharge_id' => 'required|numeric',
                ],
                [
                    'sub_incharge_id.required' => __('api_msg.sub_incharge_id_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }
            $sub_incharge_id = $request->sub_incharge_id;
            $type = isset($request->type) ? $request->type : 0;
            if ($type == 1) {

                $data = In_Charge::where('id', $sub_incharge_id)->where('department_id', '!=', 0)->first();
            } else {
                $data = Sub_In_Charge::where('id', $sub_incharge_id)->where('department_id', '!=', 0)->where('service_id', '!=', "")->first();
            }

            if ($data != null) {
                if ($type == 1) {

                    $result['total_complaint'] = Complaint::where('department_id', $data['department_id'])->count();
                    $result['today_complaint'] = Complaint::whereDay('created_at', date('d'))->whereMonth('created_at', date('m'))->whereYear('created_at', date('Y'))->where('department_id', $data['department_id'])->count();
                    $result['total_complete_complaint'] = Complaint::where('department_id', $data['department_id'])->where('status', 4)->count();
                    $result['total_cancel_complaint'] = Complaint::where('department_id', $data['department_id'])->where('status', 3)->count();
                    $result['total_in_progress_complaint'] = Complaint::where('department_id', $data['department_id'])->where('status', 2)->count();
                    $result['total_awaiting_complaint'] = Complaint::where('department_id', $data['department_id'])->where('status', 1)->count();
                } else {

                    $result['total_complaint'] = Complaint::where('sub_in_charge_id', $sub_incharge_id)->count();
                    $result['today_complaint'] = Complaint::whereDay('created_at', date('d'))->whereMonth('created_at', date('m'))->whereYear('created_at', date('Y'))->where('sub_in_charge_id', $sub_incharge_id)->count();
                    $result['total_complete_complaint'] = Complaint::where('sub_in_charge_id', $sub_incharge_id)->where('status', 4)->count();
                    $result['total_cancel_complaint'] = Complaint::where('sub_in_charge_id', $sub_incharge_id)->where('status', 3)->count();
                    $result['total_in_progress_complaint'] = Complaint::where('sub_in_charge_id', $sub_incharge_id)->where('status', 2)->count();
                    $result['total_awaiting_complaint'] = Complaint::where('sub_in_charge_id', $sub_incharge_id)->where('status', 1)->count();
                }

                return $this->common->API_Response(200, __('api_msg.get_record_successfully'), array($result));
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function get_notification(Request $request)
    {
        try {
            $validation = Validator::make(
                $request->all(),
                [
                    'user_id' => 'required|numeric',
                ],
                [
                    'user_id.required' => __('api_msg.user_id_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $user_id = $request['user_id'];

            $page_size = 0;
            $current_page = 0;
            $more_page = false;

            $user_notification_id = Read_Notification::where('user_id', $user_id)->where('type', 2)->get();
            $NotiIds = [];
            foreach ($user_notification_id as $key => $value) {
                $NotiIds[] = $value['notification_id'];
            }

            $data = Notification::where(function ($query) use ($user_id) {
                $query->where('recipient_id', $user_id)
                    ->orWhere('type', 3);
            })->where('type', '!=', 1)->where('type', '!=', 4)->whereNotIn('id', $NotiIds)->with('complaint')->orderBy('id', 'desc');

            $total_rows = $data->count();
            $total_page = $this->page_limit;
            $page_size = ceil($total_rows / $total_page);
            $current_page = $request->page_no ?? 1;
            $offset = $current_page * $total_page - $total_page;

            $more_page = $this->common->more_page($current_page, $page_size);
            $pagination = $this->common->pagination_array($total_rows, $page_size, $current_page, $more_page);

            $data->take($total_page)->offset($offset);
            $data = $data->get();

            if (count($data) > 0) {

                foreach ($data as $key => $value) {

                    $value['complatin_info'] = "";
                    $value['complatin_image'] = "";
                    $value['user_name'] = "";
                    $value['user_image'] = "";

                    if ($value['type'] == 2) {

                        if ($value['complaint'] != null) {

                            $value['complatin_info'] = $value['complaint']['complaint_info'];
                            $complaint_img = Complaint_Img::where('complaint_id', $value['complaint']['id'])->first();
                            if ($complaint_img != null) {

                                if ($complaint_img['content_type'] == 1) {
                                    $value['complatin_image'] = $this->common->getImage($this->folder_complaint, $complaint_img['content_url']);
                                } elseif ($complaint_img['content_type'] == 2) {
                                    $value['complatin_image'] = $this->common->getImage($this->folder_complaint, $complaint_img['thumbnail_image']);
                                }
                            }

                            $user = User::where('id', $value['complaint']['user_id'])->first();
                            if ($user != null) {
                                $value['user_name'] = $user['full_name'];
                                $value['user_image'] = $this->common->getImage($this->folder_user, $user['image']);
                            }
                        }
                    } else if ($value['type'] == 3) {

                        $value['image'] = $this->common->getImage($this->folder_notification, $value['image']);
                    }

                    unset($value['complaint']);
                }

                return $this->common->API_Response(200, __('api_msg.get_record_successfully'), $data, $pagination);
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function read_notification(Request $request)
    {
        try {
            $validation = Validator::make(
                $request->all(),
                [
                    'user_id' => 'required|numeric',
                    'notification_id' => 'required|numeric',
                ],
                [
                    'user_id.required' => __('api_msg.user_id_is_required'),
                    'notification_id.required' => __('api_msg.notification_id_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $data['type'] = 2;
            $data['user_id'] = $request['user_id'];
            $data['notification_id'] = $request['notification_id'];

            Read_Notification::insertGetId($data);
            return $this->common->API_Response(200, __('api_msg.notification_successfully_read'));
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function get_in_charge_notification(Request $request)
    {
        try {
            $validation = Validator::make(
                $request->all(),
                [
                    'user_id' => 'required|numeric',
                ],
                [
                    'user_id.required' => __('api_msg.user_id_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $user_id = $request['user_id'];

            $page_size = 0;
            $current_page = 0;
            $more_page = false;

            $user_notification_id = Read_Notification::where('user_id', $user_id)->where('type', 4)->get();
            $NotiIds = [];
            foreach ($user_notification_id as $key => $value) {
                $NotiIds[] = $value['notification_id'];
            }

            $data = Notification::where(function ($query) use ($user_id) {
                $query->where('recipient_id', $user_id)
                    ->orWhere('type', 3);
            })->where('type', '!=', 1)->where('type', '!=', 2)->whereNotIn('id', $NotiIds)->with('complaint')->orderBy('id', 'desc');

            $total_rows = $data->count();
            $total_page = $this->page_limit;
            $page_size = ceil($total_rows / $total_page);
            $current_page = $request->page_no ?? 1;
            $offset = $current_page * $total_page - $total_page;

            $more_page = $this->common->more_page($current_page, $page_size);
            $pagination = $this->common->pagination_array($total_rows, $page_size, $current_page, $more_page);

            $data->take($total_page)->offset($offset);
            $data = $data->get();

            if (count($data) > 0) {

                foreach ($data as $key => $value) {

                    $value['complatin_info'] = "";
                    $value['complatin_image'] = "";
                    $value['user_name'] = "";
                    $value['user_image'] = "";

                    if ($value['type'] == 2) {

                        if ($value['complaint'] != null) {

                            $value['complatin_info'] = $value['complaint']['complaint_info'];
                            $complaint_img = Complaint_Img::where('complaint_id', $value['complaint']['id'])->first();
                            if ($complaint_img != null) {

                                if ($complaint_img['content_type'] == 1) {
                                    $value['complatin_image'] = $this->common->getImage($this->folder_complaint, $complaint_img['content_url']);
                                } elseif ($complaint_img['content_type'] == 2) {
                                    $value['complatin_image'] = $this->common->getImage($this->folder_complaint, $complaint_img['thumbnail_image']);
                                }
                            }

                            $user = User::where('id', $value['complaint']['user_id'])->first();
                            if ($user != null) {
                                $value['user_name'] = $user['full_name'];
                                $value['user_image'] = $this->common->getImage($this->folder_user, $user['image']);
                            }
                        }
                    } else if ($value['type'] == 3) {

                        $value['image'] = $this->common->getImage($this->folder_notification, $value['image']);
                    }

                    unset($value['complaint']);
                }

                return $this->common->API_Response(200, __('api_msg.get_record_successfully'), $data, $pagination);
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function read_in_charge_notification(Request $request)
    {
        try {
            $validation = Validator::make(
                $request->all(),
                [
                    'user_id' => 'required|numeric',
                    'notification_id' => 'required|numeric',
                ],
                [
                    'user_id.required' => __('api_msg.user_id_is_required'),
                    'notification_id.required' => __('api_msg.notification_id_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $data['type'] = 4;
            $data['user_id'] = $request['user_id'];
            $data['notification_id'] = $request['notification_id'];

            Read_Notification::insertGetId($data);
            return $this->common->API_Response(200, __('api_msg.notification_successfully_read'));
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function get_subincharge_statistics(Request $request)
    {
        try {
            $validation = Validator::make(
                $request->all(),
                [
                    'sub_incharge_id' => 'required|numeric',
                    'start_date' => 'required',
                    'end_date' => 'required',
                ],
                [
                    'sub_incharge_id.required' => __('api_msg.sub_incharge_id_is_required'),
                    'start_date.required' => __('api_msg.start_date_is_required'),
                    'end_date.required' => __('api_msg.end_date_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $sub_incharge_id = $request->sub_incharge_id;
            $start_date = new \DateTime($request->start_date);
            $end_date   = new \DateTime($request->end_date);
            $end_date->setTime(23, 59, 59);
            $type = isset($request->type) ? $request->type : 0; // 0-Sub In-Charge,1- In-Charge

            $dailyCounts = [];

            $complaint = Complaint::query();
            if ($type == 1) {
                $in_charge = $this->common->get_in_charge($sub_incharge_id);
                if ($in_charge != null) {
                    $complaint->where('department_id', $in_charge['department_id']);
                } else {
                    return $this->common->API_Response(400, __('api_msg.data_not_found'));
                }
            } else {
                $complaint->where('sub_in_charge_id', $sub_incharge_id);
            }
            for ($date = $start_date; $date <= $end_date; $date->modify('+1 day')) {
                $dayName = $date->format('l');

                $dailyCounts[$dayName] = (clone $complaint)->whereDate('created_at', $date->format('Y-m-d'))->count();
            }

            if (count($dailyCounts) > 0) {

                return $this->common->API_Response(200, __('api_msg.get_record_successfully'), $dailyCounts);
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function add_story(Request $request)   // Type:- 1- image, 2- video
    {
        try {
            $validation = Validator::make(
                $request->all(),
                [
                    'in_charge_id' => 'required',
                    'type' => 'required',
                    'story_url' => 'required|file|mimes:jpg,jpeg,png,gif,mp4,mov,avi,wmv|max:51200',
                ],
                [
                    'in_charge_id.required' => __('api_msg.in_charge_id_is_required'),
                    'type.required' => __('api_msg.type_is_required'),
                    'story_url.required' => __('api_msg.story_url_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $insert = new Story();
            $insert->in_charge_id = $request->in_charge_id;
            $insert->description = isset($request->description) ? $request->description : "";
            $insert->type = $request->type;
            $insert->story_url = $this->common->saveImage($request->story_url, $this->folder_story, 'story_');

            if ($insert->save()) {

                return $this->common->API_Response(200, __('api_msg.story_upload_successfully'));
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_save'));
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function get_story(Request $request)
    {
        try {
            $this->common->story_expiry();
            $validation = Validator::make(
                $request->all(),
                [
                    'in_charge_id' => 'required|numeric',
                ],
                [
                    'in_charge_id.required' => __('api_msg.in_charge_id_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $in_charge_id = $request->in_charge_id;

            $data = Story::where('in_charge_id', $in_charge_id)->where('status', 1)->orderBy('id', 'DESC')->get();

            if (count($data) > 0) {

                foreach ($data as $value) {

                    if ($value['type'] == 1) {

                        $value['story_url'] = $this->common->getImage($this->folder_story, $value['story_url']);
                    } elseif ($value['type'] == 2) {
                        $value['story_url'] = $this->common->getVideo($this->folder_story, $value['story_url']);
                    }
                }
                return $this->common->API_Response(200, __('api_msg.get_record_successfully'), $data);
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function get_sub_incharge(Request $request)
    {
        try {

            $validation = Validator::make(
                $request->all(),
                [
                    'in_charge_id' => 'required|numeric',
                ],
                [
                    'in_charge_id.required' => __('api_msg.in_charge_id_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $in_charge_id = $request->in_charge_id;
            $in_charge = $this->common->get_in_charge($in_charge_id);

            if ($in_charge != null) {

                $data = Sub_In_Charge::where('department_id', $in_charge['department_id'])->where('status', 1)->orderBy('full_name', 'ASC')->get();
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_found'));
            }

            if (count($data) > 0) {

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

                return $this->common->API_Response(200, __('api_msg.get_record_successfully'), $data);
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function service_assign_to_sub_incharge(Request $request)
    {
        try {
            $validation = Validator::make(
                $request->all(),
                [
                    'sub_incharge_id' => 'required',
                    'service_id' => 'required',
                ],
                [
                    'sub_incharge_id.required' => __('api_msg.sub_incharge_id_is_required'),
                    'service_id.required' => __('api_msg.service_id_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $sub_incharge_id = $request->sub_incharge_id;
            $service_id = $request->service_id;

            $sub_incharge = Sub_In_Charge::where('id', $sub_incharge_id)->where('status', 1)->first();

            if ($sub_incharge != null) {
                $old_service_id = $sub_incharge->service_id;
                $sub_incharge->update(['service_id' => $service_id]);

                $check = $this->common->BasicNotiConfiguration('service-assigned');
                if ($check['status'] == 1 && $check['send_notification'] == 1) {
                    $title = __('label.you’ve_been_assigned_a_new_service');

                    // Convert old and new service_ids into arrays
                    $oldServices = $old_service_id ? explode(',', $old_service_id) : [];
                    $newServices = explode(',', $service_id);

                    // Find newly added services
                    $addedServices = array_diff($newServices, $oldServices);

                    // If no old service (first assignment)
                    if (empty($oldServices)) {
                        $this->common->save_notification(2, $sub_incharge->id, 0, $title);
                    } else if (!empty($addedServices)) { // If there are new ones added
                        $this->common->save_notification(2, $sub_incharge->id, 0, $title);
                    }
                }
                return $this->common->API_Response(200, __('api_msg.service_assign_successfully'));
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_save'));
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function add_service(Request $request)
    {
        try {
            if (Demo_Mode() == 1) {
                $validation = Validator::make(
                    $request->all(),
                    [
                        'department_id' => 'required',
                        'name' => 'required',
                        'description' => 'required',
                    ],
                    [
                        'department_id.required' => __('api_msg.department_id_is_required'),
                        'name.required' => __('api_msg.name_is_required'),
                        'description.required' => __('api_msg.description_is_required'),
                    ]
                );
                if ($validation->fails()) {
                    $data['status'] = 400;
                    $data['message'] = $validation->errors()->first();
                    return $data;
                }

                $insert = new Service();
                $insert->department_id = $request->department_id;
                $insert->name = $request->name;
                $insert->description =  $request->description;
                $insert->image = "";
                if ($request->file('image') != null) {
                    $insert->image = $this->common->saveImage($request->file('image'), $this->folder_service, 'service_');
                }
                $insert->sort_order = 0;
                $insert->status = 1;

                if ($insert->save()) {

                    return $this->common->API_Response(200, __('api_msg.service_add_successfully'));
                } else {
                    return $this->common->API_Response(400, __('api_msg.data_not_save'));
                }
            } else {
                return $this->common->API_Response(400, __('api_msg.this_action_is_disabled_in_demo_mode'));
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function edit_service(Request $request)
    {
        try {
            if (Demo_Mode() == 1) {
                $validation = Validator::make(
                    $request->all(),
                    [
                        'service_id' => 'required',
                    ],
                    [
                        'service_id.required' => __('api_msg.service_id_is_required'),
                    ]
                );
                if ($validation->fails()) {
                    $data['status'] = 400;
                    $data['message'] = $validation->errors()->first();
                    return $data;
                }

                $service = Service::where('id', $request['service_id'])->first();
                $array = array();
                if ($service != null) {

                    if (isset($request->name) && $request->name != '') {
                        $array['name'] = $request->name;
                    }
                    if (isset($request->description) && $request->description != '') {
                        $array['description'] = $request->description;
                    }
                    if (isset($request->image) && $request->file('image') != '') {

                        $image = $request->file('image');
                        $old_image = $service['image'];

                        $array['image'] = $this->common->saveImage($image, $this->folder_service, 'service_');
                        $this->common->deleteImageToFolder($this->folder_service, $old_image);
                    }

                    if ($service->update($array)) {

                        $this->common->imageNameToUrl(array($service), 'image', $this->folder_service);
                        return $this->common->API_Response(200, __('api_msg.service_update_successfully'), array($service));
                    } else {
                        return $this->common->API_Response(400, __('api_msg.data_not_save'));
                    }
                } else {
                    return $this->common->API_Response(400, __('api_msg.data_not_save'));
                }
            } else {
                return $this->common->API_Response(400, __('api_msg.this_action_is_disabled_in_demo_mode'));
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function delete_service(Request $request)
    {
        try {
            if (Demo_Mode() == 1) {
                $validation = Validator::make(
                    $request->all(),
                    [
                        'service_id' => 'required',
                    ],
                    [
                        'service_id.required' => __('api_msg.service_id_is_required'),
                    ]
                );
                if ($validation->fails()) {
                    $data['status'] = 400;
                    $data['message'] = $validation->errors()->first();
                    return $data;
                }

                $service = Service::where('id', $request['service_id'])->first();
                if ($service != null) {

                    $this->common->deleteImageToFolder($this->folder_service, $service['image']);
                    $service->delete();
                    return $this->common->API_Response(200, __('api_msg.service_delete_successfully'));
                } else {
                    return $this->common->API_Response(400, __('api_msg.data_not_save'));
                }
            } else {
                return $this->common->API_Response(400, __('api_msg.this_action_is_disabled_in_demo_mode'));
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function add_sub_incharge(Request $request)
    {
        try {
            if (Demo_Mode() == 1) {
                $validation = Validator::make(
                    $request->all(),
                    [
                        'department_id' => 'required',
                        'service_id' => 'required',
                        'user_name' => 'required',
                        'full_name' => 'required',
                        'email' => 'required|email|unique:tbl_sub_in_charge,email',                        
                        'password' => 'required|min:6',
                        'country_code' => 'required',
                        'mobile_number' => [
                            'required',
                            'numeric',
                            Rule::unique('tbl_sub_in_charge')->where(function ($query) use ($request) {
                                return $query->where('country_code', $request->country_code)
                                    ->where('mobile_number', $request->mobile_number);
                            }),
                        ],
                    ],
                    [
                        'department_id.required' => __('api_msg.department_id_is_required'),
                        'service_id.required' => __('api_msg.service_id_is_required'),
                        'user_name.required' => __('api_msg.user_name_is_required'),
                        'full_name.required' => __('api_msg.full_name_is_required'),
                        'email.required' => __('api_msg.email_is_required'),
                        'password.required' => __('api_msg.password_is_required'),
                        'country_code.required' => __('api_msg.country_code_is_required'),
                        'mobile_number.required' => __('api_msg.mobile_number_is_required'),
                    ]
                );
                if ($validation->fails()) {
                    $data['status'] = 400;
                    $data['message'] = $validation->errors()->first();
                    return $data;
                }

                $insert = new Sub_In_Charge();
                $insert['department_id'] = $request['department_id'];
                $insert['service_id'] = $request['service_id'];
                $insert['user_name'] = $request['user_name'];
                $insert['full_name'] = $request['full_name'];
                $insert['email'] = $request['email'];
                $insert['password'] = Hash::make($request['password']);
                $insert['country_code'] = $request['country_code'];
                $insert['mobile_number'] = $request['mobile_number'];
                $insert['image'] = "";
                if ($request->file('image') != null) {
                    $files = $request->file('image');
                    $insert['image'] = $this->common->saveImage($files, $this->folder_sub_in_charge, 'sub_inch_');
                }
                $insert['bio'] = $request['bio'] ?? "";
                $insert['device_type'] = 0;
                $insert['device_token'] = "";
                $insert['status'] = 1;

                if ($insert->save()) {

                    return $this->common->API_Response(200, __('api_msg.sub_incharge_add_successfully'));
                } else {
                    return $this->common->API_Response(400, __('api_msg.data_not_save'));
                }
            } else {
                return $this->common->API_Response(400, __('api_msg.this_action_is_disabled_in_demo_mode'));
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function edit_sub_incharge(Request $request)
    {
        try {
            if (Demo_Mode() == 1) {
                $validation = Validator::make(
                    $request->all(),
                    [
                        'sub_incharge_id' => 'required',
                    ],
                    [
                        'sub_incharge_id.required' => __('api_msg.sub_incharge_id_is_required'),
                    ]
                );
                if ($validation->fails()) {
                    $data['status'] = 400;
                    $data['message'] = $validation->errors()->first();
                    return $data;
                }

                $sub_incharge = Sub_In_Charge::where('id', $request->sub_incharge_id)->first();

                $array = array();
                if ($sub_incharge != null) {
                    if (isset($request->service_id) && $request->service_id != '') {
                        $array['service_id'] = $request->service_id;
                    }
                    if (isset($request->user_name) && $request->user_name != '') {

                        $check = Sub_In_Charge::where('user_name', $request->user_name)->first();
                        if (isset($check) && $check != null) {
                            if ($check->id == $sub_incharge->id) {
                                $array['user_name'] = $request->user_name;
                            } else {
                                return $this->common->API_Response(400, __('api_msg.user_name_exists'));
                            }
                        } else {
                            $array['user_name'] = $request->user_name;
                        }
                    }
                    if (isset($request->email) && $request->email != '') {

                        $check_email = Sub_In_Charge::where('id', '!=', $request->sub_incharge_id)->where('email', $request['email'])->first();
                        if (isset($check_email) && $check_email != null) {
                            return $this->common->API_Response(400, __('api_msg.email_address_already_exists'));
                        }

                        $array['email'] = $request['email'];
                    }
                    if (isset($request['country_code']) && $request['country_code'] != '' && isset($request['mobile_number']) && $request['mobile_number'] != '') {

                        $check_mobile = Sub_In_Charge::where('id', '!=', $request->sub_incharge_id)->where('country_code', $request['country_code'])->where('mobile_number', $request['mobile_number'])->first();
                        if (isset($check_mobile) && $check_mobile != null) {
                            return $this->common->API_Response(400, __('api_msg.mobile_number_already_exists'));
                        }

                        $array['country_code'] = $request['country_code'];
                        $array['mobile_number'] = $request['mobile_number'];
                    }
                    if (isset($request->image) && $request->file('image') != '') {

                        $image = $request->file('image');
                        $old_image = $sub_incharge['image'];

                        $array['image'] = $this->common->saveImage($image, $this->folder_sub_in_charge, 'sub_inch_');
                        $this->common->deleteImageToFolder($this->folder_sub_in_charge, $old_image);
                    }
                    if (isset($request->bio) && $request->bio != '') {
                        $array['bio'] = $request->bio;
                    }
                    if (isset($request->full_name) && $request->full_name != '') {
                        $array['full_name'] = $request->full_name;
                    }
                    if (isset($request->password) && $request->password != '') {
                        $array['password'] = hash::make($request->password);
                    }
                    if (isset($request->device_type) && $request->device_type != '') {
                        $array['device_type'] = $request->device_type;
                    }
                    if (isset($request->device_token) && $request->device_token != '') {
                        $array['device_token'] = $request->device_token;
                    }
                    if (isset($request->status) && $request->status != '') {
                        $array['status'] = $request->status;
                    }

                    if ($sub_incharge->update($array)) {

                        $this->common->imageNameToUrl(array($sub_incharge), 'image', $this->folder_sub_in_charge);
                        return $this->common->API_Response(200, __('api_msg.sub_incharge_update_successfully'), array($sub_incharge));
                    } else {
                        return $this->common->API_Response(400, __('api_msg.data_not_save'));
                    }
                } else {
                    return $this->common->API_Response(400, __('api_msg.data_not_save'));
                }
            } else {
                return $this->common->API_Response(400, __('api_msg.this_action_is_disabled_in_demo_mode'));
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function delete_sub_incharge(Request $request)
    {
        try {
            if (Demo_Mode() == 1) {
                $validation = Validator::make(
                    $request->all(),
                    [
                        'sub_incharge_id' => 'required',
                    ],
                    [
                        'sub_incharge_id.required' => __('api_msg.sub_incharge_id_is_required'),
                    ]
                );
                if ($validation->fails()) {
                    $data['status'] = 400;
                    $data['message'] = $validation->errors()->first();
                    return $data;
                }

                $sub_incharge = Sub_In_Charge::where('id', $request['sub_incharge_id'])->first();
                if ($sub_incharge != null) {

                    $this->common->deleteImageToFolder($this->folder_sub_in_charge, $sub_incharge['image']);
                    $sub_incharge->delete();
                    return $this->common->API_Response(200, __('api_msg.sub_incharge_delete_successfully'));
                } else {
                    return $this->common->API_Response(400, __('api_msg.data_not_save'));
                }
            } else {
                return $this->common->API_Response(400, __('api_msg.this_action_is_disabled_in_demo_mode'));
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function get_sub_incharge_by_service(Request $request)
    {
        try {

            $validation = Validator::make(
                $request->all(),
                [
                    'department_id' => 'required|numeric',
                    'service_id' => 'required|numeric',
                ],
                [
                    'department_id.required' => __('api_msg.department_id_is_required'),
                    'service_id.required' => __('api_msg.service_id_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $department_id = $request->department_id;
            $service_id = $request->service_id;
            $sub_incharge = Sub_In_Charge::where('department_id', $department_id)->where('status', 1)->get();
            $sub_incharge_ids = [];
            if (count($sub_incharge) > 0) {

                foreach ($sub_incharge as $value) {
                    $service = explode(',', $value['service_id']);

                    if (in_array($service_id, $service)) {
                        $sub_incharge_ids[] = $value['id'];
                    }
                }
            }

            if (count($sub_incharge_ids) > 0) {

                $data = Sub_In_Charge::whereIn('id', $sub_incharge_ids)->where('status', 1)->orderBy('full_name', 'ASC')->get();
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_found'));
            }

            if (count($data) > 0) {

                $service = Service::where('id', $service_id)->first();
                if ($service != null) {
                    $service['image'] = $this->common->getImage($this->folder_service, $service['image']);
                }

                foreach ($data as $value) {

                    $value['service_name'] = "";
                    $value['service_image'] = "";
                    if ($service != null) {
                        $value['service_name'] = $service['name'];
                        $value['service_image'] = $service['image'];
                    }
                    $value['image'] = $this->common->getImage($this->folder_sub_in_charge, $value['image']);
                }
                return $this->common->API_Response(200, __('api_msg.get_record_successfully'), $data);
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function assign_sub_incharge_to_complaint(Request $request)
    {
        try {
            $validation = Validator::make(
                $request->all(),
                [
                    'sub_incharge_id' => 'required',
                    'complaint_id' => 'required',
                ],
                [
                    'sub_incharge_id.required' => __('api_msg.sub_incharge_id_is_required'),
                    'complaint_id.required' => __('api_msg.complaint_id_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $sub_incharge_id = $request->sub_incharge_id;
            $complaint_id = $request->complaint_id;

            $complaint = Complaint::where('id', $complaint_id)->first();

            if ($complaint != null) {

                $complaint->update(['sub_in_charge_id' => $sub_incharge_id]);
                $sub_incharge = Sub_In_Charge::where('id', $sub_incharge_id)->first();

                $check = $this->common->BasicNotiConfiguration('request-assigned');
                if ($check['status'] == 1 && $check['send_notification'] == 1 && $sub_incharge != null) {
                    $title = __('label.attention_required_new_request_assigned');
                    $this->common->save_notification(2, $sub_incharge->id, $complaint->id, $title);
                }

                return $this->common->API_Response(200, __('api_msg.sub_incharge_assign_successfully'));
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_save'));
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function get_pages()
    {
        try {

            $return['status'] = 200;
            $return['message'] = __('api_msg.get_record_successfully');
            $return['result'] = [];

            $data = Page::where('type', 2)->get();
            for ($i = 0; $i < count($data); $i++) {

                $return['result'][$i]['title'] = $data[$i]['title'];
                $return['result'][$i]['url'] = env('APP_URL') . '/public/pages/2/' . $data[$i]['title'];
                $return['result'][$i]['icon'] = $this->common->getImage($this->folder_page, $data[$i]['icon']);
            }
            return $return;
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function get_complaint_by_date(Request $request)
    {
        try {
            $validation = Validator::make(
                $request->all(),
                [
                    'sub_incharge_id' => 'required|numeric',
                    'date' => 'required',
                ],
                [
                    'sub_incharge_id.required' => __('api_msg.sub_incharge_id_is_required'),
                    'date.required' => __('api_msg.date_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $sub_incharge_id = $request->sub_incharge_id;

            // Parse date safely with DateTime
            $dateObj = new \DateTime($request->date);
            $date    = $dateObj->format('Y-m-d');

            $complaints = Complaint::where('sub_in_charge_id', $sub_incharge_id)->whereDate('created_at', $date)->with('service', 'user')->latest()->get();

            if (count($complaints) > 0) {

                $data['data'] = [];
                foreach ($complaints as $value) {

                    $value['service_name'] = "";
                    $value['service_image'] = asset('assets/imgs/no_img.png');
                    $value['user_name'] = "";
                    $value['user_image'] = asset('assets/imgs/default.png');

                    if ($value['service'] != null && $value['service']['status'] == 1) {

                        $value['service_name'] = $value['service']['name'];
                        $value['service_image'] = $this->common->getImage($this->folder_service, $value['service']['image']);
                    }
                    if ($value['user'] != null) {

                        $value['user_name'] = $value['user']['full_name'];
                        $value['user_image'] = $this->common->getImage($this->folder_user, $value['user']['image']);
                    }
                    unset($value['service'], $value['user']);

                    $data['data'][] = $value;
                }
                $data['total_complaint'] = Complaint::where('sub_in_charge_id', $sub_incharge_id)->whereDate('created_at', $date)->count();
                $data['cacnel_complaint'] = Complaint::where('sub_in_charge_id', $sub_incharge_id)->whereDate('created_at', $date)->where('status', 3)->count();
                return $this->common->API_Response(200, __('api_msg.get_record_successfully'), $data);
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
}
