<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Common;
use App\Models\Complaint;
use App\Models\Complaint_Img;
use App\Models\Department;
use App\Models\Hashtag;
use App\Models\In_Charge;
use App\Models\Service;
use App\Models\Sub_In_Charge;
use Illuminate\Http\Request;
use Exception;
use Illuminate\Support\Facades\Validator;

class ComplaintController extends Controller
{
    private $folder = "complaint";
    private $folder_department = "department";
    public $common;
    public function __construct()
    {
        $this->common = new Common;
    }
    // Status:- 1- Awaiting, 2- In Progress, 3-Canceld, 4- Completed
    public function index(Request $request)
    {
        try {
            $input_search = $request['input_search'];

            if ($input_search != null && isset($input_search)) {
                $params['data'] = Department::where('name', 'LIKE', "%{$input_search}%")->orderby('name', 'asc')->paginate(20);
            } else {
                $params['data'] = Department::orderby('name', 'asc')->paginate(20);
            }

            $this->common->imageNameToUrl($params['data'], 'department_icon', $this->folder_department);
            foreach ($params['data'] as $value) {

                $value['total_complete_complaint'] = Complaint::where('department_id', $value['id'])->where('status', 4)->count();
                $value['total_archived_complaint'] = Complaint::where('department_id', $value['id'])->where('status', 3)->count();
                $value['total_in_progress_complaint'] = Complaint::where('department_id', $value['id'])->where('status', 2)->count();
                $value['total_open_complaint'] = Complaint::where('department_id', $value['id'])->where('status', 1)->count();
            }

            return view('admin.complaint.index', $params);
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }

    public function request_index($department_id, Request $request)
    {
        try {

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

            if ($request->ajax()) {

                $input_status = $request['input_status'];
                $input_service = $request['input_service'];
                $input_user = $request['input_user'];
                $input_start_date = $request['input_start_date'];
                $input_end_date = $request['input_end_date'];

                $query = Complaint::where('department_id', $department_id);

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

                if ($input_service != "all") {
                    $query->where('service_id', $input_service);
                }

                if ($input_start_date != null) {
                    $query->whereDate('created_at', '>=', $input_start_date);
                }

                if ($input_end_date != null) {
                    $query->whereDate('created_at', '<=', $input_end_date);
                }

                if ($input_status != "all") {
                    $query->where('status', $input_status);
                }
                $data = $query->with('user', 'service', 'sub_in_charge')->orderBy('id', 'desc')->get();

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

                        $complaint_delete = __('label.delete_request');

                        $delete = '<form onsubmit="return confirm(\'' . $complaint_delete . '\');" method="POST" action="' . route('complaint.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('complaint.details', [$row->id]) . '" class="edit-delete-btn mr-2">';
                        $btn .= '<i class="fa-solid fa-eye fa-xl"></i>';
                        $btn .= '</a>';
                        $btn .= $delete;
                        $btn .= '</div>';
                        return $btn;
                    })
                    ->addColumn('in_charge', function ($row) {

                        $in_charge = In_Charge::where('department_id', $row->department_id)->first();
                        if ($in_charge != null) {

                            return $in_charge->full_name;
                        } else {
                            return '-';
                        }
                    })
                    ->addColumn('start_date', function ($row) {
                        $date = date("Y-m-d", strtotime($row->created_at));
                        return $date;
                    })
                    ->rawColumns(['action'])
                    ->make(true);
            }
            return view('admin.complaint.request_index', $params);
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function destroy($id)
    {
        try {

            $complaint =  Complaint::where('id', $id)->first();
            $content = Complaint_Img::where('complaint_id', $id)->get();
            foreach ($content as $value) {
                $this->common->deleteImageToFolder($this->folder, $value['content_url']);
                $value->delete();
            }
            $complaint->delete();

            return redirect()->route('complaint.request_index', $complaint->department_id)->with('success', __('label.request_delete'));
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    // complaint Details
    public function complaintDetails($complaint_id, Request $request)
    {
        try {

            $params['data'] = [];
            $params['complaint_id'] = $complaint_id;

            $params['complaint'] = Complaint::where('id', $complaint_id)->with('user', 'department', 'service')->orderby('id', 'desc')->first();
            if (isset($params['complaint']['id'])) {

                $params['sub_in_charge'] = [];
                $sub_incharge = Sub_In_Charge::where('department_id', $params['complaint']['department_id'])->whereRaw("FIND_IN_SET(?, service_id)", [$params['complaint']['service_id']])->where('status', 1)->orderby('full_name', 'asc')->get();
                if (count($sub_incharge) > 0) {

                    foreach ($sub_incharge as $value) {

                        $service_id = explode(',', $value['service_id']);
                        if (in_array($params['complaint']['service_id'], $service_id)) {
                            $params['sub_in_charge'][] = $value;
                        }
                    }
                }
                $params['image_before'] = Complaint_Img::where('complaint_id', $complaint_id)->where('type', 1)->where('content_type', '!=', 3)->get();
                $params['image_after'] = Complaint_Img::where('complaint_id', $complaint_id)->where('type', 2)->where('content_type',  '!=', 3)->get();

                $this->common->imageNameToUrl($params['image_before'], 'content_url', $this->folder);
                $this->common->imageNameToUrl($params['image_before'], 'thumbnail_image', $this->folder);
                $this->common->imageNameToUrl($params['image_after'], 'content_url', $this->folder);
                $this->common->imageNameToUrl($params['image_after'], 'thumbnail_image', $this->folder);

                $ids = explode(',', $params['complaint']['hashtag_id']);
                $hashtags = Hashtag::whereIn('id', $ids)->get();
                $hashtagString = '';
                foreach ($hashtags as $hashtag) {
                    $hashtagString .= '#' . $hashtag->name;
                }
                $params['complaint']['hashtag'] = $hashtagString;

                return view('admin.complaint.details', $params);
            } else {
                return redirect()->back()->with('error', __('label.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function complaintDetailsUpdate(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'status' => 'required',
            ]);
            if ($request['status'] == 4) {
                $validator = Validator::make($request->all(), [
                    'request_reply' => 'required',
                ]);
            }
            if ($validator->fails()) {
                $errs = $validator->errors()->all();
                return response()->json(['status' => 400, 'errors' => $errs]);
            }

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

                $complaint['status'] = $request['status'];
                if ($complaint->sub_in_charge_id == 0 && $request['sub_in_charge_id'] != null) {

                    $sub_incharge = Sub_In_Charge::where('id', $request['sub_in_charge_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);
                    }
                }
                $complaint['sub_in_charge_id'] = $request['sub_in_charge_id'] ?? 0;
                $complaint['complaint_reply'] = $request['request_reply'] ?? "";

                if ($request['old_hashtag_id'] != null) {
                    $old_hashtag = explode(',', $request['old_hashtag_id']);
                    Hashtag::whereIn('id', $old_hashtag)->decrement('total_used', 1);
                }
                $hashtag_id = $this->common->checkHashTag($request['hashtag']);
                $hashtagId = "";
                if (count($hashtag_id) > 0) {
                    $hashtagId = implode(',', $hashtag_id);
                }
                $complaint['hashtag_id'] = $hashtagId;


                if ($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 response()->json(['status' => 200, 'success' => __('label.success_edit_request_status')]);
                } else {
                    return response()->json(['status' => 400, 'errors' => __('label.success_edit_request_status')]);
                }
            } else {
                return response()->json(['status' => 400, 'errors' => __('label.success_edit_request_status')]);
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function complaint_after_image(Request $request)
    {
        try {
            $arr_img = $request->file('image');
            $complaint_id = $request['complaint_id'];

            foreach ($arr_img as $value) {

                if (!empty($value)) {

                    $insert = new Complaint_Img();
                    $insert->complaint_id = $complaint_id;
                    $insert->type = 2;
                    $insert->content_type = 1;
                    $insert->content_url = $this->common->saveImage($value, $this->folder, 'complaint_');
                    $insert->thumbnail_image = "";
                    $insert->save();
                }
            }
            return response()->json(['status' => 200, 'success' => __('label.request_image_update_successfully')]);
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
}
