<?php

namespace App\Http\Controllers\In_Charge;

use App\Http\Controllers\Controller;
use App\Models\Common;
use App\Models\Service;
use App\Models\Sub_In_Charge;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Exception;
use Illuminate\Validation\Rule;

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

    public function index(Request $request)
    {
        try {

            $params['data'] = [];
            $incharge = InCharge_Data();
            $params['service'] = Service::where('department_id', $incharge['department_id'])->orderby('name', 'asc')->get();

            if ($request->ajax()) {

                $input_search = $request['input_search'];
                $input_status = $request['input_status'];

                $query = Sub_In_Charge::where('department_id', $incharge['department_id'])->where('service_id', '!=', "");
                if (!empty($input_search)) {
                    $query->where(function ($q) use ($input_search) {
                        $q->where('user_name', 'LIKE', "%{$input_search}%")->orWhere('full_name', 'LIKE', "%{$input_search}%")->orWhere('email', 'LIKE', "%{$input_search}%")->orWhere('mobile_number', 'LIKE', "%{$input_search}%");
                    });
                }
                if ($input_status != "all") {
                    $query->where('status', $input_status);
                }
                $data = $query->with('service')->latest()->get();

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

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

                        return '<a class="edit-delete-btn in_charge_update" title="Edit" style= "font-weight:bold;" data-toggle="modal" href="#edit_incharge_model" data-id="' . $row->id . '">' . __('label.transfer') . '</a>';
                    })
                    ->addColumn('action', function ($row) {

                        $sub_in_charge_delete = __('label.delete_sub_in_charge');

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

                        $btn = '<div class="d-flex justify-content-around">';
                        $btn .= '<a href="' . route('insub_incharge.edit', [$row->id]) . '" class="edit-delete-btn">';
                        $btn .= '<i class="fa-solid fa-pen-to-square fa-xl"></i>';
                        $btn .= '</a>';
                        $btn .= $delete;
                        $btn .= '</div>';
                        return $btn;
                    })
                    ->addColumn('status', function ($row) {
                        if ($row->status == 1) {
                            $showLabel = __('label.active');
                            return "<button type='button' id='$row->id' onclick='change_status($row->id)' class='show-btn'>$showLabel</button>";
                        } else {
                            $hideLabel = __('label.inactive');
                            return "<button type='button' id='$row->id' onclick='change_status($row->id)' class='hide-btn'>$hideLabel</button>";
                        }
                    })
                    ->rawColumns(['transfer', 'action', 'status'])
                    ->make(true);
            }
            return view('incharge.sub_in_charge.index', $params);
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function create()
    {
        try {
            $params = [];
            $incharge = InCharge_Data();
            $params['service'] = Service::where('department_id', $incharge['department_id'])->orderby('name', 'asc')->get();
            return view('incharge.sub_in_charge.add', $params);
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function store(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'user_name' => 'required|min:2',
                'full_name' => 'required|min:2',
                'email' => 'required|email|unique:tbl_sub_in_charge,email',                
                '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);
                    }),
                ],
                'password' => 'required|min:6',
                'image' => 'image|mimes:jpeg,png,jpg|max:5120',
            ]);
            if ($validator->fails()) {
                $errs = $validator->errors()->all();
                return response()->json(['status' => 400, 'errors' => $errs]);
            }

            $incharge = InCharge_Data();
            $man = new Sub_In_Charge();
            $man['department_id'] = $incharge['department_id'];
            $man['service_id'] = isset($request->service_id) ? implode(',', $request->service_id) : "";
            $man['user_name'] = $request['user_name'];
            $man['full_name'] = $request['full_name'];
            $man['email'] = $request['email'];
            $man['password'] = Hash::make($request['password']);
            $man['country_code'] = $request['country_code'];
            $man['mobile_number'] = $request['mobile_number'];
            $man['image'] = "";
            if (isset($request['image'])) {
                $files = $request['image'];
                $man['image'] = $this->common->saveImage($files, $this->folder, 'sub_inch_');
            }
            $man['bio'] = $request['bio'] ?? "";
            $man['device_type'] = 0;
            $man['device_token'] = "";
            $man['status'] = 1;
            if ($man->save()) {

                // Send Mail
                $check = $this->common->BasicNotiConfiguration('service-assigned');
                if ($check['status'] == 1 && $check['send_notification'] == 1 && $man['service_id'] != "") {
                    $title = __('label.you’ve_been_assigned_a_new_service');
                    $this->common->save_notification(2, $man->id, 0, $title);
                }

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

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

                $incharge = InCharge_Data();
                $params['service_id'] = explode(',', $params['result']['service_id']);
                $params['service'] = Service::where('department_id', $incharge['department_id'])->orderby('name', 'asc')->get();

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

                return view('incharge.sub_in_charge.edit', $params);
            } else {
                return redirect()->back()->with('error', __('label.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function update($id, Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'user_name' => 'required|min:2|unique:tbl_sub_in_charge,user_name,' . $id,
                'full_name' => 'required|min:2',
                'email' => 'required|email|unique:tbl_sub_in_charge,email,' . $id,
                'country_code' => 'required',
                'mobile_number' => [
                    'required',
                    'numeric',
                    Rule::unique('tbl_sub_in_charge')->where(function ($query) use ($request, $id) {
                        return $query->where('country_code', $request->country_code)
                            ->where('mobile_number', $request->mobile_number)
                            ->where('id', '!=', $id);
                    }),
                ],
                'image' => 'image|mimes:jpeg,png,jpg|max:5120',
            ]);
            if ($validator->fails()) {
                $errs = $validator->errors()->all();
                return response()->json(['status' => 400, 'errors' => $errs]);
            }

            $man = Sub_In_Charge::where('id', $request['id'])->first();

            if (isset($man['id'])) {
                $old_service_id = $man->service_id;

                $man['service_id'] = isset($request->service_id) ? implode(',', $request->service_id) : "";
                $man['user_name'] = $request['user_name'];
                $man['full_name'] = $request['full_name'];
                $man['country_code'] = $request['country_code'];
                $man['mobile_number'] = $request['mobile_number'];
                $man['email'] = $request['email'];
                if ($request['password'] != null && isset($request['password'])) {
                    $man['password'] = Hash::make($request['password']);
                }
                if (isset($request['image'])) {
                    $files = $request['image'];
                    $man['image'] = $this->common->saveImage($files, $this->folder, 'sub_inch_');

                    $this->common->deleteImageToFolder($this->folder, basename($request->old_image));
                }

                if ($man->save()) {

                    if ($request['service_id'] != null && !empty($request['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 = is_array($request['service_id']) ? $request['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, $man->id, 0, $title);
                            } else if (!empty($addedServices)) { // If there are new ones added
                                $this->common->save_notification(2, $man->id, 0, $title);
                            }
                        }
                    }

                    return response()->json(['status' => 200, 'success' => __('label.success_edit_sub_in_charge')]);
                } else {
                    return response()->json(['status' => 400, 'errors' => __('label.error_edit_sub_in_charge')]);
                }
            } 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 = Sub_In_Charge::where('id', $id)->first();
            if (isset($data)) {
                $this->common->deleteImageToFolder($this->folder, $data['image']);
                $data->delete();
            }
            return redirect()->route('insub_incharge.index')->with('success', __('label.sub_in_charge_delete'));
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function show($id)
    {
        try {

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

                $data->status = $data->status === 1 ? 0 : 1;
                $data->save();
                return response()->json(['status' => 200, 'success' => __('label.status_changed'), 'status_code' => $data->status]);
            } else {
                return response()->json(['status' => 400, 'errors' => __('label.data_not_found')]);
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function transfer_sub_incharge(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'service_id' => 'required',
            ]);
            if ($validator->fails()) {
                $errs = $validator->errors()->all();
                return response()->json(array('status' => 400, 'errors' => $errs));
            }

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

                $sub_incharge->service_id = implode(',', $request->service_id);
                $sub_incharge->save();

                // Send Notification
                $check = $this->common->BasicNotiConfiguration('service-assigned');
                if ($check['status'] == 1 && $check['send_notification'] == 1) {
                    $title = __('label.you’ve_been_assigned_a_new_service');
                    $this->common->save_notification(2, $sub_incharge->id, 0, $title);
                }

                return response()->json(array('status' => 200, 'success' => __('label.success_edit_sub_in_charge')));
            } else {
                return response()->json(array('status' => 400, 'errors' => __('label.error_edit_sub_in_charge')));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
}
