<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Admin\Controller;
use App\Libraries\Tabler;
use App\Models\Complaint;
use App\Models\ComplaintMessages;
use App\Models\Patient;
use App\Rules\GeneralText;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ComplaintsController extends Controller
{
    /**
     * List Complaints
     *
     * @param Request $request
     * @return void
     */
    public function index(Request $request)
    {
        $model = new Complaint();
        //$model = $model->with('patients');
        $select = $model->getComplaintsSelect();

        $th = ['complaint_date', 'description', 'is_resolved', 'created_at', 'updated_at'];

        $sortable = ['complaint_date'];
        
        $searchable = ['description', 'is_resolved'];

        $table = new Tabler('admin.complaints', $model, $select, $th, $sortable, $searchable, $request);

        $data = $table->initTable();

        $this->loadView('complaints.index', 'complaints.title', 'complaints', [], $data);
    }
    //-----------------------------------------------------------

    /**
     * Add new complaint
     *
     * @param Request $request
     * @return void
     */
    public function add(Request $request)
    {

        if ($request->getMethod() == 'POST') {

            $min_date = date('Y-m-d', strtotime("-1 week"));
            $max_date = date('Y-m-d');

            $rules = [
                'patient' => ['required', 'exists:patients,id'],
                'description' => ['required', 'max:5000', new GeneralText],
                'complaint-date' => ['required', 'before_or_equal:' . $max_date, 'after_or_equal:' . $min_date],
                'attachment' => ['mimes:png,jpg,jpeg,mp4,m4v', 'min:100', 'max:20480']
            ];

            $validated = $request->validate($rules);

            $complaint = [
                'patient_id' => $validated['patient'],
                'description' => $validated['description'],
                'complaint_date' => date('Y-m-d', strtotime($validated['complaint-date'])),
            ];


            if ($request->file('attachment') && $request->file('attachment')->isValid()) {

                $patient_dir = config('admin.complaints_dir') . '/' . $validated['patient'];

                $file_name = time() . '.' . $request->file('attachment')->guessExtension();

                $request->file('attachment')->storeAs($patient_dir, $file_name);

                $complaint['attachment'] = $file_name;
            }

            Complaint::create($complaint);

            return redirect()->route('admin.complaints')->with('success', __('admin/common.msgs.success.add'));
        }

        $patients_model = new Patient();
        $patient_name = $patients_model->patientFullName();
        $data['patients'] = Patient::select('id', $patient_name)->get();

        $this->loadView('complaints.add', 'complaints.add_title', 'complaints.add', [], $data, ['bs-datepicker/dp-bs-4.min.css'], ['momentjs/moment.min.js', 'bs-datepicker/dp-bs-4.min.js']);
    }
    //-------------------------------------------------------------------------
    /**
     * Complaint info
     *
     * @param Request $request
     * @param Complaint $complaint
     * @return void
     */
    public function info(Request $request, Complaint $complaint)
    {

        // get get patient info
        $data['patient'] = Complaint::find($complaint->id)->patient;

        $data['appointments'] = $data['patient']->appointments;

        $data['complaint'] = $complaint;

        $messages = $complaint->messages;

        $data['complaint_messages'] = '';

        $data['last_message_id'] = 0;

        if ($messages->count() > 0) {

            foreach ($messages as $message) {

                if ($message->user_id == user_id()) {
                    $data['complaint_messages'] .= view('admin.complaints.messages.message_box_right', ['message' => $message]);
                } else {
                    $data['complaint_messages'] .= view('admin.complaints.messages.message_box_left', ['message' => $message]);
                }
            }

            $data['last_message_id'] = ComplaintMessages::where('complaint_id', $complaint->id)->orderBy('id', 'DESC')->first()->id;
        }



        $this->loadView('complaints.info', 'complaints.info_title', 'complaints.info', $complaint, $data);
    }
    //--------------------------------------------------------------------------

    /**
     * Download Complaint attachment
     *
     * @param Request $request
     * @param Complaint $complaint
     * @return void
     */
    public function downloadAttachment(Request $request, Complaint $complaint)
    {

        $path = config('admin.complaints_dir') . '/' . $complaint->patient_id . '/' . $complaint->attachment;

        if (Storage::exists($path)) {

            return Storage::download($path);
        }

        abort(404);
    }
    //-----------------------------------------------------------------------------

    public function sendMessage(Request $request, Complaint $complaint)
    {

        if ( $request->ajax() && $request->getMethod() == 'POST') {
            $str = str_replace('/', '', $request->input('message'));
            $str = str_replace('\\', '', $str);

            $new_message = $new_message = preg_replace('/[\@;!#$%^&*()\"\']+/', '', $str);

            $data['message'] = substr($new_message, 0, 250);
            $data['complaint_id'] = $complaint->id;
            $data['user_id'] = user_id();

            $data['message'] = ComplaintMessages::create($data);

            $view = view('admin.complaints.messages.message_box_right', $data);
            $json = [
                'last_id' => $data['message']->id,
                'message' => (string) $view
            ];


            return response()->json($json);
        }
    }
    //-----------------------------------------------------------------------------

    public function refreshMessageBox(Request $request, int $complaint_id, int $last_msg_id = 0)
    {
        if ( $request->ajax() && $request->getMethod() == 'POST') {

            $messages = ComplaintMessages::where('id', '>', $last_msg_id)->where('complaint_id', $complaint_id)->get();

            $complaint_messages = '';

            $new_last_id = $last_msg_id;

            if ($messages->count() > 0) {

                foreach ($messages as $message) {

                    if ($message->user_id == user_id()) {
                        $complaint_messages .= view('admin.complaints.messages.message_box_right', ['message' => $message]);
                    } else {
                        $complaint_messages .= view('admin.complaints.messages.message_box_left', ['message' => $message]);
                    }
                }

                $new_last_id = ComplaintMessages::where('complaint_id', $complaint_id)->orderBy('id', 'DESC')->first()->id;
            }

            $json = [
                'last_id' => $new_last_id,
                'messages' => $complaint_messages
            ];

            return response()->json($json);
        }
    }
}
