<?php

namespace App\Http\Controllers\FCControllers;

use Illuminate\Http\Request;
use App\Models\fcmodels\Survey;
use App\Models\fcmodels\Language;
use App\Models\fcmodels\Question;
use App\Models\fcmodels\Option;
use App\Models\fcmodels\Branching;
use App\Models\fcmodels\Response;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use DB;
use Log;
class TheSurveyController extends Controller
{
    //
    public function survey(Request $request)
    {

        date_default_timezone_set("Africa/Nairobi");

        $from =$request->from; #sender of message
        //$from = trim(substr($from,1));
        $to = $request->to; #shortcode receiving the message
        $text = trim($request->text); # message from user
        $text = rtrim($text,".");
        
        //$date2 = date("d/m/Y", $date);
        // $date2 = $date;
        //echo "Date:".$date2;
        $sms2 = "";

        
        $incoming = $text;       
        (int)$first_index = 0;

        if($incoming !='')
        {
            //get survey and customer
            $survcust = Survey::first()->where('shortcode',$to)->where('status',0)->get();
            $org = $survcust[0]->organization_id;
            $survey = $survcust[0]->id;
            $participant_preloaded = $survcust[0]->participant_preloaded;
            $parttable = 'participant_'.$org.'_'.$survey;
            //check participant_preloaded state
            if($participant_preloaded == 'YES')
            {
                //check the participant
                $participant=DB::select("SELECT * from $parttable where phone=$from");
                
            }
            else if($participant_preloaded == 'NO')
            {
                //check the participant
                $participant=DB::select("SELECT * from $parttable where phone=$from");
                // if empty create new
                if(empty($participant))
                {
                    //get text values
                    $text = $from.','.$incoming;
                    $getvals = explode(',',$text);
                    //get table fields
                    $checkarray=count(Schema::getColumnListing($parttable));
                    $tablecolumns1=array_slice(Schema::getColumnListing($parttable),0,$checkarray-4);
                    //get the table columns
                    $tablecolumns=array_slice($tablecolumns1,2);
                    $combine = array_combine($tablecolumns,$getvals);
                    $fields = implode(",",$tablecolumns);
                    //
                    //generate ID
                    $finalID=DB::select("SELECT MAX(id) AS participant_id from $parttable");
                                    
                    $finalid=$finalID[0]->participant_id;
                    if(empty($finalid))
                    {
                        $id = $org.'_'.$survey.'_1';
                    }
                    else
                    {
                        $pid = explode('_',$finalid);
                        $addone = $pid[2]+1;
                        $id = $org.'_'.$survey.'_'.$addone;
                    }
                    $arr = ['id' => $id];
                    
                    $vals = implode('","',array_merge($arr,$getvals));
                    $vals = '"'.$vals.'"';
                    $addid = 'id';
                    $insert=DB::insert("INSERT INTO $parttable($addid,$fields) VALUES ($vals)");
                    //send message to choose language
                    $languages = Language::where('survey_id',$survey)->get();
                    $languages_arr = [];
                    foreach($languages as $language)
                    {
                        $pick = $language->cue." for ".$language->language;
                        array_push($languages_arr,$pick);
                    }
                    $mylanguages = implode("\n",$languages_arr);
                    
                    $this->getToSendMessage($from,urlencode('Please choose a language a language to continue'." Kindly reply with: \n". $mylanguages),$to);
                    die();
                }
                
                
            }
            ///Start process
                if(!empty($participant))
                {
                    $participant_id = $participant[0]->id;
                    $particiantstatus = $participant[0]->status;

                    //update lang selected
                    if($particiantstatus==0){
                        //check language cue
                        $languages = Language::where('cue','LIKE',"%$incoming%")->where('survey_id',$survey)->pluck('id');
                       
                        if($languages->count())
                        {
                            $language = $languages[0];
                        }
                        else
                        {
                            //tell user to reselect language
                            die('Language not found');
                        }
                        
                        $lang=DB::update("UPDATE $parttable SET language='$language' WHERE phone=$from");
                        $mylanguage=$language;
                    }

                    
                    
                    
                    ////////////////////

                    if($particiantstatus==0){
                        //Thank you message
                        $msg="Thank you for registering to submit your comments.";

                        $this->getToSendMessage($from,urlencode($msg),$to);

                        $status=1;

                        $q2=DB::update("UPDATE $parttable SET status='$status' WHERE phone=$from");
                        Log::info($q2);

                    if($q2){
                        
                            //populate questions for the participant
                            $questionr=Question::where('survey_id',$survey)->where('language_id',$mylanguage)->get();
                            
                            $participantid=$participant_id;
                            
                            $initial_questions_array=array();
                            if($questionr->count() > 0){
                            
                                foreach($questionr as $questionsdata){
                                    $initial_questionid=$questionsdata['number'];
                                    array_push( $initial_questions_array,$initial_questionid);
                                }
                                $msg="Thank you for your acceptance to participate in this survey. Kindly respond only once, and as instructed to all questions.";
                                
                                $this->getToSendMessage($from,urlencode($msg),$to);
                                
                                //insert the records for the participant
                                $one=min($initial_questions_array);
                                echo $one;
                                $quizzone = Question::where('survey_id',$survey)->where('language_id',$mylanguage)->where('number',$one)->pluck('id');
                                //check for existence of question any question
                                $allquestionsrow=Response::where('participant_id',$participantid)->get();
                                
                                if(!$allquestionsrow->count()){
                                    
                                    $insert= new Response();
                                    $insert->participant_id = $participantid;
                                    $insert->question_id = $quizzone[0];
                                    $insert->save();
                                    
                                    if($insert){
                                        //select subsequent question
                                        $firstquestion=Question::findOrFail($quizzone[0]);
                                        //check if closed
                                        if($firstquestion['type'] == 'Open')
                                        {
                                            $this->getToSendMessage($from,urlencode($firstquestion['question']),$to);
                                        }
                                        else if($firstquestion['type'] == 'Closed'){
                                            $options = Option::where('question_id',$firstquestion['id'])->get();
                                            $options_arr = [];
                                            foreach($options as $option)
                                            {
                                                $pick = $option->option." ".$option->response;
                                                array_push($options_arr,$pick);
                                            }
                                            $myoptions = implode("\n",$options_arr);
                                            
                                            $this->getToSendMessage($from,urlencode($firstquestion['question']." Please reply with: \n". $myoptions),$to);
                                            Log::info($firstquestion['question']." Please reply with:". $myoptions);
                                        }
                                        
                                    }
                                    else{
                                        die('Failed to add response');
                                    }
                                
                                }
                                else{
                                    die('No Question ');
                                }
                            
                            
                            }
                        
                    }
                    }
                    elseif($particiantstatus==1){

                        //for the first question response
                        $new_string=$incoming;
                        $participantid = $participant_id;
                        //use id1 to get non-responded question
                        $rownonresponded=Response::where('participant_id',$participantid)->where('response',NULL)->first();
                        
                        $responseid=$rownonresponded['id'];
                        $secondquestionid=$rownonresponded['question_id'];
                        
                        ///////get all the questions and check if the question is 3 or more//////////////////////////////
                        $finalarray=DB::select("SELECT MAX(id) AS qid from questions");
                        
                        $finalid=$finalarray[0]->qid;
                        
                        if($secondquestionid==$finalid){
                            $msg="Thank you for your participation. Goodbye";
                            $this->getToSendMessage($from,urlencode($msg),$to);
                        }

                        ///////////////////////////////////////////////////////////////////////////////////
                        $nonr1=Response::where('response', NULL)->where('id',$responseid)->update(['response'=>$incoming]);
                        
                        Log::info($nonr1);
                        if($nonr1){
                            //select the response to retrieve the question id
                            $queryqdata=Response::where('id',$responseid)->first();
                            $questioni_d=$queryqdata['question_id'];
                            $responseid="";
                            //get question details
                            $question = Question::findOrFail($questioni_d);
                            // if QUESTION hs branching
                            if($question['branching'] == 'YES'){
                                //find branching 
                                $branchings = Branching::where('question_id',$question['id'])->where('if',$incoming)->first();
                                
                                if(!empty($branchings)){
                                    $nextquiz=$branchings['next'];
                                    $secondquestionr = Question::where('survey_id',$survey)->where('language_id',$participant[0]->language)->where('number',$nextquiz)->get();
                                    
                                    $second_initial_questions_array=array();
                                    if($secondquestionr->count() > 0){
                                    
                                        $seondquestionsdata=$secondquestionr;
                                        //insert the second question
                                        //insert the records for the participant
                                        $two=$seondquestionsdata[0]->id;
                                        //2,3,4
                                        //check if question already exists
                                        $checkquery = Response::where('participant_id',$participantid)->where('question_id',$two)->get();
                                        
                                        if($checkquery->count() ==0)
                                        {
                                            $rinserttwo=DB::insert("INSERT INTO responses(participant_id,question_id,response) VALUES('$participantid','$two',NULL)");
                                            
                                            if($rinserttwo){
                                                //send question one-call the send function
                                                //select the question
                                                $row_2questionr=Question::findOrFail($two);
                                                if($row_2questionr['type'] == 'Open')
                                                {
                                                    $this->getToSendMessage($from,urlencode($row_2questionr['question']),$to);
                                                }
                                                else if($row_2questionr['type'] == 'Closed'){
                                                    $options = Option::where('question_id',$row_2questionr['id'])->get();
                                                    $options_arr = [];
                                                    foreach($options as $option)
                                                    {
                                                        $pick = $option->option." ".$option->response;
                                                        array_push($options_arr,$pick);
                                                    }
                                                    $myoptions = implode("\n",$options_arr);
                                                    
                                                    $this->getToSendMessage($from,urlencode($row_2questionr['question']." Please reply with: \n". $myoptions),$to);
                                                }
                                            }
                                            else{
                                                //already sent
                                            }
                                        } 
                                        else{
                                        }
                                    
                                    }
                                }
                                else
                                {
                                    $branchings = Branching::where('question_id',$question['id'])->where('if','*')->first();
                                    Log::info($branchings['if']);
                                    if(!empty($branchings)){
                                    //
                                        $nextquiz=$branchings['next'];
                                        $secondquestionr = Question::where('survey_id',$survey)->where('language_id',$participant[0]->language)->where('number',$nextquiz)->get();
                                        
                                        $second_initial_questions_array=array();
                                        if($secondquestionr->count() > 0){
                                        
                                            $seondquestionsdata=$secondquestionr;
                                            //insert the second question
                                            //insert the records for the participant
                                            $two=$seondquestionsdata[0]->id;
                                            //2,3,4
                                            //check if question already exists
                                            $checkquery = Response::where('participant_id',$participantid)->where('question_id',$two)->get();
                                            
                                            if($checkquery->count() ==0)
                                            {
                                                $rinserttwo=DB::insert("INSERT INTO responses(participant_id,question_id,response) VALUES('$participantid','$two',NULL)");
                                                
                                                if($rinserttwo){
                                                    //send question one-call the send function
                                                    //select the question
                                                    $row_2questionr=Question::findOrFail($two);
                                                    if($row_2questionr['type'] == 'Open')
                                                    {
                                                        $this->getToSendMessage($from,urlencode($row_2questionr['question']),$to);
                                                    }
                                                    else if($row_2questionr['type'] == 'Closed'){
                                                        $options = Option::where('question_id',$row_2questionr['id'])->get();
                                                        $options_arr = [];
                                                        foreach($options as $option)
                                                        {
                                                            $pick = $option->option." ".$option->response;
                                                            array_push($options_arr,$pick);
                                                        }
                                                        $myoptions = implode("\n",$options_arr);
                                                        
                                                        $this->getToSendMessage($from,urlencode($row_2questionr['question']." Please reply with: \n". $myoptions),$to);
                                                    }
                                                }
                                                else{
                                                    //already sent
                                                }
                                            } 
                                            else{
                                            }
                                        
                                        }
                                    }
                                    else
                                    {
                                        $nextquiz=$question['number']+1;
                                        $secondquestionr = Question::where('survey_id',$survey)->where('language_id',$participant[0]->language)->where('number',$nextquiz)->get();
                                        
                                        $second_initial_questions_array=array();
                                        if($secondquestionr->count() > 0){
                                        
                                            $seondquestionsdata=$secondquestionr;
                                            //insert the second question
                                            //insert the records for the participant
                                            $two=$seondquestionsdata[0]->id;
                                            //2,3,4
                                            //check if question already exists
                                            $checkquery = Response::where('participant_id',$participantid)->where('question_id',$two)->get();
                                            
                                            if($checkquery->count() ==0)
                                            {
                                                $rinserttwo=DB::insert("INSERT INTO responses(participant_id,question_id,response) VALUES('$participantid','$two',NULL)");
                                                
                                                if($rinserttwo){
                                                    //send question one-call the send function
                                                    //select the question
                                                    $row_2questionr=Question::findOrFail($two);
                                                    
                                                    if($row_2questionr['type'] == 'Open')
                                                    {
                                                        $this->getToSendMessage($from,urlencode($row_2questionr['question']),$to);
                                                    }
                                                    else if($row_2questionr['type'] == 'Closed'){
                                                        $options = Option::where('question_id',$row_2questionr['id'])->get();
                                                        $options_arr = [];
                                                        foreach($options as $option)
                                                        {
                                                            $pick = $option->option." ".$option->response;
                                                            array_push($options_arr,$pick);
                                                        }
                                                        $myoptions = implode("\n",$options_arr);
                                                        
                                                        $this->getToSendMessage($from,urlencode($row_2questionr['question']." Please reply with: \n". $myoptions),$to);
                                                    }
                                                }
                                                else{
                                                    //already sent
                                                }
                                            } 
                                            else{
                                            }
                                        
                                        }
                                           
                                        }
                                    }
                                }
                                        else
                                        {
                                            //
                                            $nextquiz=$question['number']+1;
                                            $secondquestionr = Question::where('survey_id',$survey)->where('language_id',$participant[0]->language)->where('number',$nextquiz)->get();
                                            
                                            $second_initial_questions_array=array();
                                            if($secondquestionr->count() > 0){
                                            
                                                $seondquestionsdata=$secondquestionr;
                                                //insert the second question
                                                //insert the records for the participant
                                                $two=$seondquestionsdata[0]->id;
                                                //2,3,4
                                                //check if question already exists
                                                $checkquery = Response::where('participant_id',$participantid)->where('question_id',$two)->get();
                                                
                                                if($checkquery->count() ==0)
                                                {
                                                    $rinserttwo=DB::insert("INSERT INTO responses(participant_id,question_id,response) VALUES('$participantid','$two',NULL)");
                                                    
                                                    if($rinserttwo){
                                                        //send question one-call the send function
                                                        //select the question
                                                        $row_2questionr=Question::findOrFail($two);
                                                            if($row_2questionr['type'] == 'Open')
                                                            {
                                                                $this->getToSendMessage($from,urlencode($row_2questionr['question']),$to);
                                                            }
                                                            else if($row_2questionr['type'] == 'Closed'){
                                                                $options = Option::where('question_id',$row_2questionr['id'])->get();
                                                                $options_arr = [];
                                                                foreach($options as $option)
                                                                {
                                                                    $pick = $option->option." ".$option->response;
                                                                    array_push($options_arr,$pick);
                                                                }
                                                                $myoptions = implode("\n",$options_arr);
                                                                
                                                                $this->getToSendMessage($from,urlencode($row_2questionr['question']." Please reply with: \n". $myoptions),$to);
                                                            }
                                                        
                                                    }
                                                    else{
                                                        //already sent
                                                    }
                                                } 
                                                else{
                                                }
                                            
                                            }
                                        }
                                    }
                                

                        }

                    }
                    ////////////////////
                }

            }
        
    
    //send  sms
    public function getToSendMessage($dest,$question,$to)
	{
	   // Log::info($question);
        $username = "demo1";
        $pass='$mob1d3m01$';
        $dest=$dest;//"+254708058225";//$dest;
        $msg=$question;//"test";//$question;
        $source=$to;
        //$postvalues = 'username='.$username.'&password='.$pass.'&destination='.$dest.'&message='.$msg.'&source='.$source;
    	$postvalues = 'username='.$username.'&password='.$pass.'&destination='.$dest.'&message='.$msg.'&shortcode='.$source;
    	
    // 	$url = "http://mobisky.biz/api/sendsms2former.php?$postvalues";
    	$url="http://www.mobisky.biz/api/mobisendsms.php?$postvalues";
    	$there = $url.$postvalues;
	
    	//redirect to api
		$curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, "$url");
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($curl);
	}
}
