<?php

namespace App\Http\Controllers;

use App\Models\CampaignEmails;
use App\Models\Candidate;
use App\Models\CandidateDetail;
use App\Models\CandidateEducation;
use App\Models\CandidateOperationalSkill;
use App\Models\CandidateSkill;
use App\Models\CandidateSkillset;
use App\Models\CandidateSoftSkill;
use App\Models\CandidateVideoInterviews;
use App\Models\EducationCity;
use App\Models\EducationQualification;
use App\Models\PrimaryEducation;
use App\Models\Question;
use App\Models\QuestionAnswer;
use App\Models\Role;
use App\Models\RoleQuestions;
use App\Models\RoleQuestionsAnswers;
use App\Models\SkillBlockResume;
use App\Models\SkillblockTemp;
use App\Models\VideoInterviewCategories;
use App\Models\VideoInterviewCategoriesVideos;
use DB;

//use JWTAuth;
use App\Models\User;
use App\Models\CandidateExperiences;
use App\Models\CandidateSkillsets;
use App\Models\SoftSkills;
use App\Models\CandidateSkills;
use App\Models\CandidateNotecs;
use App\Models\CandidateOperationalSkills;
use App\Models\CandidateSoftSkills;
use App\Models\CandidateEducations;
use App\Models\CandidateDetails;
use App\Models\SegregatedSkill;
use App\Models\Introduction_content;
use App\Models\Introduction_desc;
//use Request;
use Illuminate\Http\Request;

//use Request;

//use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Session;
use Symfony\Component\Console\Input\Input;

class UserController extends Controller
{
    public function __construct()
    {
    }
	
    public function index(Request $request, $step = '')
    {
        if (empty($request->session()->get('verify'))) {
            return redirect()->route('startnow');
        }
		
        if ($step != '') {
            switch ($step) {
                case 'step1':
					
					$offset = $request->page *2;
					$noOfrec = count(DB::select("select * from introduction_descs"));
					$noOfPage = ceil($noOfrec/2)-1;
					if(empty($request->page)) {
						$data['step'] = "step1?page=1";
						$data['prev'] = "";
					} else if($request->page && $noOfPage > $request->page) {
						$data['step'] = "step1?page=".($request->page+1);
						$data['prev'] = "step1?page=".($request->page-1);	
					} else {
						$data['step'] = "step3";
						$data['prev'] = "step1?page=".($request->page-1);
					}
					$sql="select * from introduction_descs order by id limit $offset,2";
					$description = DB::select($sql);
					$data['description'] = $description;
					
                    return view('steps/' . $step, $data);
                    break;
                case 'step2':
					$data['introInfo'] = Introduction_content::with('description')->get()->toArray();
                    return view('steps/' . $step, $data);
                    break;
                case 'step3':
                    $roleInfo = Role::get();
					$noOfrec = count(DB::select("select * from introduction_descs"));
					$noOfPage = ceil($noOfrec/2);
					$prev = "step1?page=".($noOfPage-1);
                    return view('steps/' . $step, ['roleInfo' => $roleInfo, 'prev'=>$prev]);
                    break;
                case 'step4':
                    $role = $request->role;
                    $roleInfo = Role::where('id', $role)->first();
                    return view('steps/' . $step, ['role' => $roleInfo]);
                    break;
                case 'step5':
                    $role = $request->role;
                    $roleInfo = Role::where('id', $role)->first();
                    return view('steps/' . $step, ['role' => $roleInfo]);
                    break;
                case 'step6':
                    $role = $request->role;
                    $roleInfo = Role::where('id', $role)->first();
                    return view('steps/' . $step, ['role' => $roleInfo]);
                    break;
                case 'step7':
                    if (Auth::check()) {
                        $user = Auth::user();
                        return redirect('user_info/' . base64_encode($user->email) . '/' . base64_encode($user->id));
                    }
                    $role = $request->role;
                    return view('steps/' . $step, ['role' => $role]);
                    break;

            }
        } else {
			
			$introInfo = DB::select("select * from introduction_contents order by id desc limit 1");
			$data['title']= $introInfo[0]->title;
			$data['video_url']= $introInfo[0]->video_url;
            return view('index', $data);
        }

    }

    public function signup(Request $req)
    {
        $role_id = $req->input('role_id');
        return view('signup', ['role_id' => $role_id]);
    }

    public function saveCategoryVideoSort(Request $request)
    {

        $sortcatsLists = $request->postdata;

        if (count($sortcatsLists) > 0) {
            foreach ($sortcatsLists as $sortcatsList) {
                list($catsId, $sortId) = explode(',', $sortcatsList);

//                dd($catsId);
                $catsData = VideoInterviewCategories::where('id', $catsId)->orderBy('sort_no', 'asc')->first();


                $catsData->update(['sort_no' => $sortId]);
            }
        }

        return true;

    }

    public function user_register(Request $request)
    {


        $this->validate($request, [
            'email' => 'required|email',
            'mobile' => 'required|min:10',
            'country_code' => 'required'
        ]);

        $userInfo = User::where('email', $request->email)->first();

        $cemailInfo = CampaignEmails::where('email_id', $request->email)->first();
        if (empty($cemailInfo)) {
            return redirect()->route('startnow');
        } else {
            if ($cemailInfo->flag == 0) {
                return redirect()->route('startnow');
            }
        }

        if (!$userInfo) {
            $verificationCode = str_random(20);
            $user = new User();
            $user->mobile = trim($request->mobile);
            $user->country_code = trim($request->country_code);
            $user->email = trim(strtolower($request->email));
            $user->role_id = $request->role_id;
            $user->password = Hash::make('123456789');
//            $user->password = Hash::make('1234567878');
            $user->save();
            $user_id = $user->id;

            $record = CampaignEmails::where(['email_id' => $user->email, 'flag' => 1])->first();
            if (!empty($record)) {
                $updateData = array();
                $updateData['user_id'] = $user_id;
                $record->update($updateData);
            }

            $redirect = 'user_info/' . base64_encode($request->email) . '/' . base64_encode($user_id);

        } else {

            $user_id = $userInfo->id;
            if ($userInfo->role_id == 404) {
                return redirect()->route('home');
            }
            if ($userInfo->flag == 1) {
                $redirect = 'thanks_you/' . base64_encode($userInfo->email) . '/' . base64_encode($userInfo->id);

//            } elseif ($userInfo->flag == 2) {
//                $redirect ='not_suitable/' . base64_encode($userInfo->email) . '/' . base64_encode($userInfo->id);
//
//
            } else {
                $redirect = 'user_info/' . base64_encode($userInfo->email) . '/' . base64_encode($userInfo->id);

            }


        }
        $loginData = Auth::loginUsingId($user_id);

        return redirect($redirect);
    }

    public function interview_questions($email, $user_id)
    {
        if (checkvalidUser($user_id) == 1) {
            return redirect()->route('home');
        } elseif (checkvalidUser($user_id) == 2) {
            $userInfo = User::where('id', base64_decode($user_id))->first();
            return redirect(route('home', ['steps' => 'step7']) . "?role=" . $userInfo->role_id);

        } elseif (checkvalidUser($user_id) == 3) {
            return redirect()->route('home');
        }

        $loginData = Auth::loginUsingId(base64_decode($user_id));

        if ($loginData->name != '') {
            return redirect('interview_questions/' . $email . '/' . $user_id);

        }
        return view('user_info', ['email' => base64_decode($email), 'user_id' => base64_decode($user_id)]);
    }

    public function user_information(Request $request)
    {

        $request->session()->put('name', $request->name);

        $user = Auth::user();
        $user->name = $request->name;
        $user->save();

        return redirect('interview_questions/' . base64_encode($request->email) . '/' . base64_encode($request->user_id));
    }

    public function interview_all_questions($email, $user_id, $id = '')
    {

        if (checkvalidUser($user_id) == 1) {
            return redirect()->route('home');
        } elseif (checkvalidUser($user_id) == 2) {
            $userInfo = User::where('id', base64_decode($user_id))->first();
            return redirect(route('home', ['steps' => 'step7']) . "?role=" . $userInfo->role_id);

        } elseif (checkvalidUser($user_id) == 3) {
            return redirect()->route('home');
        }

        $educationInfo = "";
        if (empty($id)) {

            $questionInfo = Question::limit(1)->get();

            $question = QuestionAnswer::where([
                'ques_id' => $questionInfo[0]->id,
                'user_id' => base64_decode($user_id)
            ])->first();


            if (!empty($question)) {

                $nextquestion = Question::where('id', '>', $questionInfo[0]->id)->orderBy('id', 'asc')->first();
                if (empty($nextquestion)) {
                    $questions = RoleQuestions::where('role_id', (Auth::user()->role_id))->first();

                    if (!empty($questions)) {
                        return redirect('role_questions/' . $email . '/' . $user_id . '/' . base64_encode($questions->id));
                    } else {
                        $categories = VideoInterviewCategories::orderBy('sort_no', 'asc')->first();

                        if (!empty($categories)) {
                            return redirect('categories/' . base64_decode($email) . '/' . $user_id . '/' . base64_encode($categories->id));
                        }

                        return redirect('thanks_you/' . $email . '/' . $user_id);
                    }
                }
                return redirect('interview_questions/' . $email . '/' . $user_id . '/' . base64_encode($nextquestion->id));
            } else {

            }

        } else {
            $questionInfo = Question::where('id', base64_decode($id))->get();


            $question = QuestionAnswer::where([
                'ques_id' => $questionInfo[0]->id,
                'user_id' => base64_decode($user_id)
            ])->first();

            if (!empty($question)) {


                $nextquestion = Question::where('id', '>', $questionInfo[0]->id)->orderBy('id', 'asc')->first();

                if (empty($nextquestion)) {

                    $questions = RoleQuestions::where('role_id', (Auth::user()->role_id))->first();

                    if (!empty($questions)) {
                        return redirect('role_questions/' . $email . '/' . $user_id . '/' . base64_encode($questions->id));
                    } else {
                        $categories = VideoInterviewCategories::orderBy('sort_no', 'asc')->first();

                        if (!empty($categories)) {
                            return redirect('categories/' . base64_decode($email) . '/' . $user_id . '/' . base64_encode($categories->id));
                        }

                        return redirect('thanks_you/' . $email . '/' . $user_id);
                    }

                } else {
                    return redirect('interview_questions/' . $email . '/' . $user_id . '/' . base64_encode($nextquestion->id));

                }


            } else {
                if (isset($questionInfo[0]) && $questionInfo[0]->flag == 2) {
                    $educationInfo = PrimaryEducation::get();
                }
                if (isset($questionInfo[0]) && $questionInfo[0]->flag == 6 || $questionInfo[0]->flag == 9) {
                    $educationInfo = EducationCity::get();
                }
                if (isset($questionInfo[0]) && $questionInfo[0]->flag == 3) {
                    $educationInfo = EducationQualification::get();
                }
            }


        }

//        dd($user_id);
//        dd($id);
//        dd($questionInfo);

        //print_r($educationInfo); exit;

        $data = array();
        $data['questionInfo'] = $questionInfo;
        $data['user_id'] = base64_decode($user_id);
        $data['email'] = base64_decode($email);
        $data['educationInfo'] = $educationInfo;


//        dd($data);


        return view('interview_questions', $data);
    }

    public function save_question(Request $req)
    {

        $user_id = $req->user_id;
        $ques_id = $req->ques_id;
        $options = $req->options;
        $email = $req->email;
        $QuestionAnswerArray = array();
        $QuestionAnswerArray['ques_id'] = $ques_id;
        $QuestionAnswerArray['user_id'] = $user_id;
        $QuestionAnswerArray['answer'] = $options;

        $questionInfo = QuestionAnswer::where([
            'ques_id' => $ques_id,
            'user_id' => $user_id
        ])->first();


        if (empty($questionInfo)) {
            if ($options == 9 || $options == 102) {

            } else {
                QuestionAnswer::create($QuestionAnswerArray);

            }
        }


        if ($ques_id == 1 && $options == "No") {
            $role = User::where('id', $user_id)->first()->role_id;
            $url = route('home', ['steps' => 'step4']) . "?role=" . $role;
            return redirect($url);
        } else {


            $nextquestion = Question::where('id', '>', $ques_id)->orderBy('id', 'asc')->first();

            if ($options == 9 || $options == 102) {
                return redirect('not_suitable/' . base64_encode($email) . '/' . base64_encode($user_id));
            }
            return redirect('interview_questions/' . base64_encode($email) . '/' . base64_encode($user_id) . '/' . base64_encode(($nextquestion->id)));

        }
    }

    public function send_otp(Request $req)
    {

        $otp = rand(0, 100000);
        Session::put('mobile_otp', $otp);
        Session::save();
        $mobile_number = $req->mobile_number;
//        echo Session::get('mobile_otp');exit;
        $ch = curl_init();
        $user = "kv@hirextra.com";
        $password = "hirextra";
        $receipientno = '91' . $mobile_number;
        $originator = "HireXtra";
        $msgtxt = "OTP for your mobile number is " . $otp . " .";
        curl_setopt($ch, CURLOPT_URL, "http://app.mobivatebulksms.com/gateway/api/simple/MT?");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, "USER_NAME=$user&PASSWORD=$password&ORIGINATOR=$originator&RECIPIENT=$receipientno&ROUTE=mglobal&MESSAGE_TEXT=$msgtxt");
        $buffer = curl_exec($ch);
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        echo '1';
        exit;
    }

    public function save_mobile_number(Request $req)
    {
        $user_id = $req->user_id;
        $ques_id = $req->ques_id;
        $country_code = $req->country_code;
        $mobile_number = $req->mobile_number;
        $mobile_otp = $req->mobile_otp;
        $email = $req->email;
        if (Session::get('mobile_otp') != $mobile_otp) {
            return redirect('interview_questions/' . base64_encode($email) . '/' . base64_encode($user_id) . '/' . base64_encode($ques_id) . '?error=1');
        }


        $QuestionAnswerArray = array();
        $QuestionAnswerArray['ques_id'] = $ques_id;
        $QuestionAnswerArray['user_id'] = $user_id;
        $QuestionAnswerArray['answer'] = $country_code . '-' . $mobile_number;


        QuestionAnswer::create($QuestionAnswerArray);

        return redirect('interview_questions/' . base64_encode($email) . '/' . base64_encode($user_id) . '/' . base64_encode(($ques_id + 1)));
    }

    public function upload_resume(Request $req)
    {
        ini_set("memory_limit", "10056M");
        ini_set('max_execution_time', -1);


        $jsonResult = null;
        $APIURL = "http://hirextra8.rchilli.com/RChilliParser/Rchilli/parseResumeBinary";
        try {
            $file = $req->file;//Input::file('file');
            //$description=Input::get('description');
            $assetId = null;
            $imagedata = file_get_contents($file);
            $base64 = base64_encode($imagedata);
            $key = 'Y0CPAOKBPGW';
            $version = "8.0.0";
            $subUserId = "Hirextra8";
            $data = array(
                "filedata" => $base64,
                "filename" => $file->getClientOriginalName(),
                "userkey" => $key,
                "version" => $version,
                "subuserid" => $subUserId
            );
            $str_data = json_encode($data);
            $ch = curl_init($APIURL);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POSTFIELDS, $str_data);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    'Content-Type: application/json',
                    'Content-Length: ' . strlen($str_data))
            );
            $jsonResult = curl_exec($ch); //Assign rchilli response to a variable

        } //try
        catch (Exception $e) {
            echo 'Caught exception: ', $e->getMessage(), "\n";
        } //catch

        // echo 'RESUME DATA:'; print_r($jsonResult);exit;
        $jsonResult = json_decode($jsonResult, true);


        if (!empty($jsonResult) && !isset($jsonResult['error'])) {


            $json = $jsonResult["ResumeParserData"];
            //print_r($json);exit;
            $fullname = 0;
            if (!empty($json['Name']['FullName'])) {
                $fullname = $json['Name']['FullName'];
            }
            $location = 0;
            if (!empty($json['SegregatedQualification'][3]['Institution']['Location']['City'])) {
                $location = $json['SegregatedQualification'][3]['Institution']['Location']['City'];
            }
            $summary = 0;
            if (!empty($json['Summary'])) {
                $summary = $json['Summary'];
            }
            $email = 0;
            if (!empty($json['Email'][0]['EmailAddress'])) {
                $email = $json['Email'][0]['EmailAddress'];
            }
            $mobile = 0;
            if (!empty($json["PhoneNumber"][0]["Number"])) {
                $mobile = $json["PhoneNumber"][0]["Number"];
            }
            $country_code = 0;
            if (!empty($json['ResumeCountry']['CountryCode']['IsoAlpha2'])) {
                $country_code = $json['ResumeCountry']['CountryCode']['IsoAlpha2'];
            }

            $SkillSet = $json["SegregatedSkill"];

            $operationalSkills = null;
            $softSkills = null;
            $operationalSkills = null;
            //concatenate all the skills and assign to a variable.
            $skillsData = array();
            foreach ($SkillSet as $skill) {
                $skillsData[] = $skill["Skill"];
            }
            $skillsDataStr = implode(',', $skillsData);
            $summary = '';
            $expe = (string)$json["WorkedPeriod"]["TotalExperienceInYear"];
            $Email = $json["Email"];
            $EmailAddress = "";
            if (is_array($Email) && count($Email) > 0) {
                $EmailAddress = $Email[0]['EmailAddress'];

                if (empty($EmailAddress)) {
                    $EmailAddress = $json["Email"];
                }
            }
            $asset_create_response = null;
            if ($req->hasFile('file')) {
                $files = array();
                $files = $req->file;
                $i = 0;
                if ($i == 0) {
                    $file_name = $files->getClientOriginalName();
                    $file_type = $files->getClientMimeType();
                    $path = base_path() . "/public/user_assets";
                    $destinationPath = 'user_assets';
                    $url = "/user_assets";
                    $files->move($destinationPath, $files->getClientOriginalName());
                }
                $assetId = "0";  // Assign Id of asset

            }
            $summary = '';
            $executiveSummary = null;
            $managementSummary = null;
            if ($json["Summary"]) {
                $summary = (string)$json["Summary"];
            } elseif ($json["ExecutiveSummary"]) {
                $executiveSummary = (string)$json["ExecutiveSummary"];
            } elseif ($json["ManagementSummary"]) {
                $managementSummary = (string)$json["ManagementSummary"];
            }
            $executiveSummary = (string)$json["ExecutiveSummary"];
            $managementSummary = (string)$json["ManagementSummary"];

            if ($json["DateOfBirth"]) {
                $Dob = str_replace('/', '-', $json["DateOfBirth"]); //Replace '/' with '-'
            }
            if ($json["PhoneNumber"]) {
                $country_code = $json["PhoneNumber"][0]["ISDCode"];
            } else {
                $country_code = "";
            }
            //print_r($json); exit;
            if ($json["CurrentLocation"]) {
                $curentlocation = $json["CurrentLocation"][0]["City"] . ", " . $json["CurrentLocation"][0]["State"] . ", " . $json["CurrentLocation"][0]["Country"];
            } else {
                $curentlocation = "";
            }
            if ($json["PreferredLocation"]) {
                $PreferredLocation = $json["PreferredLocation"];
            } else {
                $PreferredLocation = "";
            }
            $alternate_email = "";
            if ($json["Email"]) {
                $email_new = $json["Email"][0]["EmailAddress"];
            } else {
                $email = "";
            }
            if ($json["PhoneNumber"]) {
                $mobile_new = $json["PhoneNumber"][0]["Number"];
            } else {
                $mobile_new = "";
            }

            $languages_known = "";
            foreach ($json["LanguageKnown"] as $recomondation) {
                if (strlen($languages_known) > 0) {
                    $languages_known = $languages_known . ', ';
                }
                $languages_known = $languages_known . $recomondation["Language"];
            }

            if ((string)$json["WorkedPeriod"]["TotalExperienceInYear"] == '' || (string)$json["WorkedPeriod"]["TotalExperienceInYear"] == null) {
                $tot_exp = 0;
            } else {
                $tot_exp = (string)$json["WorkedPeriod"]["TotalExperienceInYear"];
            }
            //Insert candidate record

            if (!empty($fullname)) {
                $candidate = Candidate::create([
                    'full_name' => (string)$fullname,
                    'email' => (string)$email,
                    'phone' => (string)$mobile,
                    'mobile' => (string)$mobile,
                    'country_code' => (string)$country_code,
                    // 'date_of_birth' =>  (!empty($json["DateOfBirth"])) ? date('Y-m-d', strtotime($Dob)) : '',
                    //'gender' => (isset($json["Gender"])) ? $json["Gender"] : "Male",
                    'job_profile' => (string)$json["JobProfile"],
                    'address' => (string)$json["Address"][0]["State"],
                    'city' => (string)$json["Address"][0]["City"],
                    'state' => (string)$json["Address"][0]["State"],
                    'country' => (string)$json["Address"][0]["Country"],
                    'zip' => (string)$json["Address"][0]["ZipCode"],
                    'current_salary' => (string)$json["CurrentSalary"]["Amount"],
                    'expected_salary' => (string)$json["ExpectedSalary"]["Amount"],
                    'total_experience_in_year' => $tot_exp,
                    'asset_id' => $assetId,
                    'vendor_id' => $req->user_id,
                    'vendor_user_id' => $req->user_id,
                    'summary' => $summary,
                    'path' => $path,
                    'title' => (string)$json["Name"]["TitleName"],
                    'first_name' => (string)$json["Name"]["FirstName"],
                    'middle_name' => (string)$json["Name"]["MiddleName"],
                    'last_name' => (string)$json["Name"]["LastName"],
                    'father_name' => (string)$json["FatherName"],
                    'mother_name' => (string)$json["MotherName"],
                    'marital_status' => (string)$json["MaritalStatus"],
                    'nationality' => (string)$json["Nationality"],
                    'language_known' => (string)$languages_known,
                    'unique_id' => (string)$json["UniqueID"],
                    'license_no' => (string)$json["LicenseNo"],
                    'passport_no' => (string)$json["PassportDetail"]["PassportNumber"],
                    'pan_no' => (string)$json["PanNo"],
                    'visa_status' => (string)$json["VisaStatus"],
                    'alternate_email' => (string)$alternate_email,
                    'cover_letter' => (string)$json["Coverletter"],
                    'certification' => (string)$json["Certification"],
                    'publication' => (string)$json["Publication"],
                    'current_location' => (string)$curentlocation,
                    'preferred_location' => (string)$PreferredLocation,
                    'availability' => (string)$json["Availability"],
                    'objectives' => (string)$json["Objectives"],
                    'candidate_references' => (string)$json["References"],
                    'parsing_date' => (string)$json["ParsingDate"],
                    'resume_language' => (string)$json["ResumeLanguage"]["Language"],
                    'resume_file_name' => (string)$json["ResumeFileName"],
                    'formatted_address' => (string)$json["Address"][0]["FormattedAddress"],
                    'industry_category' => (string)$json["Category"],
                    'industry_sub_category' => (string)$json["SubCategory"],
                    'executive_summary' => $executiveSummary,
                    'management_summary' => $managementSummary,
                    'hobbies' => $json['Hobbies'],
                    'candidate_achievements' => $json['Achievements'],
                    'html_code' => $json['HtmlResume'],
                    'note' => '',
                ]);
                $candidate_skills = CandidateSkill::create([
                    'skills' => (string)$json["SkillKeywords"],
                    'candidate_id' => $candidate->id,
                ]);
                $candidate_skill = CandidateSkillset::create([
                    'skill_set' => $skillsDataStr,
                    'candidate_id' => $candidate->id,
                ]);
                $SkillBlock = $json["SkillKeywords"];
                $SkillBlock = preg_replace('/\s{3}/', '~', $SkillBlock);
                $skillsResumes = explode('~', $SkillBlock);
                if (is_array($skillsResumes) && count($skillsResumes) > 0) {
                    foreach ($skillsResumes as $skills) {

                        $skillArr = explode(':', $skills);
                        if (!empty($skillArr[1])) {

                            $SkillBlockResumeArray = array();
                            $SkillBlockResumeArray['candidate_id'] = $candidate->id;
                            $SkillBlockResumeArray['keyword'] = addslashes($skillArr[0]);
                            $SkillBlockResumeArray['skill_value'] = addslashes($skillArr[1]);
                            $SkillBlockResumeArray['found_id'] = 1;
                            SkillBlockResume::create($SkillBlockResumeArray);

                        } else {

                            $SkillBlock = preg_replace('/[\r,]/', '~', $skills);
                            $SkillBlock = preg_replace('/[~]+/', '~', $SkillBlock);
                            $SkillBlockArr = explode('~', $SkillBlock);
                            $skillName = array();
                            $skillValue = array();

                            foreach ($SkillBlockArr as $key => $value) {
                                if (!empty($value)) {
                                    $sql = "select s.skill_name, sv.skillblock_keywords from skill_block_values as sv inner join skill_blocks as s on sv.skillblock_id = s.id where skillblock_keywords like'%" . addslashes($value) . "%'";

                                    $skillInfo = DB::select($sql);
                                    if (is_array($skillInfo) && count($skillInfo) > 0) {

                                        SkillblockTemp::create([
                                            'keyword' => $skillInfo[0]->skill_name,
                                            'value' => addslashes($skillInfo[0]->skillblock_keywords),
                                        ]);


                                    } else {
                                        SkillblockTemp::create([
                                            'keyword' => 'skills',
                                            'value' => addslashes($value),
                                        ]);


                                    }
                                }
                            }
                        }
                    }
                }

                $SkillBlock = $json["SkillBlock"];

                $SkillBlock = preg_replace('/\s{3}/', '~', $SkillBlock);
                $skillsResumes = explode('~', $SkillBlock);
                if (is_array($skillsResumes) && count($skillsResumes) > 0) {
                    foreach ($skillsResumes as $skills) {

                        $skillArr = explode(':', $skills);
                        if (!empty($skillArr[1])) {

                            SkillBlockResume::create([
                                'candidate_id' => $candidate->id,
                                'keyword' => addslashes($skillArr[0]),
                                'skill_value' => addslashes($skillArr[1]),
                                'found_id' => 1,
                            ]);


                        } else {

                            $SkillBlock = preg_replace('/[\r,]/', '~', $skills);
                            $SkillBlock = preg_replace('/[~]+/', '~', $SkillBlock);
                            $SkillBlockArr = explode('~', $SkillBlock);
                            $skillName = array();
                            $skillValue = array();

                            foreach ($SkillBlockArr as $key => $value) {
                                if (!empty($value)) {
                                    $sql = "select s.skill_name, sv.skillblock_keywords from skill_block_values as sv inner join skill_blocks as s on sv.skillblock_id = s.id where skillblock_keywords like'%" . addslashes($value) . "%'";

                                    $skillInfo = DB::select($sql);
                                    if (is_array($skillInfo) && count($skillInfo) > 0) {
                                        DB::insert("insert into skillblock_temps set keyword='" . $skillInfo[0]->skill_name . "', value='" . addslashes($skillInfo[0]->skillblock_keywords) . "'");
                                    } else {
                                        DB::insert("insert into skillblock_temps set keyword='skills', value='" . addslashes($value) . "'");
                                    }
                                }
                            }
                        }
                    }
                    $skillData = DB::select("select keyword, GROUP_CONCAT(value) as keyval from skillblock_temps group by keyword order by id");

                    if (is_array($skillData) && count($skillData) > 0) {
                        foreach ($skillData as $ky => $val) {

                            if ($val->keyword == "skills") {


                                SkillBlockResume::create([
                                    'candidate_id' => $candidate->id,
                                    'keyword' => addslashes($val->keyword),
                                    'skill_value' => addslashes($val->keyval),
                                    'found_id' => 2,
                                ]);
                            } else {
                                SkillBlockResume::create([
                                    'candidate_id' => $candidate->id,
                                    'keyword' => addslashes($val->keyword),
                                    'skill_value' => addslashes($val->keyval),
                                    'found_id' => 1,
                                ]);
                            }
                        }
                    }
                    DB::delete('delete from skillblock_temps');
                }

                $user_id = $req->user_id;
                $ques_id = $req->ques_id;
                $file = $req->file;
                $email = $req->email;

                QuestionAnswer::create([
                    'ques_id' => $ques_id,
                    'user_id' => $user_id,
                    'answer' => $file
                ]);


            } else {
                $fileuploadarr = ['fullname' => $fullname,
                    'location' => $location,
                    'summary' => $summary,
                    'email' => $email,
                    'mobile' => $mobile,
                    'skills' => $skillsData,
                    'country_code' => $country_code
                ];

                $fileuploadarr['json'] = $json;
                return $fileuploadarr;
            }

            $lastCandidateId = $candidate->id;
            /*
            if($json["WorkedPeriod"]["TotalExperienceInMonths"] && is_array($json["SegregatedExperience"])) {
                foreach ($json["SegregatedExperience"] as $exp)
                {
                    $startDate = str_replace('/', '-', $exp["StartDate"]);//Replace '/' with '-'
                    $endDate = str_replace('/', '-', $exp["EndDate"]);//Replace '/' with '-'
                    $candidate_exp = CandidateExperiences::create([
                        'employer_name' => $exp["Employer"],
                        'job_title' => $exp["JobProfile"]["Title"],
                        'empoyer_city' => '',//$exp["JobLocation"]["EmployerCity"],
                        'start_date' => date('Y-m-d', strtotime($startDate)),
                        'end_date' =>  date('Y-m-d', strtotime($endDate)),
                        'is_current_employer' => ($exp["Employer"] == (String) $json["CurrentEmployer"]) ? 1 : 0 ,
                        'candidate_id' => $lastCandidateId
                    ]);
                   // $candidate_exp_response = response()->success(compact('candidate_exp'));
                } //candidate work history foreach
            } //if
            */
            //Insert a record into candidateskillssets table

            $skills_new = '';
            $candidate_skills = CandidateSkill::create([
                'skills' => (string)$json["SkillKeywords"],//isko for each lagake aur implode karna hi
                'candidate_id' => $lastCandidateId,
            ]);
            // $candidate_skills_response = response()->success(compact('candidate_skills'));

            $candidate_operational_skills = CandidateOperationalSkill::create([
                'operational_skills' => (string)$operationalSkills,
                'candidate_id' => $lastCandidateId,
            ]);
            // $candidate_operational_skills_response = response()->success(compact('candidate_operational_skills'));
            $candidate_soft_skills = CandidateSoftSkill::create([
                'soft_skills' => (string)$softSkills,
                'candidate_id' => $lastCandidateId,
            ]);
            //  $candidate_soft_skills_response = response()->success(compact('candidate_soft_skills'));
            // for only now
            foreach ($json["SegregatedQualification"] as $edu) {
                if (isset($edu["Institution"])) {
                    $startDate = str_replace('/', '-', $edu["StartDate"]);
                    $endDate = str_replace('/', '-', $edu["EndDate"]);
                    //print_r($edu["Degree"]["DegreeName"]);exit;
                    //Insert a record into candidateskillssets table
                    $candidate_educations = CandidateEducation::create([
                        'institution_name' => $edu["Institution"]["Name"],
                        'institution_city' => $edu["Institution"]["Location"]["City"],
                        'degree' => $edu["Degree"]["DegreeName"],
                        'start_date' => date('Y-m-d', strtotime($startDate)),
                        'end_date' => date('Y-m-d', strtotime($endDate)),
                        'aggregate' => $edu["Aggregate"]["Value"],
                        'candidate_id' => $lastCandidateId,
                    ]);
                    // $candidate_educations_response = response()->success(compact('candidate_educations'));
                }
            } //foreach
            ///candidate-details//need to create model and send it to database
            $recomon = "";
            foreach ($json["Recommendations"] as $recomondation) {
                if (strlen($recomon) > 0) {
                    $recomon = $recomon . ', ';
                }
                $recomon = $recomon . $recomondation["PersonName"];
            }
            $websites = "";
            foreach ($json["WebSite"] as $recomondation) {
                if (strlen($websites) > 0) {
                    $websites = $websites . ', ';
                }
                $websites = $websites . $recomondation["Url"];
            }
            $candidate_details = CandidateDetail::create([
                'gapperiod' => (string)$json["GapPeriod"],
                'averageStay' => (string)$json["AverageStay"],
                'LongestStay' => (string)$json["LongestStay"],
                'recommendations' => (string)$recomon,
                'detail_resume' => (string)$json["DetailResume"],
                'template_output_data' => (string)$json["TemplateOutput"]['TemplateOutputData'],
                'websites' => (string)$websites,
                //'overalldata' => (string) $json,
                'candidate_id' => $lastCandidateId,
            ]);

            foreach ($json["SegregatedSkill"] as $edu) {
                $segregatedskills = SegregatedSkill::create([
                    'type' => (string)$edu["Type"],
                    'skill' => (string)$edu["Skill"],
                    'Ontology' => (string)$edu["Ontology"],
                    'alias' => (string)$edu["Alias"],
                    'formattedname' => (string)$edu["FormattedName"],
                    'evidence' => (string)$edu["Evidence"],
                    'lastused' => (string)$edu["LastUsed"],
                    'candidate_id' => $lastCandidateId,
                ]);
            }

        } else {

//            echo 'invalid Resume ';
//            exit();interview_questions

            $user = Auth::user();
            return redirect()->route('interview_questions', ['email' => base64_encode($user->email), 'userid' => base64_encode($user->id), 'id' => base64_encode($req->ques_id)])->with('flash_message', 'invalid Resume');

        }
        $questions = RoleQuestions::where('role_id', (Auth::user()->role_id))->first();

        if (!empty($questions)) {
            return redirect('role_questions/' . $email . '/' . $user_id . '/' . base64_encode($questions->id));
        } else {
            $categories = VideoInterviewCategories::orderBy('sort_no', 'asc')->first();
           
            if (!empty($categories)) {
                //return redirect('categories/' . base64_decode($email) . '/' . $user_id . '/' . base64_encode($categories->id));

                return redirect('categories/' . $email . '/' . $user_id . '/' . $categories->id);
            }

            return redirect('thanks_you/' . $email . '/' . $user_id);
        }
    }

    public function thanks_you($email, $userid, Request $req)
    {
        if (checkvalidUser($userid) == 1) {
            return redirect()->route('home');
        } elseif (checkvalidUser($userid) == 2) {
            $userInfo = User::where('id', base64_decode($userid))->first();
            return redirect(route('home', ['steps' => 'step7']) . "?role=" . $userInfo->role_id);

        } elseif (checkvalidUser($userid) == 3) {
            return redirect()->route('home');
        }

//        $postData = $req->all();

        $user = Auth::user();

        if ($user->flag == 0) {
            $user->flag = 1;
            $user->save();

            $data['user'] = $user;

            $from_address = $_ENV['MAIL_FROM_ADDRESS'];

            $from_name = $_ENV['MAIL_FROM_NAME'];

            Mail::send('emails_templates.thank_you_user', $data, function ($message) use ($user, $from_address, $from_name) {

                $message->from($from_address, $from_name);
                $message->to($user->email, $user->name);
                $message->subject("Thank you for Participating!");
            });

        }


        Auth::logout();

        $req->session()->invalidate();

        $req->session()->regenerateToken();

        return view('thank_you');
    }

    public function not_suitable()
    {

        $user = Auth::user();

        $data['user'] = $user;

        $from_address = $_ENV['MAIL_FROM_ADDRESS'];

        $from_name = $_ENV['MAIL_FROM_NAME'];

        Mail::send('emails_templates.not_suitable_user', $data, function ($message) use ($user, $from_address, $from_name) {

            $message->from($from_address, $from_name);
            $message->to($user->email, $user->name);
            $message->subject("Thank you for Participating!");
        });

        return view('not_suitable');
    }

//    public function someFunction($errno, $errstr) {
//        echo '<h2>Upload failed.</h2><br>';
//        echo '<p>'.$errstr.'</p>';
//    }


    public function saveCategoryVideo(Request $request)
    {
        $responce = array();

        header("Access-Control-Allow-Origin: *");
        error_reporting(E_ALL);
        ini_set('display_errors', 1);

        $postData = $request->all();

//        dd($postData);

        if (!isset($_POST['audio-filename']) && !isset($_POST['video-filename'])) {

            $responce['error'] = 404;
            $responce['msg'] = 'Empty file name.';


            return $responce;
        }

        // do NOT allow empty file names
        if (empty($_POST['audio-filename']) && empty($_POST['video-filename'])) {

            $responce['error'] = 404;
            $responce['msg'] = 'Empty file name';

            return $responce;
        }

        // do NOT allow third party audio uploads
        if (false && isset($_POST['audio-filename']) && strrpos($_POST['audio-filename'], "RecordRTC-") !== 0) {
            $responce['error'] = 405;
            $responce['msg'] = 'File name must start with "RecordRTC-"';

            return $responce;

        }

        // do NOT allow third party video uploads
        if (false && isset($_POST['video-filename']) && strrpos($_POST['video-filename'], "RecordRTC-") !== 0) {

            $responce['error'] = 405;
            $responce['msg'] = 'File name must start with "RecordRTC-"';

            return $responce;

        }

//        $fileName = '';
//        $tempName = '';
        $file_idx = '';
//
//
        if (!empty($_FILES['audio-blob'])) {
            $file_idx = 'audio-blob';
//            $fileName = $_POST['audio-filename'];
//            $tempName = $_FILES[$file_idx]['tmp_name'];
        } else {
            $file_idx = 'video-blob';
//            $fileName = $_POST['video-filename'];
//            $tempName = $_FILES[$file_idx]['tmp_name'];
        }

        $catVideoInfo = VideoInterviewCategoriesVideos::where('id', $postData['cate'])->first();


        $vidoeFile = VideoInterviewCategoriesVideos::uploadVideo($request, $file_idx, $catVideoInfo->video_url);

//        dd($vidoeFile['filename']);

        if (!empty($vidoeFile) && $vidoeFile['error'] == 200) {


            $inserVideoArray = array();

            $catVideoInfo->video_url = $vidoeFile['filename'];

            $catVideoInfo->save();


//            $inserVideoArray['video_url'] = $vidoeFile['filename'];
//            $catVideoInfo->update($inserVideoArray);

            $responce['error'] = 200;
            $responce['msg'] = 'success';
            $responce['date'] = $catVideoInfo;

            return $responce;
        } else {
            $responce['error'] = 406;
            $responce['msg'] = 'failled';

            return $responce;
        }


    }

    public function saveVideo(Request $request)
    {

        $responce = array();

        header("Access-Control-Allow-Origin: *");
        error_reporting(E_ALL);
        ini_set('display_errors', 1);

        $postData = $request->all();


        if (!isset($_POST['audio-filename']) && !isset($_POST['video-filename'])) {

            $responce['error'] = 404;
            $responce['msg'] = 'Empty file name.';


            return $responce;
        }

        // do NOT allow empty file names
        if (empty($_POST['audio-filename']) && empty($_POST['video-filename'])) {

            $responce['error'] = 404;
            $responce['msg'] = 'Empty file name';

            return $responce;
        }

        // do NOT allow third party audio uploads
        if (false && isset($_POST['audio-filename']) && strrpos($_POST['audio-filename'], "RecordRTC-") !== 0) {
            $responce['error'] = 405;
            $responce['msg'] = 'File name must start with "RecordRTC-"';

            return $responce;

        }

        // do NOT allow third party video uploads
        if (false && isset($_POST['video-filename']) && strrpos($_POST['video-filename'], "RecordRTC-") !== 0) {

            $responce['error'] = 405;
            $responce['msg'] = 'File name must start with "RecordRTC-"';

            return $responce;

        }

//        $fileName = '';
//        $tempName = '';
        $file_idx = '';
//
//
        if (!empty($_FILES['audio-blob'])) {
            $file_idx = 'audio-blob';
//            $fileName = $_POST['audio-filename'];
//            $tempName = $_FILES[$file_idx]['tmp_name'];
        } else {
            $file_idx = 'video-blob';
//            $fileName = $_POST['video-filename'];
//            $tempName = $_FILES[$file_idx]['tmp_name'];
        }

        $vidoeFile = CandidateVideoInterviews::uploadVideo($request, $file_idx);

//        dd($vidoeFile);

        if (!empty($vidoeFile) && $vidoeFile['error'] == 200) {
            $inserVideoArray = array();
            $inserVideoArray['candidate_id'] = Auth::id();
            $inserVideoArray['video_category_id'] = $postData['video_category_id'];
            $inserVideoArray['video_id'] = $postData['record_vidoe_id'];
            $inserVideoArray['video_file'] = $vidoeFile['filename'];

            CandidateVideoInterviews::create($inserVideoArray);

            $responce['error'] = 200;
            $responce['msg'] = 'success';

            return $responce;
        } else {
            $responce['error'] = 406;
            $responce['msg'] = 'failled';

            return $responce;
        }


    }

    public function categories($email, $userid, $catid)
    {

//dd($email);


        if (checkvalidUser($userid) == 1) {
            return redirect()->route('home');
        } elseif (checkvalidUser($userid) == 2) {
            $userInfo = User::where('id', base64_decode($userid))->first();
            return redirect(route('home', ['steps' => 'step7']) . "?role=" . $userInfo->role_id);

        } elseif (checkvalidUser($userid) == 3) {
            return redirect()->route('home');
        }

        if ($catid == '') {
            return redirect('thanks_you/' . $email . '/' . $userid);
        } else {

            $candidateCateInfo = CandidateVideoInterviews::where(['video_category_id' => $catid, 'candidate_id' => base64_decode($userid)])->first();
            $data = array();
            $catid = $catid;
            $nextcategory = VideoInterviewCategories::where('id', '>', $catid)->orderBy('sort_no', 'asc')->first();
            if (!empty($nextcategory)) {
                $nextid = $nextcategory->id;
            } else {
                $nextid = '';
            }
            if (empty($candidateCateInfo)) {

                $videoInfo = VideoInterviewCategoriesVideos::with('catinfo')->where('category_id', $catid)->inRandomOrder()->first();
                if (!empty($videoInfo)) {
                    if ($videoInfo->video_url != '') {
                        $videoInfo->video_file_url = VideoInterviewCategoriesVideos::uploadDir('url') . '/' . $videoInfo->video_url;
                    } else {
                        $videoInfo->video_file_url = null;
                    }

                }


                $data['nextcategory'] = $nextcategory;
                $data['videoinfo'] = $videoInfo;
                $data['nextid'] = $nextid;
                $data['email'] = $email;
//                $data['userid'] = base64_decode($userid);
                $data['userid'] = $userid;
//                dd($data['userid']);

//            dd($data);
                return view('categories', $data);
            } else {
                if ($nextid == '') {
                    return redirect('thanks_you/' . $email . '/' . $userid);

                } else {

                    return redirect('categories/' . $email . '/' . $userid . '/' . $nextid);
                }

            }
        }
    }

    public function role_questions($email, $user_id, $id = '')
    {
        if (checkvalidUser($user_id) == 1) {
            return redirect()->route('home');
        } elseif (checkvalidUser($user_id) == 2) {
            $userInfo = User::where('id', base64_decode($user_id))->first();
            return redirect(route('home', ['steps' => 'step7']) . "?role=" . $userInfo->role_id);

        } elseif (checkvalidUser($user_id) == 3) {
            return redirect()->route('home');
        }


        if (empty($id)) {

            $questionInfo = RoleQuestions::where('role_id', (Auth::user()->role_id))->limit(1)->get();

            $question = RoleQuestionsAnswers::where([
                'question_id' => $questionInfo[0]->id,
                'user_id' => base64_decode($user_id)
            ])->first();


            if (!empty($question)) {

                $nextquestion = RoleQuestions::where('id', '>', $questionInfo[0]->id)->orderBy('id', 'asc')->first();

                return redirect('role_questions/' . $email . '/' . $user_id . '/' . base64_encode($nextquestion->id));
            } else {
                $categories = VideoInterviewCategories::orderBy('sort_no', 'asc')->first();

                if (!empty($categories)) {
                    return redirect('categories/' . base64_decode($email) . '/' . $user_id . '/' . base64_encode($categories->id));
                }

                return redirect('thanks_you/' . $email . '/' . $user_id);

            }

        } else {
            $questionInfo = RoleQuestions::where('id', base64_decode($id))->get();


            $question = RoleQuestionsAnswers::where([
                'question_id' => $questionInfo[0]->id,
                'user_id' => base64_decode($user_id)
            ])->first();

            if (!empty($question)) {


                $nextquestion = RoleQuestions::where('id', '>', $questionInfo[0]->id)->orderBy('id', 'asc')->first();

                if (empty($nextquestion)) {

                    $categories = VideoInterviewCategories::orderBy('sort_no', 'asc')->first();

                    if (!empty($categories)) {
                        return redirect('categories/' . base64_decode($email) . '/' . $user_id . '/' . base64_encode($categories->id));
                    }

                    return redirect('thanks_you/' . $email . '/' . $user_id);

                } else {
                    return redirect('role_questions/' . $email . '/' . $user_id . '/' . base64_encode($nextquestion->id));

                }


            }
        }

        $data = array();
        $data['questionInfo'] = $questionInfo;
        $data['user_id'] = $user_id;
        $data['email'] = $email;


        return view('role_questions', $data);


    }

    public function save_role_question(Request $req)
    {

        $user_id = Auth::id();
        $ques_id = $req->ques_id;
        $options = $req->options;
        $email = $req->email;
        $QuestionAnswerArray = array();
        $QuestionAnswerArray['question_id'] = $ques_id;
        $QuestionAnswerArray['user_id'] = $user_id;
        $QuestionAnswerArray['answer'] = $options;

        $questionInfo = RoleQuestionsAnswers::where([
            'question_id' => $ques_id,
            'user_id' => $user_id
        ])->first();


        if (empty($questionInfo)) {

            RoleQuestionsAnswers::create($QuestionAnswerArray);
        }

        $nextquestion = RoleQuestions::where('id', '>', $ques_id)->orderBy('id', 'asc')->first();

        if (empty($nextquestion)) {
            $categories = VideoInterviewCategories::orderBy('sort_no', 'asc')->first();

            if (!empty($categories)) {
                return redirect('categories/' . base64_encode($email) . '/' . $user_id . '/' . base64_encode($categories->id));
            }

            return redirect('thanks_you/' . $email . '/' . $user_id);

        }

        return redirect('role_questions/' . $email . '/' . base64_encode($user_id) . '/' . base64_encode(($nextquestion->id)));


    }

    public function verifyEmail(Request $request)
    {

        if ($request->isMethod('post')) {

            $requestData = $request->all();


            $this->validate(request(), [
                'email' => 'required',
                'otp' => 'required'
            ], [

                'email.required' => 'Enter email',
                'otp.required' => 'Enter otp'
            ]);

            $record = CampaignEmails::where(['email_id' => $requestData['email'], 'invitation_code' => $requestData['otp']])->first();
            if (!empty($record)) {

                $updateData = array();
                $updateData['flag'] = 1;
                $updateData['flag'] = 1;
                $record->update($updateData);

                $request->session()->put('verify', 'yes');

                return redirect()->route('home');
            } else {
                $mes = 'Invalid email/code';
                return redirect()->route('startnow')->with('flash_message', $mes);
            }

        }
        $data = array();
        return view('verifyEmail', $data);

    }
}
