<?php
namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Helpers\SalesforceHelper;
use App\Helpers\CommonHelper;
use App\Helpers\WpAPI;
use App\User;
use Validator;
use Hash;
use Config;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Mail\Message;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\File;
use App\Models\AccessToken;
use App\Models\LogsAPIs;
use App\Models\CheifComplainTypes;
use App\Models\Questions;
use App\Models\QuestionOptions;
use App\Models\PatientDetails;
use App\Models\PatientNarratives;
use App\Models\PatientCheifComplainAnswers;
use App\Models\QuestionBranchingLogic;
use App\Models\QuestionCategories;


use App\Models\UserDevices;

use Illuminate\Support\Facades\Mail;
use App\Mail\SendMailable;
use Auth;

class PatientController extends Controller
{
  /**
     * Create a new controller instance.
     *
     * @return void
     */
    public $data = array();
    public $api_log_id = 0;
    public $api_start_time = 0;
    public $current_request;

    public function __construct(Request $request)
    {
        $this->current_request = $request;
        $return = CommonHelper::contructLog($request);
        if(isset($return['api_start_time']))
        {
            $this->api_start_time = $return['api_start_time'];
        }
        if(isset($return['api_log_id']))
        {
            $this->api_start_time = $return['api_log_id'];
        }
    }

  

   

   

    


    public function saveNarrativesByPatientID(Request $request)
    { 
      $input     = json_decode($request['data'],true);
      //dd($input);
      $response   = array();
      $errors   = array();
      if(!empty($input))
      { 
        $isUpdate = 1;
        $email='';
        $isExport=0;
        $PatientId  = $input['patient_id'];

        //dd($PatientId);
        $narrativeSummary = $input['narrative_summary'];
        $answers        = $input['answers'];
     
        if(!$answers)
        {
          $errors[] = "Answers Is Required";
        }
        if(!$narrativeSummary)
        {
          $errors[] = "Narrative Summary Is Required";
        }
        if(empty($errors))
        {
          if($answers)
          {

            $this->addPatientNarrative($answers,$PatientId,$addAnother=1);
            PatientDetails::updateOrCreate(['id' => $PatientId],
              array(
                'narrative_summary' =>$narrativeSummary,
                'status' =>config('constants.CONSTANT_STATUS_ACTIVE')
              )
            );
          }
          $response[]  = "Patient Narrative Has Been Saved Successfully";   
        }
      }
      if (!empty($response)) 
      {
          $data["header"]["error"]    = '0';
          $data["header"]["message"]  = "Success";
          $data['body']['details']    = $response;
          return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
      }
      else
      {
          $data["header"]["error"]    = '1';
          $data["header"]["message"]  = $errors;
          return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
      } 
    }
   

  public function updatePatientNarrative($answers,$narrative_id,$_narrativeSummary,$patient_additional_info='')
  { 
    $optionData = PatientCheifComplainAnswers::where('narrative_id',$narrative_id);
    // $optionData = PatientCheifComplainAnswers::find($narrative_id);
    $optionData->delete();
    foreach ($answers as $k2 => $answer) 
    {
      $optionData = $answer['optionData'];
      $complain_type = $answer['complain_type'];
      $surgeon_id = $answer['surgeon_id'];
      $image_view = $answer['complainLocationData']['image_view'];
      $image = $answer['complainLocationData']['image'];
      $coordinate_x = $answer['complainLocationData']['coordinate_x'];
      $coordinate_y = $answer['complainLocationData']['coordinate_y'];
      $narrativeData  = PatientNarratives::find($narrative_id);
     
      //dd($narrativeData);
      if (!empty($optionData)) 
      {
        $narrative_text = array();
        // $optionData = PatientCheifComplainAnswers::find($narrative_id);
        // $optionData->delete();
        foreach ($optionData as $key => $row) 
        {

          $narrative_text[] = $row['narrative_text'];
          $required_input_text = "";
          $required_input = 0;
          $required_input = $row['required_input'];
          if($required_input == 1) 
          {
            $required_input_text = $row['required_input_text'];
          }
          DB::table('patient_cheif_complain_answers')->insert([
         'narrative_id'       =>  $narrative_id,
         'patient_cheif_complain_type_id'=>$complain_type,
         'question_id'  =>  $row['question_id'],
         'option_id'  =>  $row['option_id'],
         'sort_order'  =>  $row['sort_order'],
         'required_input_text'  =>  $required_input_text,
          ]);

        }
        $narrativeSummary = implode(' ', $narrative_text);
        if(!empty($narrativeData))
        { 
          $patientId =  $narrativeData->patient_id;
          $narrativeData->complain_type_id  = $answer['complain_type'];
          $narrativeData->image_view        = $answer['complainLocationData']['image_view'];
          $narrativeData->coordinate_x      = $answer['complainLocationData']['coordinate_x'];
          $narrativeData->coordinate_y      = $answer['complainLocationData']['coordinate_y'];
          $narrativeData->narrative_summary = $narrativeSummary;
          $narrativeData->save();

          $patientsData = PatientDetails::find($patientId);
          $patientsData->narrative_summary = $_narrativeSummary;
          if($patient_additional_info)
          {
            $patientsData->patient_additional_info = $patient_additional_info;
          }
          $patientsData->save();
        }
      }
    }
  }

  public function pendingPatientNarratives(Request $request)
  { 
    $id = $request['surgeon_id'];
    $offset = @$request['offset'];
    $limit = @$request['limit'];
    if(empty($offset)) 
    { 
      $offset = 0;
    } 
    $offset = $offset*$limit;
    $status = config('constants.CONSTANT_STATUS_INACTIVE');
    if(isset($request['active']))
    {
      $status = config('constants.CONSTANT_STATUS_ACTIVE');
    }
    if(!$id)
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = "Surgeon Is Required";
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    $resultData = array();
    $pendingPatientNarratives   = PatientDetails::where('surgeon_id',$id)->where('status',$status);
    $totalRecords               = $pendingPatientNarratives->count();
    $totalPages                 = (int)ceil($totalRecords/$limit);
    $pendingPatientNarratives   = $pendingPatientNarratives->offset($offset)->limit($limit)->get();
    $PatientNarratives = array();
    foreach ($pendingPatientNarratives as $row) 
    { 
      $pateint_narratives  = PatientNarratives::where('patient_id',$row->id)->get();
      $complainTypes = array();
      foreach ($pateint_narratives as $k => $r)
      { 
        if($r->primary_complain)
        {
          $_complainTypes = CheifComplainTypes::find($r->complain_type_id); 
        }
        $complainTypes=$_complainTypes->name;
      }
      $row->complain_types = $complainTypes;
      $row->pateint_narratives  = $pateint_narratives;
      $resultData[] = $row;
    }
    if (!empty($resultData)) 
    { 
      $data["header"]["error"]    = '0';
      $data["header"]["message"]  = "Success";
      $data['body']['details']    = array('data'=>$resultData,'total_pages'=>$totalPages);
      // $data['body']['details']   = $PatientNarratives;
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    else
    {
        $data["header"]["error"]    = '1';
        $data["header"]["message"]  = "Data not found";
        return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    } 
  }

  public function getPatientNarrativesByPatientID(Request $request)
  { 
    $id = $request['patient_id'];
    

    $offset = @$request['offset'];
    $limit = @$request['limit'];
    if(empty($offset)) 
    { 
        $offset = 0;
    } 
    if(!$id)
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = "Patient Is Required";
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    $resultData = array();
    $pendingPatientNarratives  = PatientDetails::where('id',$id)->where('status',config('constants.CONSTANT_STATUS_INACTIVE'))->offset($offset)->limit(config('constants.CONSTANT_API_PAGINATION'))->get();
    $PatientNarratives = array();
    foreach ($pendingPatientNarratives as $row) 
    { 
      $row->pateint_narratives  = PatientNarratives::where('patient_id',$row->id)->get();
      $resultData[] = $row;
    }
    if (!empty($resultData)) 
    {
        $data["header"]["error"]    = '0';
        $data["header"]["message"]  = "Success";
        $data['body']['details']    = $resultData;
        // $data['body']['details']   = $PatientNarratives;
        return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    else
    {
        $data["header"]["error"]    = '1';
        $data["header"]["message"]  = "Data not found";
        return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    } 
  }
  
  public function patientNarrativesDetails(Request $request)
  { 
    $id = $request['narrative_id'];
    if(!$id)
    {
      $data["header"]["error"]    = '1';
          $data["header"]["message"]  = "Narrative Is Required";
          return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
      $patientNarratives  = PatientNarratives::find($id);
      if (!empty($patientNarratives)) 
      { 
        $narrativeAnswers   = PatientCheifComplainAnswers::where('narrative_id',$id)->get();
        $complain_type_id = $patientNarratives['complain_type_id'];
        $questionData  = Questions::where('complain_type_id',$complain_type_id)->where('status',config('constants.CONSTANT_STATUS_ACTIVE'))->orderby('parent_question_id')->orderby('question_option_id')->get();
        if($narrativeAnswers)
        {
          foreach($narrativeAnswers as $key => $row)
          {
            $question         = Questions::find($row->question_id); 
            $questionOptions    = QuestionOptions::find($row->option_id);
            $row->question      = $question->name; 
            $row->option      = $questionOptions->title; 
          }

          if (!empty($questionData)) 
          {
            foreach ($questionData as $key => $row)
            {
              $row->options = QuestionOptions::where('question_id',$row->id)->get();
            }
          }
        }

          $patientNarratives->questions = $questionData;
          $patientNarratives->answers = $narrativeAnswers;
          $data["header"]["error"]    = '0';
          $data["header"]["message"]  = "Success";
          $data['body']['details']    = $patientNarratives;
          return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
      }
      else
      {
          $data["header"]["error"]    = '1';
          $data["header"]["message"]  = "Data not found";
          return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
      } 
  }

  public function getPatientComplains(Request $request)
  { 
    $id = $request['patient_id'];
   
    if(!$id)
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = "Patient Is Required";
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    $resultData = array();
    $patientNarratives = PatientNarratives::where('patient_id',$id)->get();
    foreach ($patientNarratives as $row) 
    { 
      $cheifComplain  = CheifComplainTypes::find($row->complain_type_id);
      $resultData[] = $cheifComplain;
    }
    if (!empty($resultData)) 
    {
      $data["header"]["error"]    = '0';
      $data["header"]["message"]  = "Success";
      $data['body']['details']    = $resultData;
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    else
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = "Data not found";
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    } 
  }

  public function getPatientComplainsDetails(Request $request)
  { 
    $patientId = $request['patient_id'];
    $complainId = $request['complain_id'];
   
    if(!$patientId)
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = "Patient ID Is Required";
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    if(!$complainId)
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = "Complain ID Is Required";
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
   
    $resultData = PatientNarratives::where('patient_id',$patientId)->where('complain_type_id',$complainId)->first();
    // foreach ($patientNarratives as $row) 
    // { 
    //   $cheifComplain  = CheifComplainTypes::find($row->complain_type_id);
    //   $resultData[] = $cheifComplain;
    // }
    if (!empty($resultData)) 
    {
      $data["header"]["error"]    = '0';
      $data["header"]["message"]  = "Success";
      $data['body']['details']    = $resultData;
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    else
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = "Data not found";
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    } 
  }

  

  public function acceptNarrative(Request $request)
  { 
    $token     = $request['token'];
    $this->CheckAccessToken($token);

    $narrativeId  = $request['narrative_id'];
    $surgeonId    = $request['surgeon_id'];
    if(!$surgeonId && $narrativeId)
    {
      $data["header"]["error"]    = '1';
          $data["header"]["message"]  = "Narrative or Surgeon Is Required";
          return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
      $patientNarratives  = PatientNarratives::find($narrativeId);
      if($patientNarratives)
      {
        if($surgeonId==$patientNarratives->via_surgeon_id)
        {
          $patientNarratives->status = config('constants.CONSTANT_STATUS_ACTIVE');
          
          $data["header"]["error"]    = '0';
          $data["header"]["message"]  = "Success";
          $data['body']['details']    = "Narrative accept Successfully";
          return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
      }

      else
      {
        $data["header"]["error"]    = '1';
            $data["header"]["message"]  = "Invalid Surgeon ID";
            return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
      }
      }
      else
      {
        $data["header"]["error"]    = '1';
          $data["header"]["message"]  = "Invalid Narrative ID";
          return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
      }
      
  }





  public function getQuestionByNarrativeID(Request $request)
  { 
      $id = $request['narrative_id'];
      $patientNarratives  = PatientNarratives::find($id);
      $narrativeAnswers   = PatientCheifComplainAnswers::where('narrative_id',$id)->get();
      $questionData      = array();
      if($narrativeAnswers)
        {
          foreach ($narrativeAnswers as $key => $row)
          {
            
            $row->selected_option   = $row->option_id;
            $questionsOptions       = QuestionOptions::find($row->option_id); 
            $row->narrative_text   = $questionsOptions->narrative_text;
          }
        }
            // dd($narrativeAnswers);

      // $questionData  = Questions::where('complain_type_id',$patientNarratives->complain_type_id)->where('status',config('constants.CONSTANT_STATUS_ACTIVE'))->orderby('parent_question_id')->orderby('question_option_id')->get();
      // foreach ($questionData as $key => $row)
      // {
      //   $row->options = QuestionOptions::where('question_id',$row->id)->get();
      // }
      if ($patientNarratives->count() > 0) 
      {
          $data["header"]["error"]    = '0';
          $data["header"]["message"]  = "Success";
          $data['body']['details']   = $patientNarratives;
          $data['body']['details']['questions']    = $narrativeAnswers;
          return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
      }
      else
      {
          $data["header"]["error"]    = '1';
          $data["header"]["message"]  = "Data not found";
          return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
      } 
  }
 


  public function mailSent($mail, $data)
  { 
     Mail::to($mail)->send(new SendMailable($data));
     return 'Email was Successfully sent';
  }

  public function CheckAccessToken($token)
  {
    // if (!empty($token)) 
    // {
    //   $AccessToken  = AccessToken::where('token',$token)->first();
    //   if (empty($AccessToken)) 
    //   {
    //       $data["header"]["error"]    = '1';
    //       $data["header"]["message"]  = 'Token does not match';
    //      echo CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    //   die;
    //   }
    // }
  }


   public function updatePatientNarratives(Request $request)
  { 
    $input     = json_decode($request['data'],true);
    $response   = array();
    $errors   = array();
    if(!empty($input))
    { 
      
      $narrative_id = $input['narrative_id'];
      $narrativeSummary = $input['narrative_summary'];
  
      $answers        = $input['answers'];
   
      if(!$answers)
      {
        $errors[] = "Answers Is Required";
      }
      if(!$narrativeSummary)
      {
        $errors[] = "Narrative Summary Is Required";
      }
     
      if(empty($errors))
      {

        /** TO DO's after auth get user_id which is equla to via_surgeon_id and departmentID **/

        //$savePatientNarratives->department_id     = Auth::user()->department_id;
        //$savePatientNarratives->via_surgeon_id    = Auth::user()->id;
        if($answers)
        {

          $this->updatePatientNarrative($answers,$narrative_id,$narrativeSummary,$input['patient_additional_info']);

        }
        // if ($input['isExport'] == true) 
        // {
        //   $this->mailSent($email,$narrativeSummary);
        // }

        $response[]  = "Patient Narrative Has Been Saved Successfully";   
      }
    }
    if (!empty($response)) 
    {
      $data["header"]["error"]    = '0';
      $data["header"]["message"]  = "Success";
      $data['body']['details']    = $response;
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    else
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = $errors;
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    } 
  }


  public function saveSurgeonQuestion(Request $request)
  { 
    $input     = json_decode($request['data'],true);
    $response   = array();
    $errors   = array();
    $token     = $request['token'];
    $this->CheckAccessToken($token);
    if(!empty($input))
    { 
      $surgeon_id  = $input['surgeon_id'];
      $complain_type_id        = $input['complain_type_id'];
      $question_title        = $input['question_title'];
      $responseText = $input['response'];

      if(!$surgeon_id)
      {
        $errors[] = "Surgeon Is Required";
      }
      if(!$complain_type_id)
      {
        $errors[] = "Complain Type ID Is Required";
      }
      if(!$question_title)
      {
        $errors[] = "Question Title Is Required";
      }
      if(!$responseText)
      {
        $errors[] = "Response Is Required";
      }

      if(empty($errors))
      { 
        DB::table('surgeon_question')->insertGetId([
         'surgeon_id'=>  $surgeon_id,
         'complain_type_id'       =>  $complain_type_id,
         'question_title'       =>  $question_title,
         'response'       =>  $responseText,
       ]);
        $response[]  = "Surgeon Question Has Been Saved Successfully";   
      }
    }
    if (!empty($response)) 
    {
      $data["header"]["error"]    = '0';
      $data["header"]["message"]  = "Success";
      $data['body']['details']    = $response;
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    else
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = $errors;
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    } 
  }
  public function getComplaintypes()
  { 
     $userData = CheifComplainTypes::where('status',config('constants.CONSTANT_STATUS_ACTIVE'))->orderBy('sort_order')->get();
     if (!empty($userData)) 
     {
          $data["header"]["error"]    = '0';
          $data["header"]["message"]  = "Success";
          $data['body']['details']    = $userData;
          return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
     }
     else
     {
          $data["header"]["error"]    = '1';
          $data["header"]["message"]  = "Cheif Complain Types table is empty";
          return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
     } 
  }

  public function getQuestionByComplainTypes(Request $request)
  { 
    $id = $request['complain_type_id'];
    $token     = $request['token'];
    $this->CheckAccessToken($token);

    $questionData  = Questions::where('complain_type_id',$id)->where('status',config('constants.CONSTANT_STATUS_ACTIVE'))->orderby('parent_question_id')->orderby('question_option_id')->get();
    foreach ($questionData as $key => $row)
    {
      $row->options = QuestionOptions::where('question_id',$row->id)->get();
      $questionCategory = QuestionCategories::find($row->category_id);
      $row->category_order = $questionCategory->question_order;
      $row->branchingQuestionData = QuestionBranchingLogic::where('question_id',$row->id)->get();

      
    }
    
    if ($questionData->count() > 0) 
    {
        $data["header"]["error"]    = '0';
        $data["header"]["message"]  = "Success";
        $data['body']['details']    = $questionData;
        return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    else
    {
        $data["header"]["error"]    = '1';
        $data["header"]["message"]  = "Data not found";
        return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    } 
  }

  public function getPatientComplainById(Request $request)
  { 
    $id = $request['patient_id'];
    //$token     = $request['token'];
    //$this->CheckAccessToken($token);

    $patientDetail  = PatientDetails::find($id);
    
    if ($patientDetail->count() > 0) 
    {
        $data["header"]["error"]    = '0';
        $data["header"]["message"]  = "Success";
        $data['body']['details']    = $patientDetail;
        return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    else
    {
        $data["header"]["error"]    = '1';
        $data["header"]["message"]  = "Data not found";
        return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    } 
  }
  public function getPatientOptionsByPatientId(Request $request)
  { 
    $id = $request['patient_id'];
    //$token     = $request['token'];
    //$this->CheckAccessToken($token);

    $patientNarratives  = PatientNarratives::where('patient_id',$id)->get();
    $optionData =   array();

    if($patientNarratives->count() > 0) 
    { 
      foreach ($patientNarratives as $key => $row)
      {
        $_optionData = PatientCheifComplainAnswers::where('narrative_id',$row->id)->get();
        if(!empty($_optionData))
        {
          foreach ($_optionData as $k => $r)
          { 

            $narrativeText = QuestionOptions::find($r->option_id);
            //dd($narrativeText);
            $r->narrative_text = $narrativeText->narrative_text;
            $optionData[$r->patient_cheif_complain_type_id][] = $r;
          }
        }
      }
      
      $data["header"]["error"]    = '0';
      $data["header"]["message"]  = "Success";
      $data['body']['details']    = $optionData;
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    else
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = "Data not found";
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    } 
  }

  public function savePatientNarratives(Request $request)
  { 
    $input     = json_decode($request['data'],true);
    $response   = array();
    $errors   = array();
    $token     = $request['token'];
    $this->CheckAccessToken($token);
    if(!empty($input))
    { 
      $title          = $input['title'];
      $firstName      = $input['first_name'];
      $lastName       = $input['last_name'];
      $email          = $input['email'];
      $phone          = $input['phone'];
      $gender         = $input['gender'];
      $dob            = $input['dob'];
 
      $patient_additional_info  = $input['patient_additional_info'];
      $surgeon_id     = $input['surgeon_id'];
      $narrativeSummary = $input['narrative_summary'];
      $isExport     = $input['isExport'];
      $answers        = $input['answers'];
    

      
      if(!$firstName)
      {
        $errors[] = "First Name Is Required";
      }
      if(!$lastName)
      {
        $errors[] = "Last Name Is Required";
      }
      if(!$dob)
      {
        $errors[] = "Date of Birth Is Required";
      }
      if(!$gender)
      {
        $errors[] = "Gender Is Required";
      }
      if(!$email)
      {
        $errors[] = "Email Is Required";
      }
 
      if(!$answers)
      {
        $errors[] = "Answers Is Required";
      }
      if(!$narrativeSummary)
      {
        $errors[] = "Narrative Summary Is Required";
      }
     
      if(empty($errors))
      {

        /* TO DO's after auth get user_id which is equla to via_surgeon_id and departmentID */

        //$savePatientNarratives->department_id     = Auth::user()->department_id;
        //$savePatientNarratives->via_surgeon_id    = Auth::user()->id;
        if($answers)
        {

           $PatientId = DB::table('patient_details')->insertGetId([
           'title'       =>  $title,
           'first_name'  =>  $firstName,
           'last_name'  =>  $lastName,
           'email'      =>  $email,
           'phone'     =>  $phone,
           'gender'    =>  $gender,
           'narrative_summary'       =>  $narrativeSummary,
           'date_of_birth'=>  $dob,
           'surgeon_id'=>  $surgeon_id,
           'patient_additional_info'       =>  $patient_additional_info,
           'surgeon_id'     =>  $surgeon_id,
           'status'     =>  config('constants.CONSTANT_STATUS_INACTIVE'),
            ]);


          $this->addPatientNarrative($answers,$PatientId);
          if ($isExport == true) 
          {
              $this->mailSent($email,$narrativeSummary);
          }

        }
        

        $response[]  = "Patient Narrative Has Been Saved Successfully";   
      }
    }
    if (!empty($response)) 
    {
        $data["header"]["error"]    = '0';
        $data["header"]["message"]  = "Success";
        $data['body']['details']    = $response;
        return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
    else
    {
        $data["header"]["error"]    = '1';
        $data["header"]["message"]  = $errors;
        return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    } 
  }

  public function addPatientNarrative($answers,$PatientId,$addAnother=0)
  {
    foreach ($answers as $k2 => $answer) 
    {
      $optionData       = $answer['optionData'];
      $complain_type    = $answer['complain_type'];
      $surgeon_id       = $answer['surgeon_id'];
      $primary_complain = $answer['primary_complain'];
      $image_view       = $answer['complainLocationData']['image_view'];
      $image            = $answer['complainLocationData']['image'];
      $coordinate_x     = $answer['complainLocationData']['coordinate_x'];
      $coordinate_y     = $answer['complainLocationData']['coordinate_y'];
      // $narrative_text   = $answer['optionData'][$k2]['narrative_text'];
      //$primary_complain = 0;
      $narrativeSummary = '';
      if ($k2 == 0) 
      {

        $primary_complain = 1;
      }
      if($addAnother)
      {
        $primary_complain = 0;
      }
      $narrativePatientId = DB::table('patient_narratives')->insertGetId([
      
     'patient_id'         =>  $PatientId,
     'complain_type_id'   =>  $complain_type,
     'surgeon_id'         =>  $surgeon_id,
     'status'             =>  config('constants.CONSTANT_STATUS_INACTIVE'),
     'primary_complain'   =>  $primary_complain,
     'narrative_summary'  =>  $narrativeSummary,
     'image_view'         =>  $image_view,
     'coordinate_x'       =>  $coordinate_x,
     'coordinate_y'       =>  $coordinate_y,
      ]);

      if (!empty($optionData)) 
      {
        $narrative_text = array();
        foreach ($optionData as $key => $row) 
        {

            $narrative_text[]     = $row['narrative_text'];
            $required_input_text  = "";
            $required_input       = 0;
            $required_input       = $row['required_input'];
            if($required_input == 1) 
            {
              $required_input_text = $row['required_input_text'];
            }
            DB::table('patient_cheif_complain_answers')->insert([
           'narrative_id'                     =>  $narrativePatientId,
           'patient_cheif_complain_type_id'   =>  $complain_type,
           'question_id'                      =>  $row['question_id'],
           'option_id'                        =>  $row['option_id'],
           'sort_order'                       =>  $row['sort_order'],
           'required_input_text'              =>  $required_input_text,
            ]);
        }

        $narrativeSummary = implode(' ', $narrative_text);

        $updatePatientNarrativeData['narrative_summary']  = $narrativeSummary;
        PatientNarratives::updateOrCreate(['id' => $narrativePatientId]
            ,$updatePatientNarrativeData);
      }
    }
  }

  public function approvedPatientNarratived(Request $request)
  {
      
    $token     = $request['token'];
    $this->CheckAccessToken($token);
    $patientId = @$request['patient_id'];
    if($patientId)
    {
      $patienDetails = PatientDetails::find($patientId);
      $patienDetails->status = config('constants.CONSTANT_STATUS_ACTIVE');
      $patienDetails->save();
      $data["header"]["error"]    = '0';
      $data["header"]["message"]  = "Patient has been approved";
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);

    }
    else
    {
      $data["header"]["error"]    = '1';
      $data["header"]["message"]  = "Invalid Patient ID";
      return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
    }
  }
}
