<?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 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 getQuestionBySearch(Request $request)
    { 
      $searchTerm = $request['search_term'];
      $token     = $request['token'];
      $this->CheckAccessToken($token);

        $questionData  = Questions::where('name','LIKE',"%{$searchTerm}%")->where('status',config('constants.CONSTANT_STATUS_ACTIVE'))->get();
        foreach ($questionData as $key => $row)
        {
          $row->options = QuestionOptions::where('question_id',$row->id)->get();
        }
       
        if (!empty($questionData)) 
        {
            $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 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 pendingPatientNarratives(Request $request)
    { 
      $id = $request['surgeon_id'];
      $offset = @$request['offset'];
      $limit = @$request['limit'];
      if(empty($offset)) 
      { 
          $offset = 0;
      } 
      if(!$id)
      {
        $data["header"]["error"]    = '1';
        $data["header"]["message"]  = "Surgeon Is Required";
        return CommonHelper::response($data, $this->api_log_id, $this->api_start_time);
      }
      $pendingPatientNarratives  = PatientNarratives::where('surgeon_id',$id)->where('status',config('constants.CONSTANT_STATUS_INACTIVE'))->offset($offset)->limit(config('constants.CONSTANT_API_PAGINATION'))->get();
      if (!empty($pendingPatientNarratives)) 
      {
          $data["header"]["error"]    = '0';
          $data["header"]["message"]  = "Success";
          $data['body']['details']    = $pendingPatientNarratives;
          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',$patientNarratives->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; 
            }
          }
      // dd($questionOptions);
          $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 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 addPatientNarrative($answers,$PatientId)
    {
      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;
        }

        $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'],
             'required_input_text'              =>  $required_input_text,
              ]);
          }

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

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


    public function updatePatientNarrative($answers,$narrative_id,$narrativeSummary)
    { 
      $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'];
        $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'];
        //$primary_complain = 0;
        // if ($k2 == 0) 
        // {
        //   $primary_complain = 1;
        // }


       //  $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,
       //  ]);


        // $PatientNarratives = PatientNarratives::find($narrative_id);
        // $PatientNarratives->delete();

        // $patientDetailData['patient_id']          = $PatientId;
        // $patientDetailData['complain_type_id']  = $complain_type;
        // $patientDetailData['surgeon_id']        = $surgeon_id;
        // $patientDetailData['status']            = config('constants.CONSTANT_STATUS_INACTIVE');
        // $patientDetailData['primary_complain']  = $primary_complain;
        // $patientDetailData['narrative_summary'] = $narrativeSummary;
        // $patientDetailData['image_view']        = $image_view;
        // $patientDetailData['coordinate_x']      = $coordinate_x;
        // $patientDetailData['coordinate_y']      = $coordinate_y;
        // $narrativePatientId = PatientNarratives::updateOrCreate(['patient_id' => $PatientId]
        //     ,$patientDetailData);
        




        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'],
           'required_input_text'  =>  $required_input_text,
            ]);

          }
        }
      }
    }

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

        $patientNarratives  = PatientNarratives::find($id);
        $narrativeAnswers   = PatientCheifComplainAnswers::where('narrative_id',$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->selected_option     = $row->option_id;


              $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')->first();
              $row->options      = $questionData ;


            }
          }
              // 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 ($questionData->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();
      $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'];
        // $PatientId = $input['patient_id'];
        $narrative_id = $input['narrative_id'];
        $narrativeSummary = $input['narrative_summary'];
    
        $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->updatePatientNarrative($answers,$narrative_id,$narrativeSummary);

            }
            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);
      } 
    }
}