<?php

namespace App\Http\Controllers\Physician;

use Illuminate\Http\Request;
use App\Models\CheifComplainTypes;
use App\Models\Clinics;
use App\Models\Roles;
use App\Models\FormEnteries;
use App\Models\Questions;
use App\Models\QuestionBranchingLogic;
use App\Models\QuestionOptions;
use App\Models\QuestionCategories;
use App\Models\ImageMapping;
use DateTime;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use Auth;
use App\User;
use App\Helpers\CommonHelper;
use Illuminate\Support\Facades\Config;
use DB;
use Validator;
use Session;
use App\Models\PendingQuestions;

class PhysicianController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable 
     */
    public function index()
    {   
        return view('physician.crud.form');
    }

    public function change_password()
    {   
        return view('physician.crud.change_password');
    }

    public function profile()
    {   
        return view('physician.crud.profile');
    }

    public function editPhysician(Request $request)
    {
        $user = Auth::user();
        $data['roleData']           = Roles::get();
        $data['clinicsData']        = Clinics::select('title','id')->get();
        $data['selectedRoles']      = array();
        $data['selected_clinic']    = array();
        $data['id']                 = $user->id;
        $data['userData']           = user::find($user->id);
        $data['selected_clinic_data'] = "";
        
        if ($user->id) 
        {
            $data['selectedRoles']      = $data['userData']->roles->pluck('id');
            foreach ($data['selectedRoles'] as $value) 
            {
                 $data['selectedRoleId'] =   $value;
            }
            if (!empty($data['userData']->clinic_id))
            {
                $data['selected_clinic'] = clinics::select('title','id')->where('id', $data['userData']->clinic_id)->get();
                foreach ($data['selected_clinic'] as  $value) 
                {
                  $data['selected_clinic_data'] = $value;
                }
            }
            if ($data['userData']->picture) 
            {
                $data['userData']->picture = CommonHelper::getImageFolderUrlForComplainType($data['userData']->picture);
            }
            else
            {
                $data['userData']->picture = "";
            }
        }
        else 
        {
            $data['selectedRoleId'] =   "";
        }
        if($request->input('btn-submit'))
        {   

            //  $emailExist = "1";
            // $sameNameEmail = "";
            // if ($request->input('email')) 
            // {
            //     $userEmail = $request->input('email');
            //     $oldUserEmailRetrieveFromDb           = user::select('email')->where('email',$userEmail)->where('id','<>',$data['id'])->first();
            //     if ($oldUserEmailRetrieveFromDb) 
            //     {
            //        $emailExist = "";
            //        $sameNameEmail = $oldUserEmailRetrieveFromDb->email;
            //     }
            //     else
            //     {
            //        $emailExist = "1";
            //        $sameNameEmail = "";
            //     }
            // }



            $rules = array('name' => 'required','first_name' => 'required','last_name' => 'required',
                           'office_phone' => 'required','mobile_no' => 'required'
                            );
           
            $messages['name.required']                =  'Name is required';
            $messages['first_name.required']          =  'First Name is required';
            $messages['last_name.required']           =  'Last Name is required';
            // $messages['email.required']               =  'Email is required';
            // $messages['email.email']                  =  'Please provide valid Email';
            // $messages['emailExist.required']          =  'This Email is already exist please choose another one';
            $messages['office_phone.required']        =  'Office Phone is required';
            $messages['mobile_no.required']           =  'Mobile No is required';
                    
            $request_all =  $request->all();
            // $request_all['emailExist'] = $emailExist;
            $validator = Validator::make($request_all, $rules,$messages);
            if ($validator->fails()) 
            {   
                return redirect(route('physician_edit'))->withErrors($validator)->withInput();
            }

            $data['name']                             = $request->input('name');
            $data['email']                            = $request->input('userEmail');
            $data['first_name']                       = $request->input('first_name');
            $data['last_name']                        = $request->input('last_name');
            $data['office_phone']                     = $request->input('office_phone');
            $data['extension']                        = $request->input('extension');
            $data['mobile_no']                        = $request->input('mobile_no');
            // $picture                                  = $request->file('picture');
            // $clinic_id                                = asset(config('constants.CHIEF_COMPLAINTS_IMAGE').$request->file('picture'));
            $clinic_id                                = $request->input('clinic');
            $roleId                                   = $request->input('roles');
            $data['id']                               = $request->input('userId');
            // $data['email']                            = $request->input('email');
            // $data['password']                         = bcrypt($request->get('password'));
            $userRoles                                = array(); 
            if($request->file('picture')) 
            {
                $fileName = $_FILES['picture']['name'];
                $image = $request->file('picture'); 
                $image->move(config('constants.CHIEF_COMPLAINTS_IMAGE'), $image->getClientOriginalName());   
                $userImageUrlPath = $fileName;
                $data['picture']  = $userImageUrlPath;
            }  
            else
            {
                $filePath = pathinfo($request->input('oldPicture'));
                $data['picture']  = $filePath['basename'];
            }

            $user = User::updateOrCreate(
                ['id' => $data['id']],
                $data
            );
            return redirect(route('physician_edit'))->with('success', 'Your Profile edited Successfully!');

        }
       
        return view('physician.crud.profile',$data);
    }

    // // Pending Question Listing
    public function pendingQuestions()
    {   
        return view('physician.questions.pending_question');
    }
    // Pending Question Listing Ajax
    public function pendingQuestionAjax(Request $request)
    {
        $_getParams             = $_GET;
        $params                 = CommonHelper::_processDataTableRequest($_getParams);
        
        $draw                   = $params['draw'];      
        $offset                 = $params['offset'];
        $status                 = @$_GET['status'];
        $searchKeyword          = @$_GET['search_keyword'];
        $sortColumn             = $params['sort_column'];
        $sortOrderDirection     = $params['sort_direction'];
        $recordsPerPage         = $params['records_per_page'];
        $objQuestions               =  new PendingQuestions();

        $recordsTotal           = $objQuestions->count();
        $recordsFiltered        = $recordsTotal;
        if($searchKeyword)
        {           
            $objUsers = $objUsers->where(function($query) use ($searchKeyword) 
            {
                $query->orWhere('title', 'like', '%'.$searchKeyword.'%');
                
            });
        }
       
        $objQuestions       = $objQuestions->offset($offset)->limit($recordsPerPage);
     
        $recordsFiltered    = $objQuestions->count();
        $objQuestions       = $objQuestions->orderby('id', 'ASC')->get();

        // dd($recordsFiltered);die;         
        $listData = array(); 
        foreach ($objQuestions as $key => $row) 
        {           
            $deletePath = route('chief_complains_delete', $row->id);
            $editPath   = route('chief_complains_save', $row->id);

//             $tplActions  = <<<EOT
//             <a title="View" class="la la-eye" href="$editPath" value="edit" style="margin:5px;><i class="" aria-hidden="true"></i></a>
//             <small><a title="$statusText" class="$statusIcon" onclick="return confirm('Are you sure want to change the status of this record?')" href="$deletePath"><i class="" aria-hidden="true"></i></a></small>
            
// EOT;
            //View Question Hide ----->  <br /><br /><small><a title="View Questions" class="" href="$viewQuestionsPath" style="font-size:10px;">View Questions</a></small>
            $tempArray      = array();
            $surgeon        = User::find($row->surgeon_id); 

            $complain       = CheifComplainTypes::find($row->complain_id); 
            $category       = QuestionCategories::find($row->category_id); 

            $tempArray[]    = $surgeon->first_name." ".$surgeon->last_name;
            $tempArray[]    = $complain->name;
            $tempArray[]    = $category->title;
            $tempArray[]    = $row->title;
            $tempArray[]    = $row->response;
            $listData[]     = $tempArray;
        }
        $data = array(
            "draw"            => $draw,
            "recordsTotal"    => $recordsTotal,
            "recordsFiltered" => $recordsFiltered,
            "data"            => $listData
        );
        
        return response()->json($data);
    }

    // CHEIF COMPLAINS LISTING
     public function chiefComplaintsListing()
    {   
        return view('physician.chief-complaints.listing');
    }

    //  CREATE DATATABLE FOR CHEIF COMPLAINS
    public function chiefComplaintsAjax(Request $request)
    {
        $_getParams             = $_GET;
        $params                 = CommonHelper::_processDataTableRequest($_getParams);
        
        $draw                   = $params['draw'];      
        $offset                 = $params['offset'];
        $status                 = @$_GET['status'];
        $searchKeyword          = @$_GET['search_keyword'];
        $sortColumn             = $params['sort_column'];
        $sortOrderDirection     = $params['sort_direction'];
        $recordsPerPage         = $params['records_per_page'];
        $objUsers               =  new CheifComplainTypes();

        $recordsTotal           = $objUsers->count();
        $recordsFiltered        = $recordsTotal;
        if($searchKeyword)
        {           
            $objUsers = $objUsers->where(function($query) use ($searchKeyword) 
            {
                $query->orWhere('name', 'like', '%'.$searchKeyword.'%');
                
            });
        }
         if($status!='')
        {   
            $objUsers = $objUsers->where('status', $status)->offset($offset)->limit($recordsPerPage);
        }
        $objUsers = $objUsers->offset($offset)->limit($recordsPerPage);
     
        $recordsFiltered = $objUsers->count();
        $objUsers         = $objUsers->orderby('sort_order', 'ASC')->get();

        // dd($recordsFiltered);die;         
        $listData = array(); 
        foreach ($objUsers as $key => $row) 
        {           
            $deletePath = route('chief_complains_delete', $row->id);
            $editPath   = route('chief_complains_save', $row->id);

            $viewQuestionsPath   = route('chief_complains_questions_tree', $row->id);

            // $viewQuestionsPath=$editPath;

            // ACTIVE AND INACTIVE COMPLAIN TYPES
            $statusIcon = "ti-close";
            $statusText = "Inactive Now";
            $status = 'Active';
            if($row->status==config('constants.CONSTANT_STATUS_INACTIVE'))
            {   
                $statusIcon = "ti-check";
                $status = 'Inactive';
                $statusText = "Active Now";
            }
            $tplActions  = <<<EOT
            <a title="Edit" class="la la-pencil" href="$editPath" value="edit" style="margin:5px;><i class="" aria-hidden="true"></i></a>
            <small><a title="$statusText" class="$statusIcon" onclick="return confirm('Are you sure want to change the status of this record?')" href="$deletePath"><i class="" aria-hidden="true"></i></a></small>
            
EOT;
            //View Question Hide ----->  <br /><br /><small><a title="View Questions" class="" href="$viewQuestionsPath" style="font-size:10px;">View Questions</a></small>
            $tempArray  = array();
            $roles      = array();
            // $userRoles  = $row->load('roles');
            // foreach ($userRoles->roles as $key => $value) {
            //    $roles[] = $value->name;
            // }
            if ($row->status == config('constants.CONSTANT_STATUS_INACTIVE')) 
            {
                $status = "Inactive";
            }
            else
            {
                $status = "Active";
            }
            $imageMapping = ImageMapping::where('complain_type_id',$row->id)->first();
            $imageArr = array();
            if ($row->image_front) 
            {
                $imageArr = explode('.', $row->image_front);
                $frontType = $imageArr[0];
            }
            if ($row->image_back) 
            {
                $imageArr = explode('.', $row->image_back);
                $backType = $imageArr[0];
            }
            $tempArray[]    = $row->name;
            // dd($row->image_front)
            // $tempArray[]    = '<img src="'.CommonHelper::getImageFolderUrlForComplainType($row->image_front).'"> 
            //                     <br> <a href="'.route('image_map',$row->id .'/'. 'front').'"> Front Edit</a>';
            $tempArray[]    = '<img src="'.CommonHelper::getImageFolderUrlForComplainType($row->image_front).'">';
            
            // $tempArray[]    = '<img src="'.CommonHelper::getImageFolderUrlForComplainType($row->image_back).'"> 
            //                     <br> <a href="'.route('image_map', $row->id .'/'. 'back').'"> Back Edit</a>';
            $tempArray[]    = '<img src="'.CommonHelper::getImageFolderUrlForComplainType($row->image_back).'"> ';
            $tempArray[]    = $row->sort_order;
            $tempArray[]    = $status;
            $tempArray[]    = $tplActions;
            $listData[]     = $tempArray;
        }
        $data = array(
            "draw"            => $draw,
            "recordsTotal"    => $recordsTotal,
            "recordsFiltered" => $recordsFiltered,
            "data"            => $listData
        );
        
        return response()->json($data);
    }

    public function saveChiefComplaints(Request $request, $id = false)
    {
         $data = array();        
         $data['heading'] = "Add New Chief Complain";
         $complainTypeId  = $request->input('chiefComplaintsId');
         $CheifComplainsOrder = CheifComplainTypes::select('sort_order')->get();
         if (!$CheifComplainsOrder->isEmpty()) 
         {
              foreach ($CheifComplainsOrder as  $value) 
                {
                  $question_order[] =  $value->sort_order;
                }
                $CheifComplainsHighestSort = max($question_order);
                $CheifComplainsHighestSort ++ ;
                $CheifComplainsSortorder = $CheifComplainsHighestSort;
                // dd($question_order );
                $data['suggestedSortOrder'] = $CheifComplainsSortorder;
         }
         else
         {
            $data['suggestedSortOrder'] = 1;
         }
        if ($id) 
            {
                $data['chiefComplaints'] = CheifComplainTypes::find($id);
                // $data['image_front'] = CommonHelper::getImageFolderUrlForComplainType($data['chiefComplaints']->image_front);
                // $data['image_back'] = CommonHelper::getImageFolderUrlForComplainType($data['chiefComplaints']->image_back);

                $data['heading'] = "Edit Chief Complain";
              if ($data['chiefComplaints']->image_front) 
              {
                $data['image_front'] = CommonHelper::getImageFolderUrlForComplainType($data['chiefComplaints']->image_front);
              }

               if ($data['chiefComplaints']->image_back) 
              {
                $data['image_back'] = CommonHelper::getImageFolderUrlForComplainType($data['chiefComplaints']->image_back);
              }
            }
        else 
            {
              $data['image_front'] = "";
              $data['image_back'] = "";
            }

       if ($request->input('btn-submit')) 
       {
            $currentchiefComplainsId = $request->input('chiefComplaintsId');
            $chiefComplainsOrder = $request->input('sort_order');
            $chiefComplainsName = $request->input('name');
            $CheifComplainsSortorder = $request->input('suggestedSort_order');
            $currentChiefComplainsSortOrders = CheifComplainTypes::select('sort_order')->where('sort_order',$chiefComplainsOrder)->where('id','<>',$currentchiefComplainsId)->first();
            $sameNameChiefComplain = CheifComplainTypes::select('name')->where('name',$chiefComplainsName)->where('id','<>',$currentchiefComplainsId)->first();
            // dd($currentChiefComplainsSortOrders);
            $chiefComplainExist = "1";  
            if ($sameNameChiefComplain == NULL) 
                {
                    $chiefComplainExist = "1";

                    $sameNameChiefComplain = "";
                }
            else
            {

                $sameNameChiefComplain = $sameNameChiefComplain->name;
                $chiefComplainExist = "";
            }
            if ($currentChiefComplainsSortOrders == NULL) 
                {
                    $sortOrderExist = "1";
                    $sortOrderExistInDb = "";
                    $CheifComplainsSortorder = "";

                }
            else
            {
                $sortOrderExist = "";
                $sortOrderExistInDb = $currentChiefComplainsSortOrders->sort_order;
                $CheifComplainsSortorder++;
            }
            if($request->input('sort_order'))
            {
                $sortOrderValidation = $request->input('sort_order');
            }
            else
            {
                $sortOrderValidation = "";
            }
            if ($currentchiefComplainsId == NULL) 
            {
                $CheifComplainsOrder = CheifComplainTypes::select('sort_order')->get();
                 if (!$CheifComplainsOrder->isEmpty()) 
                 {
                      foreach ($CheifComplainsOrder as  $value) 
                        {
                          $question_order[] =  $value->sort_order;
                        }
                        $CheifComplainsHighestSort = max($question_order);
                        $CheifComplainsHighestSort ++ ;
                        $CheifComplainsSortorder = $CheifComplainsHighestSort;
                        // dd($question_order );
                        // $data['suggestedSortOrder'] = $CheifComplainsSortorder;
                 }
            }
            if ($currentchiefComplainsId) 
            {
                $CheifComplainsOrder = CheifComplainTypes::select('sort_order')->get();
                 if (!$CheifComplainsOrder->isEmpty()) 
                 {
                      foreach ($CheifComplainsOrder as  $value) 
                        {
                          $question_order[] =  $value->sort_order;
                        }
                        $CheifComplainsHighestSort = max($question_order);
                        $CheifComplainsHighestSort ++ ;
                        $CheifComplainsSortorder = $CheifComplainsHighestSort;
                        // dd($question_order );
                        // $data['suggestedSortOrder'] = $CheifComplainsSortorder;
                 }
            }
            $rules = array('name' => 'required', 'sort_order' => 'required|numeric|min:1','sortOrderExist' => 'required',
                'chiefComplainExist' => 'required','sortOrderValidation' => 'required');
            $messages['name.required']            =  'Name is required';
            $messages['question_order.required']   =  'Question is Order required';
            $messages['sort_order.numeric']   =  'Question Order must be a numeric value';
            $messages['sortOrderValidation.required']   =  'Sort Order is required';
            $messages['chiefComplainExist.required']   =  'The Title "'.$sameNameChiefComplain.'" is already used as a title';
            $messages['sortOrderExist.required']   =  'Chief Complain is already exists for sort order "'.$sortOrderExistInDb.'". It should be "'.$CheifComplainsSortorder.'"';

           
            $data['chiefComplaintsId'] = $request->input('chiefComplaintsId');
            $data['name']       = $request->input('name');
            $data['sort_order'] = $request->input('sort_order');

            if ($request->input('old_front_image') || $request->input('old_back_image')) 
            {
                if ($request->input('name')) 
                {
                    $rules = array('name' => 'required|max:255','chiefComplainExist' => 'required');
                    $messages['name.required']   =  'Title is required';
                    $messages['chiefComplainExist.required']   =  'The Title "'.$sameNameChiefComplain.'" is already used as a title';
                    $request_all = $request->all();
                    $request_all['chiefComplainExist'] = $chiefComplainExist;
                    $validator = Validator::make($request_all, $rules,$messages);

                    if ($validator->fails()) 
                    {   
                        $favIconName = $_FILES['image_front']['name'];
                        return redirect(route('chief_complains_save',$data['chiefComplaintsId']))->withErrors($validator)->withInput();
                    }

                    $data['name']       = $request->input('name');
                }

                if($request->file('image_front')) 
                    {
                        $rules = array('name' => 'required|max:255','image_front' => 'required|image|mimes:jpg,png,jpeg|max:2048'
                                        );

                        // $messages['name.required']            =  'Name is required';
                        $messages['image_front.required']         =  'Front Image is required';
                        $messages['image_front.mimes']            =  'Invalid type of front image file.';
                        // $messages['sortOrderExist.required']   =  'Chief Complain is already exists for sort order "'.$sortOrderExistInDb.'". It should be "'.$CheifComplainsSortorder.'"';
                        $validator = Validator::make($request->all(), $rules,$messages);
                        if ($validator->fails()) 
                        {   
                            $favIconName = $_FILES['image_front']['name'];
                            return redirect(route('chief_complains_save',$data['chiefComplaintsId']))->withErrors($validator)->withInput();
                        }

                        $fileName = $_FILES['image_front']['name'];
                        $image = $request->file('image_front'); 
                        $image->move(config('constants.CHIEF_COMPLAINTS_IMAGE'), $image->getClientOriginalName());   
                        $userImageUrlPath = $fileName;
                        $data['image_front']  = $userImageUrlPath;
                    }
                else
                    {
                        $data['image_front']  = $request->input('old_front_image');
                    }

                if($request->file('image_back')) 
                    {
                        $rules = array('name' => 'required','image_back' => 'required|image|mimes:jpg,png,jpeg|max:2048'
                                        );
                        // $messages['name.required']            =  'Name is required';
                        $messages['image_back.required']         =  'Back Image is required';
                        $messages['image_back.mimes']             =  'Invalid type of back image file.';
                        // $messages['sortOrderExist.required']   =  'Chief Complain is already exists for sort order "'.$sortOrderExistInDb.'". It should be "'.$CheifComplainsSortorder.'"';
                        $validator = Validator::make($request->all(), $rules,$messages);
                        if ($validator->fails()) 
                        {   
                            $logoName = $_FILES['image_back']['name'];
                            return redirect(route('chief_complains_save',$data['chiefComplaintsId']))->withErrors($validator)->withInput();
                        }

                        $fileName = $_FILES['image_back']['name'];
                        $image = $request->file('image_back'); 
                        $image->move(config('constants.CHIEF_COMPLAINTS_IMAGE'), $image->getClientOriginalName());   
                        $userImageUrlPath = $fileName;
                        $data['image_back']  = $userImageUrlPath;
                    }
                else
                    {
                        $data['image_back']  = $request->input('old_back_image');
                    }

                if ($request->input('sort_order')) 
                {
                    $rules = array('sortOrderExist' => 'required');
                    $messages['sortOrderExist.required']   =  'Chief Complain is already exists for sort order "'.$sortOrderExistInDb.'". It should be "'.$CheifComplainsSortorder.'"';
                    $request_all = $request->all();
                    $request_all['sortOrderExist'] = $sortOrderExist;
                    $validator = Validator::make($request_all, $rules,$messages);
                    if ($validator->fails()) 
                    {   
                        return redirect(route('chief_complains_save',$data['chiefComplaintsId']))->withErrors($validator)->withInput();
                    }
                }     
            }

            else
            {
                if ($request->input('name')) 
                {
                    $rules = array('name' => 'required|max:255','chiefComplainExist' => 'required',
                                    'image_front' => 'required|image|mimes:jpg,png,jpeg|max:2048',
                                    'image_back' => 'required|image|mimes:jpg,png,jpeg|max:2048');
                    $messages['chiefComplainExist.required']   =  'The Title "'.$sameNameChiefComplain.'" is already used as a title';
                    $messages['image_front.required']   =  'Front Image is required';
                    $messages['image_back.required']   =  'Back Image is required';
                    $request_all = $request->all();

                    $request_all['chiefComplainExist'] = $chiefComplainExist;

                    $validator = Validator::make($request_all, $rules,$messages);
                    if ($validator->fails()) 
                    {   
                        $favIconName = $_FILES['image_front']['name'];
                        return redirect(route('chief_complains_save',$data['chiefComplaintsId']))->withErrors($validator)->withInput();
                    }
                    $data['name']       = $request->input('name');
                }

                if(empty($request->file('image_front') &&  $request->file('image_back')))
                    {
                        $rules = array('name' => 'required',
                                    'image_front' => 'required|image|mimes:jpg,png,jpeg|max:2048',
                                    'image_back' => 'required|image|mimes:jpg,png,jpeg|max:2048',
                                    'sort_order' => 'required'
                                    );
                        $messages['name.required']            =  'Name is required';
                        $messages['image_front.required']         =  'Front Image is required';
                        $messages['image_front.mimes']            =  'Invalid type of front image file.';
                        $messages['image_back.required']         =  'Back Image is required';
                        $messages['sort_order.required']             =  'Sort Order is required.';
                        // $messages['sortOrderExist.required']   =  'Chief Complain is already exists for sort order "'.$sortOrderExistInDb.'". It should be "'.$CheifComplainsSortorder.'"';
                        $validator = Validator::make($request->all(), $rules,$messages);
                        if ($validator->fails()) 
                        {   
                            return redirect(route('chief_complains_save',$data['chiefComplaintsId']))->withErrors($validator)->withInput();
                        }
                    }
                    if($request->file('image_front') &&  $request->file('image_back'))
                    {
                        $rules = array('name' => 'required',
                                    'image_front' => 'required|image|mimes:jpg,png,jpeg|max:2048',
                                    'image_back' => 'required|image|mimes:jpg,png,jpeg|max:2048',
                                    'sort_order' => 'required'
                                    );
                        $messages['name.required']            =  'Name is required';
                        $messages['image_front.required']         =  'Front Image is required';
                        $messages['image_front.mimes']            =  'Invalid type of front image file';
                        $messages['image_back.required']         =  'Back Image is required';
                        $messages['image_back.mimes']         =  'Invalid type of Back Image file';
                        $messages['sort_order.required']             =  'Sort Order is required.';
                        // $messages['sortOrderExist.required']   =  'Chief Complain is already exists for sort order "'.$sortOrderExistInDb.'". It should be "'.$CheifComplainsSortorder.'"';
                        $validator = Validator::make($request->all(), $rules,$messages);
                        if ($validator->fails()) 
                        {   
                            return redirect(route('chief_complains_save',$data['chiefComplaintsId']))->withErrors($validator)->withInput();
                        }
                    }
                 if($request->file('image_front') || $request->file('image_front')== NULL) 
                    {
                        $rules = array('name' => 'required',
                                 'image_front' => 'required|image|mimes:jpg,png,jpeg|max:2048'
                                 );
                        $messages['name.required']            =  'Name is required';
                        $messages['image_front.required']         =  'Front Image is required';
                        $messages['image_front.mimes']            =  'Invalid type of front image file.';
                        // $messages['sortOrderExist.required']   =  'Chief Complain is already exists for sort order "'.$sortOrderExistInDb.'". It should be "'.$CheifComplainsSortorder.'"';
                        $validator = Validator::make($request->all(), $rules,$messages);
                        if ($validator->fails()) 
                        {   
                            return redirect(route('chief_complains_save',$data['chiefComplaintsId']))->withErrors($validator)->withInput();
                        }
                        $fileName = $_FILES['image_front']['name'];
                        $image = $request->file('image_front'); 
                        $image->move(config('constants.CHIEF_COMPLAINTS_IMAGE'), $image->getClientOriginalName());   
                        $userImageUrlPath = $fileName;
                        $data['image_front']  = $userImageUrlPath;
                    }

                if($request->file('image_back') || $request->file('image_back')== NULL) 
                    {
                        $rules = array('name' => 'required',
                             'image_back' => 'required|image|mimes:jpg,png,jpeg|max:2048'
                             );
                        $messages['name.required']            =  'Name is required';
                        $messages['image_back.required']         =  'Back Image is required';
                        $messages['image_back.mimes']             =  'Invalid type of back image file.';
                        // $messages['sortOrderExist.required']   =  'Chief Complain is already exists for sort order "'.$sortOrderExistInDb.'". It should be "'.$CheifComplainsSortorder.'"';
                        $validator = Validator::make($request->all(), $rules,$messages);
                        if ($validator->fails()) 
                        {   
                            return redirect(route('chief_complains_save',$data['chiefComplaintsId']))->withErrors($validator)->withInput();
                        }
                        $fileName = $_FILES['image_back']['name'];
                        $image = $request->file('image_back'); 
                        $image->move(config('constants.CHIEF_COMPLAINTS_IMAGE'), $image->getClientOriginalName());   
                        $userImageUrlPath = $fileName;
                        $data['image_back']  = $userImageUrlPath;
                    }
                if ($request->input('sort_order')) 
                    {
                        $rules = array('sortOrderExist' => 'required');
                        $messages['sortOrderExist.required']   =  'Chief Complain is already exists for sort order "'.$sortOrderExistInDb.'". It should be "'.$CheifComplainsSortorder.'"';
                        $request_all = $request->all();
                        $request_all['sortOrderExist'] = $sortOrderExist;
                        $validator = Validator::make($request_all, $rules,$messages);
                        if ($validator->fails()) 
                        {   
                            return redirect(route('chief_complains_save',$data['chiefComplaintsId']))->withErrors($validator)->withInput();
                        }
                        $data['sort_order'] = $request->input('sort_order');
                    } 
                   
            }
            
            CheifComplainTypes::updateOrCreate(
                ['id' => $data['chiefComplaintsId']],
                $data
            );


            if ($data['chiefComplaintsId']) 
            {
                $message = 'Chief Complaint edited Successfully! ';
            }
            else 
            {
                $message = 'Chief Complaint added Successfully! ';
            }
            return redirect(route('chief_complains_listing'))->with('success', $message);

       }
      
        return view('physician.chief-complaints.form', $data);

    }

     public function deleteChiefComplains($id)
    {
        if($id)
        {   
            $CheifComplainData   = CheifComplainTypes::find($id);
            if(!$CheifComplainData)
            {
                // Redirect to base
                return redirect(route('admin_users_listing'));
            }
            if(config('constants.CONSTANT_STATUS_INACTIVE')==$CheifComplainData->status)
            {
                $status = "active";
                $CheifComplainData->status = config('constants.CONSTANT_STATUS_ACTIVE');
            }
            else
            {
                $status = "inactive";
                $CheifComplainData->status = config('constants.CONSTANT_STATUS_INACTIVE');
            }
            // if(!$CheifComplainData)
            // {
            //     // Redirect to base
            //     return redirect(route('admin_users_listing'));
            // }
            $CheifComplainData->save();
            // $CheifComplainData->where('id', $id)->delete();
            return redirect()->back()->with('success', 'Cheif Complain has been '.$status.' successfully!');
            return redirect(route('admin_users_listing'));
        }
    }

    //ADD AND EDIT PHYSICIAN 

    public function questionOptionsList(Request $request)
    {   
        $optionData  = array();
        if ($request->input('question_id')) 
        {
            $optionData   = QuestionOptions::where('question_id',$request->input('question_id'))->orderby('sort_order')->get()->toArray();
        }
        echo json_encode(['data'=>$optionData]);die;
    }

     public function complainTypeList(Request $request)
    {   
        $optionData  = array();
        if ($request->input('complain_type_id')) 
        {
            $optionData   = Questions::where('status',config('constants.CONSTANT_STATUS_ACTIVE'))->where('complain_type_id',$request->input('complain_type_id'))->orderby('sort_order')->get()->toArray();
        }

        echo json_encode(['data'=>$optionData]);die;
    }

    public function saveQuestions(Request $request , $id = 0)
    {
        $parentQuestionId = $request->input('parent_question_id');
        $questionoptionId = $request->input('question_option_id');
        $parentArray = array();
        if (!empty($parentQuestionId)) 
        {
            foreach ($parentQuestionId  as $key => $row1) 
            {
                if (!empty($row1)) 
                {
                    $parentArray[$key]['parentId'] =  $row1;
                }
            }
        }
        if (!empty($questionoptionId)) 
        {
            foreach ($questionoptionId  as $key => $row2) 
            {
                if (!empty($row2)) 
                {
                    $parentArray[$key]['parentOptionsId'] =  $row2;
                }
            }
        }
      

        // $data = Session::get('questionoptionId');
       
        $duplicateQuestions = Questions::where('duplicate_form_id', $id);
        $duplicateQuestionsCount = $duplicateQuestions->count();
      // $data = new Questions();
        $heading = "Add New Question";
        $questions          = new Questions();
        $questionData       = Questions::All();
        $questionsArray= "";
        $QuestionBranchingLogics = 0;
        $parentQuestionOptions  = "";
        $parent_question_id = 0;
        $route = route('save_question');


        if ($id) 
        {   
            $heading = "Edit Question";
            $questions = Questions::find($id);

            $QuestionBranchingLogics= array();
            $QuestionBranchingLogics = QuestionBranchingLogic::where('question_id',$id)->get()->toArray();
            //dd($QuestionBranchingLogics);
            // dd($QuestionBranchingLogics[0]['question_id']);
            /*
            if($questions->question_category)
            {
                echo $questions->question_category->title;
                exit; 
            }*/

            $parent_question_id = $questions->parent_question_id;

            $questionsArray= array();
            $questionsArray = Questions::where('status',config('constants.CONSTANT_STATUS_ACTIVE'))->where('complain_type_id',$questions->complain_type_id)->where('id', '!=', $id)->get()->toArray();

            if(empty($questions))
            {
                return redirect(route('questions_listing'));
            }
            $route = route('save_question',$id);
        }

        if ($request->input('btn-submit')) 
        {   
            // dd($parent_question_id);
            // dd($request);
            // dd($request->input('old_questions_opt_id'));
            //dd($request);
            // validation here
            $questionId   = $request->input('questionId');
            $questionName   = $request->input('name');
            $complainTypeId   = $request->input('complain_type_id');

            $parentQuestionId = $request->input('parent_question_id');
            $questionoptionId = $request->input('question_option_id');




            $selectedParentQuestion  = Questions::select('name')->where('parent_question_id',$parent_question_id)->first();
            //$parentQuestionExist  = Questions::select('name')->where('complain_type_id',$complainTypeId)->first();

            $mostParentQuestionForComplainType = Questions::where('complain_type_id', $complainTypeId)
                                                          ->where('parent_question_id', 0)
                                                          ->where('question_option_id', 0)
                                                          ->first();

            $haveRootQuestionForComplainType = 0;
            $mostParentQuestionIdForComplainType = 0;

            if($mostParentQuestionForComplainType)
            {
                $mostParentQuestionIdForComplainType = $mostParentQuestionForComplainType->id;

                $haveRootQuestionForComplainType = 1;
            }


            $sameQuestion       = Questions::select('name')->where('name',$questionName)->where('id' ,'<>', $questionId )->first();
            // $questionValidateData       = Questions::where('parent_question_id',$parentQuestionId)->where('question_option_id', $questionoptionId )->first();
            
            $questionValidateData = array();

            foreach ($parentArray  as $key => $row) 
            {
                if (!empty($row['parentId']) && !empty($row['parentOptionsId'])) 
                {
                    
                    $questionValidateData       = QuestionBranchingLogic::where('parent_question_id',$row['parentId'])->where('parent_question_option_id',$row['parentOptionsId'] )->first();
                }
            }

            $parentQuestionExist = "";

            $haveSameParentQuestionForComplainType = 0;
            if($haveRootQuestionForComplainType > 0)
            {
                if($parentQuestionId && $questionoptionId)
                {
                    $parentQuestionExist = "1";
                }
                else
                {
                    $parentQuestionExist = "";
                }
            }
            else
            {
                $parentQuestionExist = "1";
            }

            if($questionId)
            {
                if($questionId == $mostParentQuestionIdForComplainType)
                {
                    $parentQuestionExist = "1";
                }
            }


            $parentAndQuestionidExist = "1";
            /*
            if($parentQuestionExist != "1")
            {
                 if($parentQuestionId)
                 {
                    if(!$questionoptionId)
                    {
                        $parentAndQuestionidExist = ""; 
                    }
                 }
            }*/
            

            if ($sameQuestion) 
            {
                $questionTitleExist = "";

                $questionTitle = $sameQuestion->name;
            }
            else
            {
                $questionTitleExist = 1;
            }


            $questionValidateData = '';
            if($parentQuestionId && $questionoptionId)
            {
                if($questionId)
                {   
                     foreach ($parentArray  as $key => $row) 
                    {   
                        if (!empty($row['parentId']) && !empty($row['parentOptionsId'])) 
                        {
                            $questionValidateData   = QuestionBranchingLogic::where('parent_question_id',$row['parentId'])->where('parent_question_option_id' , $row['parentOptionsId'] )->where('id','<>', $questionId)->first();
                        }
                    }

                }
                else
                {
                    foreach ($parentArray  as $key => $row) 
                    {
                        if (!empty($row['parentId']) && !empty($row['parentOptionsId'])) 
                        {
                            $questionValidateData   = QuestionBranchingLogic::where('parent_question_id',$row['parentId'])->where('parent_question_option_id' , $row['parentOptionsId'])->first();
                        }
                    }
                   

                }
            }            
            


            $QueBranchErrorTitle = '';
            if ($questionValidateData) 
            {
                $questionExist = "";

                $QueBranchErrorTitle = $questionValidateData->name;
            }
            else
            {
                $questionExist = 1;
            }
            $questionOptionsOldData = array();
            $questionOptionsArray = array();
            // $finalQuestionOptionsArray = array();
            $questionOptionsId              = $request->input('old_questions_opt_id');
            $questionOptionsText            = $request->input('option_text');
            $questionOptionsOrder           = $request->input('option_order');
            $questionOptionsNarrativeText   = $request->input('option_narrative_text');
            $questionOptionsRequiredInput   = $request->input('option_required_input');
            $questionOptionsRequiredInputLabel   = $request->input('option_required_input_label');

            
            $questionOptionsTextNotFound = "1";
            $questionOptionsSortOrderNotFound = "1";
            $questionOptionsNarrativeTextNotFound = "1";
            $questionOptionsSortOrderNotFoundNumeric = "1";
            

            if (is_array($questionOptionsText) && count($questionOptionsText) > 0) 
            {
                $questionOptionsTextForValidation = $questionOptionsText;
                $questionOptionsOrderForValidation = $questionOptionsOrder;
                $questionOptionsNarrativeTextForValidation = $questionOptionsNarrativeText;
                $questionOptionsRequiredInputForValidation = $questionOptionsRequiredInput;

                foreach ($questionOptionsText as $key => $value) 
                {
                    $questionOptionsOldData = array();

                    if($questionOptionsTextNotFound)
                    {
                        if(!$value)
                        {
                            $questionOptionsTextNotFound = "";
                        }
                        else
                        {
                            $questionOptionsTextNotFound = "1";
                        }
                    }
                    
                    if($questionOptionsSortOrderNotFound)
                    {
                        if (!$questionOptionsOrder[$key]) 
                        {
                            $questionOptionsSortOrderNotFound = "";
                        }
                        else
                        {
                            $questionOptionsSortOrderNotFound = "1";
                        }
                    }

                    if($questionOptionsSortOrderNotFoundNumeric)
                    {
                        if (is_numeric($questionOptionsOrder[$key])) 
                        {
                            $questionOptionsSortOrderNotFoundNumeric = "1";
                        }
                        else
                        {
                            $questionOptionsSortOrderNotFoundNumeric = "";
                        }
                    }

                    if ($questionOptionsSortOrderNotFound == NULL) 
                    {
                        $questionOptionsSortOrderNotFoundNumeric = "1";
                    }

                    if($questionOptionsNarrativeTextNotFound)
                    {
                        if (!$questionOptionsNarrativeText[$key]) 
                        {
                            $questionOptionsNarrativeTextNotFound = "";
                        }
                         else
                        {
                            $questionOptionsNarrativeTextNotFound = "1";
                        }
                    }

                    if(empty($questionOptionsRequiredInputLabel[$key])) 
                    {
                        $questionOptionsRequiredInputLabel[$key] = "";
                    }
                    

                    $questionOptionsOldData['old_questions_opt_id'] = $questionOptionsId[$key];
                    $questionOptionsOldData['title'] = $value;
                    $questionOptionsOldData['sort_order'] = $questionOptionsOrder[$key];
                    $questionOptionsOldData['narrative_text'] = $questionOptionsNarrativeText[$key];
                    $questionOptionsOldData['required_input'] = $questionOptionsRequiredInput[$key];
                    $questionOptionsOldData['required_input_label']       = $questionOptionsRequiredInputLabel[$key];
                    
                    $questionOptionsArray[] = (object) $questionOptionsOldData;

                }

                //echo '--'.$questionOptionsSortOrderNotFoundNumeric.'--';
                //exit;
            }
            $questionOptinsvalidation = "";
            if($questionOptionsArray)
            {
                $questionOptinsvalidation = "1";
            }

            $rules = array('questionTitleExist' => 'required','questionExist' => 'numeric',  'category' => 'required',  
                'complain_type_id' => 'required','name' => 'required|max:255', 'status' => 'required', 
                //'questionExist' => 'required', 'parentAndQuestionidExist' => 'required', 'parentQuestionExist' => 'required',
                  'questionOptinsvalidation' => 'required','questionOptionsTextNotFound' => 'required',
                 'questionOptionsSortOrderNotFound' => 'required', 'questionOptionsSortOrderNotFoundNumeric' => 'required',
                 'questionOptionsNarrativeTextNotFound' => 'required');
            $messages['category.required']            =  'Question Category is required';
            $messages['complain_type_id.required']    =  'Chief Complain is required';
            $messages['name.required']                =  'Question Title is required';
            $messages['questionOptionsTextNotFound.required']                =  'Option Text is required for some of the option(s)';
            $messages['questionOptionsSortOrderNotFoundNumeric.required']                =  'Option Order should be numeric - please check some of the option(s)';
            $messages['questionOptionsSortOrderNotFound.required']                =  'Option Order is required for some of the option(s)';
            $messages['questionOptionsNarrativeTextNotFound.required']                =  'Option Narrative Text is required for some of the option(s)';
            // $messages['question_order.required']      =  'Question is Order required';
            //$messages['questionExist.required']       =  'This Question Branching logic already applied on "'.$QueBranchErrorTitle.'"';
            // $messages['parent_question_id.required']       =  'Parent Question is required';
            $messages['questionTitleExist.required']       =  'Given title for this question is already exists';
            $messages['parentAndQuestionidExist.required']       =  'Parent Queston and Option for Parent Queston is required';
            // $messages['question_option_id.required']       =  'Options For Parent Question is required';
            $messages['parentQuestionExist.required']        =  'You have to select branching logic for this question';
            $messages['questionOptinsvalidation.required']        =  'Please provide options details';

            $request_all = $request->all();

            $request_all['questionTitleExist'] =  $questionTitleExist;
            $request_all['questionExist'] =  $questionExist;
            $request_all['parentQuestionExist'] =  $parentQuestionExist;
            $request_all['parentAndQuestionidExist'] =  $parentAndQuestionidExist;
            $request_all['questionOptinsvalidation'] =  $questionOptinsvalidation;
            $request_all['questionOptionsTextNotFound'] =  $questionOptionsTextNotFound;
            $request_all['questionOptionsSortOrderNotFound'] =  $questionOptionsSortOrderNotFound;
            $request_all['questionOptionsNarrativeTextNotFound'] =  $questionOptionsNarrativeTextNotFound;
            $request_all['questionOptionsSortOrderNotFoundNumeric'] =  $questionOptionsSortOrderNotFoundNumeric;
            
            $validator = Validator::make($request_all, $rules,$messages);
            
            if ($validator->fails()) 
            {   
                $QuestionBranchingLogics = array();

                if($request['parent_question_id'])
                {
                    foreach ($request['parent_question_id'] as $key => $value) 
                    {
                        $_QuestionBranchingLogics['parent_question_id']        = $value;
                        $_QuestionBranchingLogics['parent_question_option_id'] = $request['question_option_id'][$key];
                        $QuestionBranchingLogics[] = $_QuestionBranchingLogics;
                    }
                    
                }
                //dd($QuestionBranchingLogics);
                return redirect(route('save_question',$questionId))->
                withErrors($validator)->withInput()
                ->with(
                    [
                        'complainTypeId'=> $complainTypeId, 
                        'parentQuestionId'=> $parentQuestionId, 
                        'questionoptionId'=> $questionoptionId, 
                        'questionId'=> $questionId, 
                        'questionOptionsArray'=> $questionOptionsArray, 
                        'duplicateQuestionsCount' => $duplicateQuestionsCount,
                        'questionsArray'=> Questions::where('complain_type_id',$complainTypeId)->get()->toArray(),
                        'QuestionBranchingLogics'=>$QuestionBranchingLogics
                ]);
            }

            $questions->name                = $request->input('name');
            $questions->category_id         = $request->input('category');
            $questions->sort_order          = $request->input('sort_order');
            $questions->status              = $request->input('status');

             $questions->parent_question_id = 0;
            // if($request->input('parent_question_id'))
            // {
            //     $questions->parent_question_id  = $request->input('parent_question_id');

            //     $parent_question_id = $questions->parent_question_id;
            // }

            $questions->department_id       = Auth::user()->department_id;
            $questions->added_by_id         = Auth::user()->id;
            $questions->complain_type_id    = $request->input('complain_type');            

            $questions->question_option_id = 0;
            // if($request->input('question_option_id'))
            // {
            //     $questions->question_option_id  = $request->input('question_option_id');
            // }

            if($request->input('name') && $request->input('complain_type_id'))
            {   
                $questions->complain_type_id    = $request->input('complain_type_id');

            }
            $questions->save();

            $questionOptionsId              = $request->input('old_questions_opt_id');
            $questionOptionsText            = $request->input('option_text');
            $questionOptionsOrder           = $request->input('option_order');
            $questionOptionsNarrativeText   = $request->input('option_narrative_text');
            $questionOptionsRequiredInput   = $request->input('option_required_input');
            $questionOptionsRequiredInputLabel   = $request->input('option_required_input_label');

            if (empty($questionOptionsId)) 
            {
                QuestionOptions::where('question_id',$questions->id)->update(['question_id' => NULL]);
            }
            if($questionOptionsText)
            {   

                if(!empty($questionOptionsId))
                {   
                    QuestionOptions::whereNotIn('id',array_filter($questionOptionsId))->where('question_id',$questions->id)->delete();
                }
                
                foreach ($questionOptionsText as $key => $value)
                {   
                    $questionOptionsData = array();
                    $id = @$questionOptionsId[$key];
                   
                   /* if($id)
                    {
                        $questionOptionsData                  = QuestionOptions::find($id);
                    }
                    else
                    {
                         $questionOptionsData                      = new QuestionOptions();
                    }*/
                    //$questionOptionsData['id']              = $questionOptionsId[$key];

                    if(empty($questionOptionsRequiredInputLabel[$key])) 
                    {
                        $questionOptionsRequiredInputLabel[$key] = "";
                    }
                    
                    $questionOptionsData['title']             = $value;
                    $questionOptionsData['sort_order']        = $questionOptionsOrder[$key];
                    $questionOptionsData['required_input']       = $questionOptionsRequiredInput[$key];
                    $questionOptionsData['required_input_label']       = $questionOptionsRequiredInputLabel[$key];
                    $questionOptionsData['narrative_text']    = $questionOptionsNarrativeText[$key];
                    $questionOptionsData['question_id']       = $questions->id;
                    QuestionOptions::updateOrCreate(['id' => $id]
                        ,$questionOptionsData);
                    //$questionOptionsData->save();
                    
                   
                }
            }

           DB::table('question_branching_logic')->where('question_id', $questionId)->delete();
            if (!empty($parentArray)) 
            {
                foreach ($parentArray  as $key => $row) 
                {
                    if (!empty($row['parentId']) && !empty($row['parentOptionsId'])) 
                    {
                        

                        $question_branching_logicID = DB::table('question_branching_logic')->insert([
                             'parent_question_id'       =>   $row['parentId'],
                             'parent_question_option_id'       =>  $row['parentOptionsId'],
                             'question_id'  =>  $questions->id,
                              ]);
                        // dd($question_branching_logicID);
                    }
                }
            }
            return redirect(route('save_question', $questions->id))->with('success', 'Question has been saved successfully!');

        }

        return view('physician.questions.form',[
            'questionData'=>$questionData,
            'heading'=>$heading,
            'route'=>$route,
            'questions'=>$questions,
            'questionsArray'=>$questionsArray,
            'QuestionBranchingLogics'=>$QuestionBranchingLogics,
            // 'parentQuestionOptions'=> QuestionOptions::where('question_id', 2)->orderby('sort_order')->get(),
            // 'parentQuestionOptions'=> QuestionOptions::where('question_id', 2)->orderby('sort_order')->get(),
            'questionOptions'=>QuestionOptions::where('question_id', $id)->orderby('sort_order')->get(),
            'complain_types'=>CheifComplainTypes::all(),
            'categories'=> QuestionCategories::all(),
            'id'=>$id,
            'question_model' => new Questions(),
            'duplicateQuestionsCount' => $duplicateQuestionsCount
            ]
        );

    }

      //  CREATE DATATABLE FOR CHEIF COMPLAINS
    public function QuestionsAjax(Request $request)
    {
        $_getParams             = $_GET;
        $params                 = CommonHelper::_processDataTableRequest($_getParams);
        $status                 = @$_GET['status'];
        $complainType           = @$_GET['complain'];
        $category               = @$_GET['category'];
        $draw                   = $params['draw'];      
        $offset                 = $params['offset'];
        $searchKeyword          = $params['search_keyword'];
        $sortColumn             = $params['sort_column'];
        $sortOrderDirection     = $params['sort_direction'];
        $recordsPerPage         = $params['records_per_page'];
        $objQuestions           =  new Questions();
        $recordsTotal           = $objQuestions->count();
        $objQuestions =$objQuestions->where('duplicate_form_id', NULL);
        if($complainType!='')
        {   
            $objQuestions =$objQuestions->where('complain_type_id', $complainType);
        }
        if($category!='')
        {   
           $objQuestions =$objQuestions->where('category_id', $category);
        }
        if($searchKeyword)
        {           
            $objQuestions = $objQuestions->where(function($query) use ($searchKeyword) 
            {
              $query->orWhere('name', 'like', '%'.$searchKeyword.'%');

            });
        }
        if($status!='')
        {   
            $objQuestions = $objQuestions->where('status', $status);
        }
        
        // if($sortColumn!='')
        // {   
        //    $objQuestions =$objQuestions->orderBy($sortColumn,$sortOrderDirection);
        // }
        

        
        $objQuestions = $objQuestions->offset($offset)->limit($recordsPerPage);
        $recordsFiltered        = $objQuestions->count();
        $objQuestions               = $objQuestions->orderby('id', 'ASC')->get();
        $listData = array(); 
        foreach ($objQuestions as $key => $row) 
        {       
            $tempArray      = array();
            $_arOptionData  = array();
            $chiefComplain  = CheifComplainTypes::select('name')->where('id', $row->complain_type_id)->first();
            $questionCategories  = QuestionCategories::select('title')->where('id', $row->category_id)->first();
            if ($questionCategories) 
                {
                   $questionCategories = $questionCategories->title;
                }
            else
                {
                    $questionCategories = "";
                }
            if($chiefComplain)
                {
                    $chiefComplain = $chiefComplain->name;
                }
            else
                {
                    $chiefComplain = "";    
                }
            $parentQuestionTitle  = $row::select('name','id','question_option_id')->where('id', $row->parent_question_id)->first();

            if ($parentQuestionTitle) 
                {
                   $QuestionOptions  = QuestionOptions::select('title')->where('id',$row->question_option_id)->first();
                   $editQuestion     = route('save_question', $parentQuestionTitle->id);
                   $QuestionOptions  = $QuestionOptions['title'];
                   $parentTitle      = $parentQuestionTitle->name;
                   $deitPencil       = "la la-pencil";
                   $parentHeading    = "Parent Question";
                   $OptionForParentQuestion = "Option For Parent Question";
                }
            else
                {
                    $editQuestion = "";
                    $parentTitle = "";
                    $QuestionOptions = "";
                    $deitPencil = "";
                    $parentHeading = "";
                    $OptionForParentQuestion = "";

                }

            $tempArray[] = $chiefComplain;
            $tempArray[] = $questionCategories;
            $tempArray[] = $row->name;//.'<br><br/><strong>'.$parentHeading.'</strong><br>'.$parentTitle.'<a class="'.$deitPencil.'" href="'.$editQuestion.'" style="margin:5px;><i class="" aria-hidden="true"></i></a><br><br/><strong>'.$OptionForParentQuestion.'<br> </strong>'.$QuestionOptions;
            // $tempArray[]    = $row->sort_order;

            $questionOptions = QuestionOptions::where('question_id', $row->id)->orderby('sort_order')->get();
          
            foreach ($questionOptions as  $value) 
            {

                $_arOptionData[]    = "<li>".$value->title."</li>";
               
            }
                $tempArray[]    = implode('', $_arOptionData);
                // $tempArray[]    = $tempArray2;

           
            $deletePath = route('delete_questions', $row->id);
            $editPath   = route('save_question', $row->id);
            $statusIcon = "ti-close";
            $statusText = "Inactive Now";
            $status = 'Active';
            if($row->status==config('constants.CONSTANT_STATUS_INACTIVE'))
            {   
                $statusIcon = "ti-check";
                $status = 'Inactive';
                $statusText = "Active Now";
            }
            $tplActions  = <<<EOT
            <a title="Edit" class="la la-pencil" href="$editPath" value="edit" style="margin:5px;><i class="" aria-hidden="true"></i></a>
            <small><a title="$statusText" class="$statusIcon" onclick="return confirm('Are you sure want to change the status of this record?')" href="$deletePath" style="margin:5px;><i class="" aria-hidden="true"></i></a></small>
EOT;
                
                $roles      = array();
               
                $tempArray[]    = $status;
                $tempArray[]    = $tplActions;
                $listData[]     = $tempArray;
        }
        $data = array(
            "draw"            => $draw,
            "recordsTotal"    => $recordsTotal,
            "recordsFiltered" => $recordsFiltered,
            "data"            => $listData
        );
            
        return response()->json($data);
    }


    public function duplicateQuestionsAjax(Request $request, $id = 0)
    {
        $_getParams             = $_GET;

        $params                 = CommonHelper::_processDataTableRequest($_getParams);
        $status                 = @$_GET['status'];
        $complainType           = @$_GET['complain'];
        $category               = @$_GET['category'];
        
        $draw                   = $params['draw'];      
        $offset                 = $params['offset'];
        $searchKeyword          = $params['search_keyword'];
        $sortColumn             = $params['sort_column'];

        $sortOrderDirection     = $params['sort_direction'];
        $recordsPerPage         = $params['records_per_page'];
        $objQuestions           =  new Questions();
        $recordsTotal           = $objQuestions->count();
       if($id!='')
        {   
            $objQuestions = $objQuestions->where('duplicate_form_id', $id);
        }
        $recordsFiltered           = $objQuestions->count();
        if($searchKeyword)
        {           
            $objQuestions = $objQuestions->where(function($query) use ($searchKeyword) 
            {
              $query->orWhere('name', 'like', '%'.$searchKeyword.'%');

            });
        }
        
           $objQuestions = $objQuestions->offset($offset)->limit($recordsPerPage);
        // if($sortColumn!='')
        // {   
        //     $objQuestions =$objQuestions->where('complain_type_id', $complainType);
        // }
        
        // if($category!='')
        // {   
        //    $objQuestions =$objQuestions->where('category_id', $category);
        // }

        $recordsFiltered        = $objQuestions->count();
     // dd($recordsFiltered);
        $objQuestions               = $objQuestions->orderby('id', 'ASC')->get();
        $listData = array(); 
                 
        foreach ($objQuestions as $key => $row) 
        {       

                $tempArray      = array();
                $_arOptionData  = array();
             
                $parentQuestionTitle  = $row::select('name','id','question_option_id')->where('id', $row->parent_question_id)->first();
                if ($parentQuestionTitle) 
                    {
                       $QuestionOptions  = QuestionOptions::select('title')->where('id',$row->question_option_id)->first();
                       $editQuestion     = route('save_question', $parentQuestionTitle->id);
                       $QuestionOptions  = $QuestionOptions['title'];
                       $parentTitle      = $parentQuestionTitle->name;
                       $deitPencil       = "la la-pencil";
                       $parentHeading    = "Parent Question";
                       $OptionForParentQuestion = "Option For Parent Question";
                    }
                else
                    {
                        $editQuestion = "";
                        $parentTitle = "";
                        $QuestionOptions = "";
                        $deitPencil = "";
                        $parentHeading = "";
                        $OptionForParentQuestion = "";

                    }
                $tempArray[] = $row->id;
                $tempArray[] = $row->name;
               
                // $tempArray[]    = $row->sort_order;

                $questionOptions = QuestionOptions::where('question_id', $row->id)->orderby('sort_order')->get();
              
                foreach ($questionOptions as  $value) 
                {

                    $_arOptionData[]    = "<li>".$value->title."</li>";
                   
                }
                
                $tempArray[]    = implode('', $_arOptionData);
                //$tempArray[] = $parentTitle;
                //$tempArray[] = $QuestionOptions;
               

               
                $deletePath = route('delete_questions', $row->id);
                $editPath   = route('save_question', $row->id);
                $statusIcon = "ti-close";
                $statusText = "Inactive Now";
                $status = 'Active';
                if($row->status==config('constants.CONSTANT_STATUS_INACTIVE'))
                {   
                    $statusIcon = "ti-check";
                    $status = 'Inactive';
                    $statusText = "Active Now";
                }
                $tplActions  = <<<EOT
                <a title="Edit" class="la la-pencil" href="$editPath" value="edit" style="margin:5px;><i class="" aria-hidden="true"></i></a>
                <small><a title="$statusText" class="$statusIcon" onclick="return confirm('Are you sure want to change the status of this record?')" href="$deletePath" style="margin:5px;><i class="" aria-hidden="true"></i></a></small>
EOT;
                
                $roles      = array();
               
                // $tempArray[]    = $status;
                $tempArray[]    = $tplActions;
                $listData[]     = $tempArray;
        }
        $data = array(
            "draw"            => $draw,
            "recordsTotal"    => $recordsTotal,
            "recordsFiltered" => $recordsFiltered,
            "data"            => $listData
        );
            
        return response()->json($data);
    }

    // QUESTIONS LISTING

      public function questionsListing()
    {   
        $data['questionCategories'] = QuestionCategories::All();
        $data['cheifComplainTypes'] = CheifComplainTypes::All();
        return view('physician.questions.listing',$data);
    }

    // DELETE QUESTIONS

      public function deleteQuestions($id)
    {
        if($id)
        {   
            $questionData   = Questions::find($id);
            if(!$questionData)
            {
                // Redirect to base
                return redirect(route('questions_listing'));
            }
            if(config('constants.CONSTANT_STATUS_INACTIVE')==$questionData->status)
            {
                $questionData->status = config('constants.CONSTANT_STATUS_ACTIVE');
            }
            else
            {
                $questionData->status = config('constants.CONSTANT_STATUS_INACTIVE');
            }
            $questionData->save();
            //QuestionOptions::where('question_id',$id)->update(['status' => 0]);
            return redirect()->back()->with('success', 'Question has been deleted successfully!');
            //return redirect(route('questions_listing'));
        }
    }

    public function chiefComplainsTree($id)
    {
        $complainTypeId = $id;
        $data = array();

        $questions = Questions::where('complain_type_id', $complainTypeId)
                              ->get();
        $complainType = CheifComplainTypes::select('name')->where('id', $id)->first();
        $complainHeading = @$complainType->name;

        foreach($questions as $q)
        {
            $questionOptions = $q->getQuestionOptions($q->id);
            
            foreach($questionOptions as $o)
            {
                if(!$q->parent_question_id)
                {
                    $q->parent_question_id = 0;
                }

                if(!$q->question_option_id)
                {
                    $q->question_option_id = 0;
                }
                
                $data[] = array(
                                
                                'question_id'    => $q->id,
                                'question_title' => $q->name,
                                'parent_question_id' => $q->parent_question_id,
                                'parent_question_option_id' => $q->question_option_id,
                                'option_id' => $o->id,
                                'option_text' => $o->title
                        );

            }
        }

        $data = $this->buildTree($data);

        $treeHTML = "No Questions Found!";

        if(is_array($data) && count($data) > 0)
        {

            $treeHTML = $this->buildTreeHTML($data);
        }        

        $heading = "Questions Tree View for " .$complainHeading;

        return view('physician.tree-view.complain_tree', [ 'data' => $data, 'heading' => $heading, 'tree_html' => $treeHTML ]);

        //return view('physician.tree-view.complain_tree');
    }

    function buildTree(array $elements, $parentId = 0, $optionId=0) 
    {
        $branch = array();

        foreach ($elements as $element) 
        {
            if( ($element['parent_question_id']  == $parentId) && ($element['parent_question_option_id']  == $optionId) ) 
            {
                $children = $this->buildTree($elements, $element['question_id'], $element['option_id']);
                
                if ($children)
                {
                    $element['children'] = $children;
                }

                $branch[] = $element;
            }
        }

        return $branch;
    }

    function buildTreeHTML($elements, $html='') 
    {
        $html .= '<ul>';

        foreach ($elements as $element) 
        {
            //-->$html .= '<li class="jstree-open" style="padding-bottom: 5px;"><span style="color: green; font-size: 15px;">' . @$element['question_title'] . '</span> <span class="ti-arrow-right" style="padding: 0px 5px; color: red; font-weight: bold;"></span> <span style="color: blue;">' . @$element['option_text'] .'</span>';

            $question_id = @$element['question_id'];

            $html .= '<li class="jstree-open" style="padding-bottom: 5px;"><span style="color: green; font-size: 15px;"> ' . @$element['question_title'] . ' <a href="#'.$question_id.'" onclick="return treeViewOnClickTrigger('.$question_id.');" class="la la-pencil" ></a> </span>  <span class="ti-arrow-right" style="padding: 0px 5px; color: red; font-weight: bold;"></span> <span style="color: blue;">' . @$element['option_text'] .' </span>';

            if(isset($element['children']))
            {
                $html = $this->buildTreeHTML($element['children'], $html);
            }

            $html .= '</li>';
        }

        $html .= '</ul>';

        return $html;
    }

    public function duplicateUser($id)
    {
        if ($id) 
        {
            // REPLICATE QUESTIONS
            $questionsData = Questions::find($id);
            $duplicateQuestion = $questionsData->replicate();
            $duplicateQuestion['name'] = 'Duplicate of: '.$questionsData->name;
            $duplicateQuestion['duplicate_form_id'] = $id;
            $duplicateQuestion['question_option_id'] = NULL;
            $duplicateID = $duplicateQuestion->save();

            // REPLICATE QUESTION OPTIONS
            $questionOptionsData = QuestionOptions::where('question_id', $id)->get();
            foreach ($questionOptionsData as $value) 
            {
                $duplicateQueOptions = $value->replicate();
                $duplicateQueOptions['question_id'] = $duplicateQuestion->id;
                $duplicateQueOptions->save();
            }

            $QuestionBranchingLogicData = QuestionBranchingLogic::where('question_id', $id)->get();
            foreach ($QuestionBranchingLogicData as $value) 
            {
                $duplicateQueParent = $value->replicate();
                $duplicateQueParent['question_id'] = $duplicateQuestion->id;
                $duplicateQueParent->save();
            }
            return redirect(route('save_question', $duplicateQuestion->id))->with('success', 'Question replicated successfully!');
        }
    }

     public function imageMapping($id = false, $imageType= '')
    {
        $imageSrc = '';
        $imageType = 'image_'.$imageType;

        if ($id) 
        {  
            
            if (!empty($imageType)) 
            {
                $imageSrc = CheifComplainTypes::select($imageType)->where('id',$id)->first();
                if (!empty($imageSrc)) 
                {
                    if(isset($imageSrc->image_front))
                    {
                        $image = $imageSrc->image_front;
                    }
                    if(isset($imageSrc->image_back))
                    {
                        $image = $imageSrc->image_back;
                    }
                    // $imageSrc         = asset('').'assets/'.$image;

                    $imageSrc = CommonHelper::getImageFolderUrlForComplainType($image);
                    $imageMapping['imageMapping'] = ImageMapping::where('complain_type_id',$id)->where('image_type',$imageType)->get();

                    if (!$imageMapping['imageMapping']->isEmpty()) 
                    {
                            $imageMapping['imageMapping'][0]->image_src = $imageSrc;
                       
                    }
                    else
                    {

                        $imageMapping = "";
                    }
                }
            }
            return view('physician.chief-complaints.image_mapping', ['imageMapping' => $imageMapping ,'image' => $imageSrc , 'image_type' => $imageType , 'complain_type_id' => $id]);
            // return response()->json($imageMapping);
        }
        $imageMapping = "";
        $id = "";
        $imageType = "";
        return view('physician.chief-complaints.image_mapping', ['imageMapping' => $imageMapping,'image' => $imageSrc , 'image_type' => $imageType , 'complain_type_id' => $id ]
    );
    }

     public function imagePixel()
    {   
        return view('physician.chief-complaints.image_pixel');
    }

    public function ImageMappingaAjaxAdd(Request $request)
    {
        $id = Auth::user()->id;
        // $imageMapping['chiefComplainImage'] = CheifComplainTypes::select('image_front','image_back')->where('image_front',$id)->first();
        $imageMapping = new ImageMapping();
        $imageArray = $request->input('myJSON');
        $image_type = $request->input('image_type');
        $complain_type_id = $request->input('complain_type_id');
        $imageArray = html_entity_decode($imageArray);
        $imageArray = json_decode($imageArray);
        $imageSrc                     = $imageArray->src;
        $imageSrc                     = ImageCreateFromJpeg($imageSrc);
        $imageMapping['image_width']  = ImageSX($imageSrc);
        $imageMapping['image_height'] = ImageSY($imageSrc);
        $imageMapping['image_src']    = $imageArray->src;
        $imageMapping['image_type']   = $image_type;
        $imageMapping['complain_type_id']      = $complain_type_id;
        $imageMapping['user_id']      = $id;
        $imageMapping['label']        = $imageArray->text;
        $imageMapping['coordinate_x'] = $imageArray->shapes[0]->geometry->x;
        $imageMapping['coordinate_y'] = $imageArray->shapes[0]->geometry->y;
        $imageMapping['coordinate_width']        = $imageArray->shapes[0]->geometry->width;
        $imageMapping['coordinate_height']       = $imageArray->shapes[0]->geometry->height;
        $imageMapping->save();
        echo $imageMapping->id; 
        exit;

        // ImageMapping::updateOrCreate(
        //         $imageMapping
        //     );
    }

     public function ImageMappingaAjaxEdit(Request $request)
    {
        $id = Auth::user()->id;
        // $imageMapping['chiefComplainImage'] = CheifComplainTypes::select('image_front','image_back')->where('image_front',$id)->first();
        // $imageMapping = new ImageMapping();
        $imageArray = $request->input('myJSON');
        $image_type = $request->input('image_type');
        $complain_type_id = $request->input('complain_type_id');
        $imageArray = html_entity_decode($imageArray);
        $imageArray = json_decode($imageArray);
        $imageSrc                     = $imageArray->src;
        $imageSrc                     = ImageCreateFromJpeg($imageSrc);
        $imageMapping['image_width']  = ImageSX($imageSrc);
        $imageMapping['image_height'] = ImageSY($imageSrc);
        $imageMapping['image_src']    = $imageArray->src;
        $imageMapping['image_type']   = $image_type;
        $imageMapping['complain_type_id']      = $complain_type_id;
        $imageMapping['user_id']      = $id;
        $imageMapping['id']           = $imageArray->image_map_id;
        $imageMapping['label']        = $imageArray->text;
        $imageMapping['coordinate_x'] = $imageArray->shapes[0]->geometry->x;
        $imageMapping['coordinate_y'] = $imageArray->shapes[0]->geometry->y;
        $imageMapping['coordinate_width']        = $imageArray->shapes[0]->geometry->width;
        $imageMapping['coordinate_height']       = $imageArray->shapes[0]->geometry->height;
        // $imageMapping->save();
        // dd($imageMapping);

        ImageMapping::updateOrCreate(
                ['id' => $imageMapping['id']],
                $imageMapping
            );
    }

    public function imageMappingDelete(Request $request)
    {
        $imageArray = $request->input('myJSON');
        $imageArray = html_entity_decode($imageArray);
        $imageArray = json_decode($imageArray);
        $id = $imageArray->image_map_id;
        if ($id) 
        {
            $ImageMapping = ImageMapping::find($id);
            $ImageMapping->delete();
        }
    }

// PHP program to Check if 
// a point lies on or inside 
// a rectangle | Set-2 

// function to find if given 
// point lies inside a given 
// rectangle or not. 
   // public function isCoordinateExist($id = 4) 
   // { 
   //      $imageMapping = ImageMapping::find($id);
   //      $x = 0.00847458;
   //      $y = 0.0035461;
   //      $x1 = $imageMapping->coordinate_x * 1000;
   //      $y1 = $imageMapping->coordinate_y * 1000;
   //      $x2 = $x1 + $imageMapping->width;
   //      $y2 = $y1 + $imageMapping->height;
        
   //      if($x > $x1 && $x < $x2 && $y > $y1 && $y < $y2)
   //      {
   //         echo "exist";die; 
   //      } 
   //      else
   //      {
   //          echo "not exist";die;
   //      }
   //  } 
}