<?php

namespace App\Http\Controllers;

use App\Models\PostData;
use App\Models\PostImage;
use App\Models\PostLike;
use App\Models\comments_adds;
use Illuminate\Http\Request;
use App\Models\Education;
use App\Models\UserModel;
use App\Models\PostJob;
use App\Models\JobExamList;
use App\Models\Organisation;
use App\Models\QuestionDetail;
use App\Models\JobAppStatus;
use App\Models\QuestionInformation;
use App\Models\JobsApplyData;
use App\Models\QuestionAns;
use App\Models\PostJobFilterData;
use App\Models\Follower;
use App\Models\social_media_link;
use Illuminate\Support\Facades\Session;



class PostJobs extends Controller
{




    public function submitJobApplication(Request $request){
    $job_posted_email=$request->job_posted_by;
    $job_title=$request->job_title;
    $job_created_At=$request->job_id_created_at;
   $session_emailId = Session::get('emailId');
   $questionAns=$request->QuestionAns;
   $QAnsArray = explode (":-", $questionAns);
   for($i=0; $i< sizeof($QAnsArray);$i++)
   {
       $qText="";
       $qAns="";
       $questionA= $QAnsArray[$i];
          $QA = explode (":", $questionA);
          if(sizeof($QA)>0){
            $qText=$QA[0];
          }
          if(sizeof($QA)>1){
            $qAns=$QA[1];
          }
       if(strlen($qText)>0 && strlen($qAns) > 0){
       QuestionAns::create([
        'job_posted_email'=> $job_posted_email,
        'job_title'=> $job_title,
        'job_id'=> $job_created_At,
        'question_txt'=>$qText,
         'question_ans'=>$qAns,
        ]);
       }

   }


    $resultVisit = JobsApplyData::where([['post_job_email_address', $job_posted_email],['job_title',$job_title],['job_id',$job_created_At]])->get();

     if($resultVisit->count() >0){

            return redirect()->route('viewjobs')->with( ['message' => 'AppliedAlready'] );
     die;
     }
    JobsApplyData::create([
        'post_job_email_address'=> $job_posted_email,
        'job_title'=> $job_title,
        'job_id'=> $job_created_At,
        'applied_person_email'=>$session_emailId,

        ]);
       $job_profile_name="";
          $resultt=  PostJob::where([['email_address','=', $job_posted_email],['job_title','=', $job_title],['created_at','=', $job_created_At]])->get();
         if ($resultt) {
                      foreach($resultt as $row)
                      {
                          $job_profile_name= $row["job_img_name"];
                      }
         }
   return redirect()->route('viewjobs')->with( ['message' => 'submitted_successfully','job_profile_image' =>$job_profile_name,'job_posted_by_email' =>$job_posted_email] );

    }




    public function addQuestion(Request $request){
        $questionText=$request->questionText;
        $questionType=$request->questionType;
         $session_emailId = Session::get('emailId');
         $job_detail=$request->jobDetail;

        QuestionDetail::create([
        'question_text'=> $questionText,
        'question_option'=> $questionType,
        'email_address'=> $session_emailId,
        'job_detail'=> $job_detail,

        ]);



    }
    public function filterJobs(Request $request){


        $job_name=$request->job_name;
        $field=$request->field;
        $country_name=$request->country_name;
         $city_name=$request->city_name;
          $schedule=$request->schedule;
         $mode=$request->mode;
         $duration=$request->duration;
         $olddays=$request->oldday;

       Session::put('job_name', $job_name);
       Session::put('field', $field);
       Session::put('country_name', $country_name);
       Session::put('city_name', $city_name);
       Session::put('mode', $mode);
       Session::put('duration', $duration);
         Session::put('olddays', $olddays);

         return    view('viewjobs');



    }



         public function submitApplyForJob(Request $request){

          $session_emailId = Session::get('emailId');
          JobsApplyData::create([
            'post_job_email_address'=> $request->email_add_who_post_job,
            'job_title'=> $request->job_title,
            'job_id'=> $request->job_id,
            'applied_person_email'=>     $session_emailId,
          ]);



          $PostedJobDetail= PostJobFilterData::where([['job_id', $request->job_id]])->first();
          $result = UserModel::where('email_id', $session_emailId)->get();
          if ($result) {
              foreach($result as $row) {
                  $ethnicity = $row["ethnicity"];
                  $gender = $row["gender"];
                  $status = $row["status"];
                  $birth_date = $row["birth_date"];
                 break;
              }

          }

          //First Check BirthDate...............................
          $startAge=NULL;
          $endAge=NULL;
          $birthDate = new \DateTime($birth_date);
          $currentDate = new \DateTime();
          $interval = $currentDate->diff($birthDate);
          $age = $interval->y;
          if(!empty($PostedJobDetail->sAge)){
          $startAge=(int) $PostedJobDetail->sAge;
          }
          if(!empty($PostedJobDetail->eAge)){
          $endAge= (int) $PostedJobDetail->eAge;
          }

          $canNotApply=FALSE;
          if($startAge!=NULL && $endAge!=NULL){
          if($age>=$startAge && $age<= $endAge){
            $canNotApply=FALSE;
          }
        }
        if(!empty($PostedJobDetail->Gender)){

          if($gender==$PostedJobDetail->Gender){
            $canNotApply=FALSE;
          }
        }
        if(!empty($PostedJobDetail->status)){

            if($status==$PostedJobDetail->status){
              $canNotApply=FALSE;
            }
          }
          if(!empty($PostedJobDetail->Ethnicity)){
            if (stripos($PostedJobDetail->Ethnicity,  $ethnicity) !== false) {
              $canNotApply=FALSE;
            }
          }


          $PostedJobDetail= PostJob::where([['job_id', $request->job_id]])->first();
         // $Exam_List= JobExamList::where([['job_id', $request->job_id]])->get();

          $Exam_List = JobExamList::join('exam_list', 'exam_list.exam_name', '=', 'jobs_exam_list_table.exam_name')
          ->where('jobs_exam_list_table.job_id', $request->job_id)
          ->select('jobs_exam_list_table.*', 'exam_list.exam_logo_name') // Selecting all fields from job_exam_list and the jobexamicon from job_exam_icons
          ->get();

          $user_info = $this->returnUserInfo($PostedJobDetail->email_address);
          return view("viewjobs")->with([
            'CanNotApply' => $canNotApply,
            'JobDetails' => $PostedJobDetail,
            'ExamList' => $Exam_List,
            'UserInfo' => $user_info,
            'appliedSuccessfully'=>TRUE,
            'IsAlreadyApplied'=>TRUE,
        ]);


         }

        public function applyforjob(Request $request){
          $session_emailId = Session::get('emailId');

          $existingApplication = JobsApplyData::where('job_id', $request->job_id)
                                        ->where('applied_person_email', $session_emailId)
                                        ->where('post_job_email_address', $request->posted_person_email)
                                        ->first();
          $isAlreadyApplied=FALSE;
          if( $existingApplication){
            $isAlreadyApplied=TRUE;
            }





          $PostedJobDetail= PostJobFilterData::where([['job_id', $request->job_id]])->first();
          $result = UserModel::where('email_id', $session_emailId)->get();
          if ($result) {
              foreach($result as $row) {
                  $ethnicity = $row["ethnicity"];
                  $gender = $row["gender"];
                  $status = $row["status"];
                  $birth_date = $row["birth_date"];
                 break;
              }

          }

          //First Check BirthDate...............................

          $birthDate = new \DateTime($birth_date);
          $currentDate = new \DateTime();
          $interval = $currentDate->diff($birthDate);
          $age = $interval->y;
          $startAge=NULL;
          $endAge=NULL;




          if(!empty($PostedJobDetail->sAge)){
            $startAge=(int) $PostedJobDetail->sAge;
          }
          if(!empty($PostedJobDetail->eAge)){
          $endAge= (int) $PostedJobDetail->eAge;
          }

          $canNotApply=FALSE;
          if($startAge!=NULL && $endAge!=NULL){
          if($age>=$startAge && $age<= $endAge){
            $canNotApply=FALSE;
          }else{
            $canNotApply=TRUE;
          }
        }

        if(!empty($PostedJobDetail->Gender)){

          if($gender==$PostedJobDetail->Gender){
            $canNotApply=FALSE;
          }else{
            $canNotApply=TRUE;
          }
        }
        if(!empty($PostedJobDetail->status)){

            if($status==$PostedJobDetail->status){
              $canNotApply=FALSE;
            }else{
              $canNotApply=TRUE;
            }
          }
          if(!empty($PostedJobDetail->Ethnicity)){

            if (stripos($PostedJobDetail->Ethnicity,  $ethnicity) !== false) {
              $canNotApply=FALSE;
            }else{$canNotApply=TRUE;}
          }



          $PostedJobDetail= PostJob::where('job_id', $request->job_id)->first();
         // $Exam_List= JobExamList::where([['job_id', $request->job_id]])->get();

          $Exam_List = JobExamList::join('exam_list', 'exam_list.exam_name', '=', 'jobs_exam_list_table.exam_name')
          ->where('jobs_exam_list_table.job_id', $request->job_id)
          ->select('jobs_exam_list_table.*', 'exam_list.exam_logo_name') // Selecting all fields from job_exam_list and the jobexamicon from job_exam_icons
          ->get();

          $user_info = $this->returnUserInfo($PostedJobDetail->email_address);


          return view("viewjobs")->with([
            'CanNotApply' => $canNotApply,
            'JobDetails' => $PostedJobDetail,
            'ExamList' => $Exam_List,
            'UserInfo' => $user_info,
            'IsAlreadyApplied'=>$isAlreadyApplied,
        ]);

        }







        public function returnUserInfo($emailAdd)
        {

            $infoArray = [];
            $resultProfile = UserModel::where('email_id', $emailAdd)->get();
            $num_rows = count($resultProfile);
            if ($num_rows > 0) {
                foreach ($resultProfile as $row) {
                    $infoArray[] = $row["profile_picture"];
                    $infoArray[] = $row["first_name"] . " " . $row["second_name"];
                }
            }

            // else {

            //     $resultProfile = Organisation::where('email_id', $emailAdd)->get();
            //     $num_rows = count($resultProfile);

            //     if ($num_rows > 0) {

            //         foreach ($resultProfile as $row) {
            //             $infoArray[] = $row["profile_picture"];
            //             $infoArray[] = $row["first_name"] . " " . $row["second_name"];
            //         }
            //     } else {
            //         $resultProfile = Education::where('email_id', $emailAdd)->get();
            //         $num_rows = count($resultProfile);
            //         if ($num_rows > 0) {
            //             foreach ($resultProfile as $row) {
            //                 $infoArray[] = $row["profile_picture"];
            //                 $infoArray[] = $row["first_name"] . " " . $row["second_name"];
            //             }
            //         }
            //     }
            // }
            return $infoArray;
        }


    public function addQuestionOption(Request $request){
         $questionText=$request->questionText;
        $optionText=$request->OptionText;
         $session_emailId = Session::get('emailId');
         $job_detail=$request->jobDetail;


              QuestionInformation::create([
        'question_text'=> $questionText,
        'question_option'=> $optionText,
        'email_address'=> $session_emailId,
        'job_title'=> $job_detail,

        ]);
    }
    // Upload Post
    public function submitJobInfo(Request $request){

        $job_title = $request->job_title;
        // $field = $request->field;
        $address=$request->address;
        $country=$request->country_name;
        $city_name=$request->city_name;

        $description=$request->description;
        $description =nl2br($description);
        $requirement=$request->requirement;
        $requirement =nl2br($requirement);
        $task=$request->Task;
        $task =nl2br($task);
        $schedule=$request->schedule;
        $salary=$request->salary;
        $mode=$request->mode;
        $duration=$request->duration;
        $driver_license=$request->driver_license;
        $car=$request->car;
        $startAge=$request->candiateAgeStart;
        $endAge=$request->candiateAgeEnd;
        $gender=$request->genders;
        $ethnicityData=$request->ethnicity;
        $categoryList=$request->categoryList;
    //     $caucasian=$request->caucasian;
    //     $north_african=$request->north_african;
    //     $african=$request->african;
    //     $Hispanic=$request->Hispanic;
    //     $Asian=$request->Asian;
    //     $Afro_latin=$request->Afro_latin;
    //     $South_asian=$request->South_asian;
    //     $Native_american=$request-> Native_american;
    //     $Middle_eastern =$request->  Middle_eastern;
    //     $Other =$request->Other;
    //     $all=$request->all;
    //     $ethnicityData="";
    //     if(strlen($caucasian)>0){
    //         if($ethnicityData==""){
    //             $ethnicityData=$ethnicityData.',';
    //         }else
    //         {
    //             $ethnicityData=$ethnicityData.$caucasian.',';
    //         }
    //     }
    //   if(strlen($north_african)>0){
    //         if($ethnicityData==""){
    //             $ethnicityData=$north_african.',';
    //         }else
    //         {
    //             $ethnicityData=$ethnicityData.$north_african.',';
    //         }
    //     }
    //   if(strlen($african)>0){
    //         if($ethnicityData==""){
    //             $ethnicityData=$african.',';
    //         }else
    //         {
    //             $ethnicityData=$ethnicityData.$african.',';
    //         }
    //     }
    //   if(strlen($Hispanic)>0){
    //         if($ethnicityData==""){
    //             $ethnicityData=$Hispanic.',';
    //         }else
    //         {
    //             $ethnicityData=$ethnicityData.$Hispanic.',';
    //         }
    //     }
    //   if(strlen($Asian)>0){
    //         if($ethnicityData==""){
    //             $ethnicityData=$Asian.',';
    //         }else
    //         {
    //             $ethnicityData=$ethnicityData.$Asian.',';
    //         }
    //     }
    //   if(strlen($Afro_latin)>0){
    //         if($ethnicityData==""){
    //             $ethnicityData=$Afro_latin.',';
    //         }else
    //         {
    //             $ethnicityData=$ethnicityData.$Afro_latin.',';
    //         }
    //     }

    //   if(strlen($South_asian)>0){
    //         if($ethnicityData==""){
    //             $ethnicityData=$South_asian.',';
    //         }else
    //         {
    //             $ethnicityData=$ethnicityData.$South_asian.',';
    //         }
    //     }
    //   if(strlen($Native_american)>0){
    //         if($ethnicityData==""){
    //             $ethnicityData=$Native_american.',';
    //         }else
    //         {
    //             $ethnicityData=$ethnicityData.$Native_american.',';
    //         }
    //     }

    //      if(strlen($Middle_eastern)>0){
    //         if($ethnicityData==""){
    //             $ethnicityData=$Middle_eastern.',';
    //         }else
    //         {
    //             $ethnicityData=$ethnicityData.$Middle_eastern.',';
    //         }
    //     }

    //      if(strlen($Other)>0){
    //         if($ethnicityData==""){
    //             $ethnicityData=$Other.',';
    //         }else
    //         {
    //             $ethnicityData=$ethnicityData.$Other.',';
    //         }
    //     }
    //   if(strlen($all)>0){
    //         if($ethnicityData==""){
    //             $ethnicityData=$all.',';
    //         }else
    //         {
    //             $ethnicityData=$ethnicityData.$all.',';
    //         }
    //     }
        $session_emailId = Session::get('emailId');

        $examDetails =$request->  examDetail;


        //$filterData =$request->  filterList;


        $datee = date('Y-m-d H_i_s') . '';


            $fileName="";

          if(isset($_FILES['customFile'])){
            $errors= array();
            $file_name = $_FILES['customFile']['name'];
            $file_size = $_FILES['customFile']['size'];
            $file_tmp = $_FILES['customFile']['tmp_name'];
            $file_type = $_FILES['customFile']['type'];

            $file = explode('.',$_FILES['customFile']['name']);
            $file_raw = end($file);
            $file_ext = strtolower($file_raw);

            $extensions = array("jpeg","jpg","png");
             $randomNum= rand(10,1000);
            $email_id=Session::get('emailId');
            $position = strpos($email_id, '@');
            $fileName1 = substr($email_id, 0, $position);
           $fileName = $fileName1;
            $fileName =$randomNum. $fileName .'.'.$file_ext;

            if(empty($errors) == true){

              $path = public_path("PostImages/" . $email_id . "/" . $datee);
              //Setup our new file path

              if (!file_exists($path)) {
                mkdir($path, 0777, true);
              }
              //Upload the file into the temp dir
              if (move_uploaded_file($file_tmp, "PostImages/" . $email_id . "/" . $datee . "/" . $fileName)) {

                //Handle other code here

              }







            }else{
                print_r($errors);
            }
          }










         $dateTimeStmp = date('Y-m-d H:i:s') ;

         PostJob::create([
        'email_address'=> $session_emailId,
        'job_title'=> $job_title,
        'job_addres'=> $address,
        'job_description'=> $description,
        'job_requirement'=> $requirement,
        'job_task'=> $task,
        'job_schedule'=> $schedule,
        'job_salary'=> $salary,
        'job_mode'=> $mode,
        'job_duration'=> $duration,
        'driver_licens'=> $driver_license,
        'job_car'=> $car,
        'startAge'=> $startAge,
        'endAge'=> $endAge,
        'gender'=> $gender,
        'ethnicity'=> $ethnicityData,
        'job_img_name'=>$fileName,
        'created_at'=>$dateTimeStmp,
        'job_id' => $datee,
        'country_name'=>$country,
        'city_name'=>$city_name,
        'category_id'=>$categoryList,

        ]);


        //Adding Exam Job Data To Database.........................

        $JobExamList = explode(',', $examDetails);
        for($i=0;$i< count($JobExamList);$i++){

        JobExamList::create([
        'job_id'=> $datee,
        'user_email'=> $session_emailId,
        'exam_name'=> $JobExamList[$i],

         ]);
        }
        //.........................................................

         PostJobFilterData::create([
        'email_id'=> $session_emailId,
        'job_title'=> $job_title,
        'job_id'=>$datee,
        'sAge'=>$request->startAge,
        'eAge'=>$request->endAge,
        'Gender'=>$request->genderSelected,
        'Ethnicity'=>$request->entList,
        'status'=>$request->status,
        'LicenceVscar'=>$request->carvslicenance,

        ]);


      $resultForName = Organisation::where('email_id', $session_emailId)->get();
             $FullName="";
                   if (count($resultForName)>0) {
                        foreach($resultForName as $roww) {
                         $FullName= $roww["first_name"].' '.$roww["second_name"];
                        }
                   }


         PostData::create([
            'email_id' => $email_id,
            'FullName' => $FullName,
            'PostText' => $job_title,
            'DateTime' => $datee,
            'PostImgeName' => $datee,
            'isJobPost' => 'Yes'
        ]);


        if (!empty($_POST["YesNo"])) {

          $obj=$_POST['YesNo'];
           foreach ($obj as $index => $object) {
              // Sanitize and process each object
               $questionTet = isset($object['name']) ? htmlspecialchars($object['name']) : '';
               QuestionDetail::create([
                'email_address' => $email_id,
                'question_text' => $questionTet,
                'question_type' => 'YesNo',
                'job_id' => $datee,
                'opt_one' => NULL,
                'opt_two' => NULL,
                'opt_three' => NULL,
                'opt_four' => NULL

            ]);
             }
          }


          if (!empty($_POST["OptQuestion"])) {

            $obj=$_POST['OptQuestion'];
             foreach ($obj as $index => $object) {
                // Sanitize and process each object
                 $questionTet = isset($object['name']) ? htmlspecialchars($object['name']) : '';
                 $QuestionOpt = explode('|', $questionTet);
                 $questionText="";
                 $opt1=NULL;
                 $opt2=NULL;
                 $opt3=NULL;
                 $opt3=NULL;
                 if(count($QuestionOpt)> 0){
                  $questionText=$QuestionOpt[0];
                 }
                 if(count($QuestionOpt)>1){
                  $opt1=$QuestionOpt[1];
                 }
                 if(count($QuestionOpt)>2){
                  $opt2=$QuestionOpt[2];
                 }
                 if(count($QuestionOpt)>3){
                  $opt3=$QuestionOpt[3];
                 }
                 if(count($QuestionOpt)>4){
                  $opt4=$QuestionOpt[4];
                 }
                 QuestionDetail::create([
                  'email_address' => $email_id,
                  'question_text' => $questionText,
                  'question_type' => 'Opt',
                  'job_id' => $datee,
                  'opt_one' => $opt1,
                  'opt_two' => $opt2,
                  'opt_three' => $opt3,
                  'opt_four' => $opt4

              ]);

               }
            }



            if (!empty($_POST["TextBased"])) {

              $obj=$_POST['TextBased'];
               foreach ($obj as $index => $object) {
                  // Sanitize and process each object

                  // Sanitize and process each object
                  $questionTet = isset($object['name']) ? htmlspecialchars($object['name']) : '';
                  QuestionDetail::create([
                    'email_address' => $email_id,
                    'question_text' => $questionTet,
                    'question_type' => 'TextBased',
                    'job_id' => $datee,
                    'opt_one' => NULL,
                    'opt_two' => NULL,
                    'opt_three' => NULL,
                    'opt_four' => NULL

                ]);

                 }
              }



      // $obj=$_POST['OptQuestion'];


      // foreach ($obj as $index => $object) {
      //     // Sanitize and process each object
      //     $name = isset($object['name']) ? htmlspecialchars($object['name']) : '';
      //     $value = isset($object['value']) ? htmlspecialchars($object['value']) : '';

      //     // Output or process the values
      //     echo "Object $index:<br>";
      //     echo "Name: $name<br>";
      //     echo "Value: $value<br><br>";
      // }












        return redirect()->route('home');




    }




}
