<?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\PatientNarratives;
use App\Models\PatientCheifComplainAnswers;


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::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'];
        $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();
        }
        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'];
        $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();
      // dd($input);
      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'];
        $complainTypes  = $input['complain_types'];
        $patient_additional_info  = $input['patient_additional_info'];
        $surgeon_id     = $input['surgeon_id'];
        $narrativeSummary = $input['narrative_summary'];
        $image_view     = $input['image_view'];
        $coordinate_x   = $input['coordinate_x'];
        $coordinate_y   = $input['coordinate_y'];
        $answers        = $input['answers'];
        $day            = '2';
        $duration            = 'week';
        $pateint_experience = $day.'-'.$duration;//$input['pateint_experience'];

        
          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(!$surgeon_id)
          {
            $errors[] = "Surgeon Is Required";
          }
          if(!$complainTypes)
          {
            $errors[] = "Complain Types Is Required";
          }
          if(!$answers)
          {
            $errors[] = "Answers Is Required";
          }
          if(!$narrativeSummary)
          {
            $errors[] = "Narrative Summary Is Required";
          }
          if(!$image_view)
          {
            $errors[] = "Image view  Is Required";
          } 
          if(!$coordinate_x)
          {
            $errors[] = "Coordinate X Is Required";
          }
          if(!$coordinate_y)
          {
            $errors[] = "Coordinate Y 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)
            {

              foreach ($answers as $k2 => $answer) 
              {
 
                $narrativePatientId = DB::table('patient_narratives')->insertGetId([
               'title'       =>  $title,
               'first_name'  =>  $firstName,
               'last_name'  =>  $lastName,
               'email'      =>  $email,
               'phone'     =>  $phone,
               'gender'    =>  $gender,
               'date_of_birth'=>  $dob,
               'complain_type_id'  =>  $complainTypes,
               'surgeon_id'     =>  $surgeon_id,
               'status'       =>  config('constants.CONSTANT_STATUS_INACTIVE'),
               'narrative_summary'       =>  $narrativeSummary,
               'image_view'       =>  $image_view,
               //'pateint_experience'       =>  $pateint_experience,
               'patient_additional_info'       =>  $patient_additional_info,
               'coordinate_x'       =>  $coordinate_x,
               'coordinate_y'      =>  $coordinate_y,
                ]);
                foreach ($answer as $key => $row) 
                {
                    DB::table('patient_cheif_complain_answers')->insert([
                   'narrative_id'       =>  $narrativePatientId,
                   'patient_cheif_complain_type_id'       =>  $complainTypes,
                   'question_id'  =>  $row['question_id'],
                   'option_id'  =>  $row['option_id'],
                    ]);
                }

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

            $response[$key]  = "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)
    { 
      $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();
        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';
  }
}