<?php

namespace App\Controllers;

use App\Models\Md_student;
use App\Models\Md_sms;
use App\Models\Md_cms;
use App\Models\Md_login;
$session = \Config\Services::session();

class Home extends BaseController
{
    
    
    public function __construct() {
         $this->Md_login = new Md_student();
         $this->Md_sms= new Md_sms();
         $this->Md_cms= new Md_cms();
         $this->Md_userlogin = new Md_login();
    }
    
    public function index(): string
    {
        return view('index');
    }
    
    
    
public function PasswordChange() 
 {
        header("Access-Control-Allow-Origin: *");
        // If you need to allow specific methods
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
        // If you need to allow specific headers
        header("Access-Control-Allow-Headers: Content-Type, Authorization");
        $datas = json_decode(file_get_contents("php://input"), true);
      
        $newpassword=$datas['newpassword'];
        $password=$datas['password'];
        $uid=$datas['uid'];
        $module=$datas['module'];
        
     
        $final = array();
        $ArrayData = array();
        
        if (!empty($newpassword) && !empty($password) && !empty($uid))
        {
            
            if ($newpassword!=$password)
            {
                 $final = array('status' => 4,'msg'=>"New password and confirm password is not same.");
                 echo json_encode($final);
                exit();
            }
            
            if($module=="laptop")
            {
                $table = "users";
                $updareData = array('usr_password' =>md5($newpassword));
                $condition = array('pk_user_id'=>$uid);
                $this->Md_userlogin->UpdateData($table, $condition, $updareData);
                
            }else {
  
                $table = "login";
                $updareData = array('password' =>md5($newpassword),'original_pass'=>$newpassword);
                $condition = array('id'=>$uid);
                $this->Md_login->UpdateData($table, $condition, $updareData);
            }
            $final = array('status' => 1, 'msg'=>"Your password is changed successfully.");
        } else {
            $final = array('status' => 2,'msg'=>"New password or Confirm password is empty");
        }
        echo json_encode($final);
        exit();
    }
    
    public function CMSCall() 
    {     
        header("Access-Control-Allow-Origin: *");
        // If you need to allow specific methods
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
        // If you need to allow specific headers
        header("Access-Control-Allow-Headers: Content-Type, Authorization");
        
        $datas = json_decode(file_get_contents("php://input"), true);
        $cms_key=$datas['cms_key'];

        if (!empty($cms_key)) 
        {
            if($cms_key=="about-us")
            {
                $table = "cms";
                // $fields = array('*');
                // $condition = array('cms_key' => $cms_key,'cms_status' => '1');
                // $arrayUser = $this->Md_database->getData($table, $fields, $condition, 'cms_pkey DESC', '1');
                
                $arrayUser=$this->Md_cms->CmsData($table,$cms_key);
            }else if($cms_key=="instruction")
            {
                // $table = "instruction";
                // $fields = array('title');
                // $condition = array('status' => '1');
                // $arrayUser = $this->Md_database->getData($table, $fields, $condition, 'pk_id DESC', '1');
                  
                 $arrayUser=$this->Md_cms->CmsDataInstruction();
              
            }

            if (!empty($arrayUser)) {
                if($cms_key=="instruction")
                {
                    $final = array('status' => 1, 'sms' =>'cms us data fetch.','cms_content'=> $arrayUser->title,'cms_page'=> "Instruction");
                }else if($cms_key=="about-us")
                {
                 $final = array('status' => 1, 'sms' =>'cms us data fetch.','cms_content'=> $arrayUser->cms_content,'cms_page'=> $arrayUser->cms_page);   
                }
            }else {
                $final = array('status' => 2, 'sms' =>'CMS key not found.');
            }
        } else {
                $final = array('status' => 3, 'sms' =>'Sorry...something went wrong.');
        }
         echo json_encode($final);
        exit();
    }

public function OrderHistory() 
 {
        header("Access-Control-Allow-Origin: *");
        // If you need to allow specific methods
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
        // If you need to allow specific headers
        header("Access-Control-Allow-Headers: Content-Type, Authorization");
        $datas = json_decode(file_get_contents("php://input"), true);
      
        $userid=$datas['userid'];
        
        error_reporting(0);
        $final = array();
        $ArrayData = array();
        
        if (!empty($userid))
        {    
            // $table = "student";
            // $select = array('pk_id,fk_login_id,MVPMAcademicYear,typeof_admission_want,selected_hostel,payment_status,MVPMAcademicYear,created_date,payment_date');
            // $condition = array('fk_login_id' => $userid);
            // $paymentHistory = $this->Md_database->getData($table, $select, $condition, 'pk_id DESC', '');

            $paymentHistory=$this->Md_login->OrderHistory($userid);

                $finalsResult=[];
                if (!empty($paymentHistory)) {
                            $i = 1;
                            foreach ($paymentHistory as $rows) {
                                
                                        $arrayHostelCheck = [];
                                        $FinalArray = [];
                                        $rowsStr = "";
                                        $rowsTemp = "";
                                        
                                        if (!empty($rows['selected_hostel'])) {

                                            $ArrrayHotelArray = explode(',', $rows['selected_hostel']);
                                            if (!empty($ArrrayHotelArray)) {

                                                foreach ($ArrrayHotelArray as $rowsTemp) {

                                                    // $this->db->select('hostel_name,hostel_shortname,pk_id');
                                                    // $this->db->where('pk_id', $rowsTemp);
                                                    // $this->db->from('name');
                                                    // $query = $this->db->get();
                                                    // $arrayHostelCheck[] = $query->row();
                                                    $arrayHostelCheck[]=$this->Md_login->Hostels($rowsTemp);
                                                    
                                                }

                                                if (!empty($arrayHostelCheck)) {
                                                    foreach ($arrayHostelCheck as $rowsStr) {
                                                        $FinalArray[] = $rowsStr->hostel_shortname;
                                                    }

                                                    $ArrrayHotels = implode(', ', ($FinalArray));
                                                }
                                            }
                                            
                                            $rows['ArrrayHotels']=$ArrrayHotels;
                                        }else {
                                            $rows['ArrrayHotels']=null;
                                        }
                                        
                                         if ($rows['payment_status'] == "5") 
                                         {
                                          $payment_status="Pending";
                                        } else if ($rows['payment_status'] == "1") {
                                            $payment_status="From Confirm";
                                         } else if ($rows['payment_status'] == "2") { 
                                           $payment_status="Aborted";
                                         } else if ($rows['payment_status'] == "3") { $payment_status="Failure";
                                         } else if ($rows['payment_status'] == "6") {
                                            $payment_status="Edit";
                                         } else if ($rows['payment_status'] == "4") {
                                            $payment_status="Security Error";
                                         } else if ($rows['payment_status'] == "7") { 
                                            $payment_status="Reject";
                                         } else if ($rows['payment_status'] == "8") { 
                                            $payment_status="On Hold";
                                         }
                                        
                                        $FinalArray=count($FinalArray) * 250;
                                        $rows['payment_status']=$payment_status;
                                        $rows['totalAmount']=$FinalArray;
                                        $rows['typeof_admission_want']=ucfirst($rows['typeof_admission_want']);
                                        $rows['created_date']=((!empty($rows['payment_date']) && "0000-00-00 00:00:00"!=$rows['payment_date'])? date('d-m-Y',strtotime($rows['payment_date'])) : date('d-m-Y',strtotime($rows['created_date'])));
                                        $finalsResult[]=$rows;
                                    
                                    }
                                $final = array('status' => 1, 'msg'=>"Your order history",'res_result'=>$finalsResult);         
                                }else {



            $final = array('status' => 3, 'msg'=>"Your order history is empty",'res_result'=>[]);
                                }
        } else {
            $final = array('status' => 2,'msg'=>"User id is empty");
        }
        echo json_encode($final);
        exit();
    }
    
public function FinalRegister() 
 {
        header("Access-Control-Allow-Origin: *");
        // If you need to allow specific methods
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
        // If you need to allow specific headers
        header("Access-Control-Allow-Headers: Content-Type, Authorization");
        $datas = json_decode(file_get_contents("php://input"), true);
      
        $Mobile=$datas['Mobile'];
        $newpassword=$datas['newpassword'];
        $conpassword=$datas['conpassword'];
        
        error_reporting(0);
        $final = array();
        $ArrayData = array();
        
        if (!empty($newpassword) && !empty($conpassword) && !empty($Mobile))
        {
            
            if ($newpassword!=$conpassword)
            {
                 $final = array('status' => 4,'msg'=>"New password and confirm password is not same.");
                 echo json_encode($final);
                exit();
            }
        
             $table = "login";
            $insertData = array(
                'mobile' => $Mobile,
                'username' => $Mobile,
                'password' => md5($newpassword),
                'original_pass' => $newpassword,
                'status' => '1',
                'created_date' => date('Y-m-d H:i:s'),
                'created_ip_address' => $_SERVER['REMOTE_ADDR']
            );

            $this->Md_login->InsertLoginAction($table, $insertData);
            
            $final = array('status' => 1, 'msg'=>"Your registration is successfully. Please login");
        } else {
            $final = array('status' => 2,'msg'=>"New password or Confirm password or Mobile no is empty");
        }
        echo json_encode($final);
        exit();
    }

    public function ReactOTPVerfiy() 
     {
        header("Access-Control-Allow-Origin: *");
        // If you need to allow specific methods
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
        // If you need to allow specific headers
        header("Access-Control-Allow-Headers: Content-Type, Authorization");
        $datas = json_decode(file_get_contents("php://input"), true);
        $otp=$datas['otp'];
        
        error_reporting(0);
        $final = array();
        $ArrayData = array();
        
        if (!empty($otp)) 
        {
            // $table = "otp_verify";
            // $select = array('*');
            // $condition = array('otp' => $otp, 'verify' =>1);
            // $ArrayData = $this->Md_database->getData($table, $select, $condition, '', '1');
             $ArrayData=$this->Md_login->OTPVerifyNow($otp);
            
            // echo '<pre>';
            // print_r($ArrayData);
            // die;
            if(!empty($ArrayData))
            {
                $table = "otp_verify";
                $updareData = array('verify' => 2);
                $condition = array('pk_id'=>$ArrayData->pk_id);
                $ArrayData=$this->Md_login->UpdateData($table, $condition, $updareData);
                 
                $final = array('status' => 1, 'msg'=>"OTP is verify successfully.");
            }else {
              $final = array('status' => 2,'msg'=>"You enter wrong otp.");   
            }
        } else {
            $final = array('status' => 2,'msg'=>"OTP is empty.");
        }
        
        echo json_encode($final);
        exit();
    }
        
     public function ReactOTPSend() 
     {
        header("Access-Control-Allow-Origin: *");
        // If you need to allow specific methods
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
        // If you need to allow specific headers
        header("Access-Control-Allow-Headers: Content-Type, Authorization");
        $datas = json_decode(file_get_contents("php://input"), true);
        $Mobile=$datas['Mobile'];
      
    //   $final = array('status' => 1, 'msg'=>"OTP send on register mobile no.");
    //     echo json_encode($final);
    //     exit();
        
        error_reporting(0);
        // $Mobile = $this->input->post('Mobile');
        $otp = mt_rand(100000, 999999);
        $final = array();
        $ArrayData = array();
        
        if (!empty($Mobile)) 
        {
            // $table = "login";
            // $select = array('*');
            // $condition = array('username' => $Mobile, 'status !=' => '3');
            // $ArrayData = $this->Md_database->getData($table, $select, $condition, '', '1');

            $ArrayData=$this->Md_login->MobilenoUniqueCheck($Mobile);
 
            if (!empty($ArrayData)) {
                $final = array('status' => 3,'msg'=>"Mobile no is register with us.");
            } else {
                
            // $table = "otp_verify";
            // $select = array('otp');
            // $condition = array('mobile' => $Mobile, 'verify' => 1);
            // $ArrayDatas = $this->Md_database->getData($table, $select, $condition, '', '1');
          
            $ArrayDatas=$this->Md_login->OTPVerifyCheck($Mobile);
              
          
            if(!empty($ArrayDatas))
            {
                $otp=$ArrayDatas->otp;
            }else {

                $table = 'otp_verify';
                $data = array(
                    'mobile' => $Mobile,
                    'otp' => $otp,
                    'verify' =>1,
                    'ip_address' => $_SERVER['REMOTE_ADDR'],
                );
                $this->Md_login->InsertLoginAction($table, $data);
            }
                // $table = "sms_master";
                // $select = array('link,username,password,senderid');
                // $condigtion = array('status' => '1');
                // $arraySMSApi = $this->Md_database->getData($table, $select, $condigtion, '', '1');
                
                  
                $arraySMSApi=$this->Md_sms->SmsConfigGet();

                if (!empty($arraySMSApi)) {
                    $smslink = "";
                    $username = "";
                    $password = "";
                    $senderid = "";
                    $smslink = $arraySMSApi->link;
                    $username =$arraySMSApi->username;
                    $password = $arraySMSApi->password;
                    $senderid =$arraySMSApi->senderid;
                    $message = urlencode($otp . " is your OTP for mobile no verification on MVPM Hostel Apply Form. Do not share with anyone. link : https://www.mvpm.org/hostel/ - MVPM");
                    $url = $smslink . "?username=" . $username . "&password=" . $password . "&senderid=" . $senderid . "&route=1&numbers=$Mobile&message=$message&dndrefund=1";
                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, $url);
                    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    $contents = curl_exec($ch);
                    $return_val = curl_close($ch);
                    $return_val;
                }
            
                $final = array('status' => 1, 'msg'=>"OTP send on register mobile no.");
            }

        } else {
            $final = array('status' => 2,'msg'=>"Mobile no is empty.");
        }
        
        echo json_encode($final);
        exit();
    }
    
    public function ReactMobileNumberCheckUnique() 
    {
       
        header("Access-Control-Allow-Origin: *");
        // If you need to allow specific methods
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
        // If you need to allow specific headers
        header("Access-Control-Allow-Headers: Content-Type, Authorization");
        $datas = json_decode(file_get_contents("php://input"), true);
        $Mobile=$datas['Mobile'];
        
        $final = array();
        $ArrayData = array();

        if (!empty($Mobile)) {

            // $table = "login";
            // $select = array('*');
            // $condition = array('username' => $Mobile, 'status !=' => '3');
            // $ArrayData = $this->Md_database->getData($table, $select, $condition, '', '1');
            
           
            $ArrayData=$this->Md_login->MobilenoUniqueCheck($Mobile);
             
            if (!empty($ArrayData)) {
                $final = array('status' => 1);
            } else {
                $final = array('status' => 2);
            }
        } else {
            $final = array('status' => 3);
        }
        echo json_encode($final);
        exit();
    }
    
    public function ReactLoginAction() 
    {   
    
        header("Access-Control-Allow-Origin: *");
        // If you need to allow specific methods
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
        // If you need to allow specific headers
        header("Access-Control-Allow-Headers: Content-Type, Authorization");
        
        $datas = json_decode(file_get_contents("php://input"), true);
        $Mobile=$datas['Mobile'];
        $Password=$datas['Password'];

        if (!empty($Mobile) && !empty($Password)) 
        {
            $EncryPassword = md5($Password);

            // $year = date('Y');
            // $table = "login";
            // $fields = array('*');
            // $condition = array('mobile' => $Mobile, 'password' => $EncryPassword, 'status' => '1');
            // $arrayUser = $this->Md_database->getData($table, $fields, $condition, 'id DESC', '1');

           
            $arrayUser=$this->Md_login->loginCheck($Mobile, $EncryPassword);

            if (empty($arrayUser)) {
                
                $final = array('status' => 2, 'sms' =>'Sorry! mobile or password is wrong.','url'=>'login','logintype'=>'user');
                echo json_encode($final);
                exit();   

            } else if (!empty($arrayUser) && $arrayUser->status == "2") 
            {
                
                $final = array('status' => 2, 'sms' =>'Sorry! student not active..','url'=>'login','logintype'=>'user');
                echo json_encode($final);
                exit();            

            } else if (!empty($arrayUser) && $arrayUser->status == "1") {


                $table = 'student_login_activity';
                $data = array(
                    'fk_stud_id' => $arrayUser->id,
                    'logout_date' => '',
                    'login_date' => date('Y-m-d H:i:s'),
                    'ip_address' => $_SERVER['REMOTE_ADDR'],

                );
                
                $this->Md_login->InsertLoginAction($table, $data);

            $final = array('status' => 1, 'sms' =>'Thanks! you are login successfully.','url'=>'payhistory','logintype'=>'user','loginid'=> $arrayUser->id);
            echo json_encode($final);
            exit();
            }

        } else {

            $final = array('status' => 2, 'sms' =>'Sorry...something went wrong.');
            echo json_encode($final);
            exit();

        }
    }
    
    
    
    public function ChangeTypeofAdminission() 
    {   
   
        header("Access-Control-Allow-Origin: *");
        // If you need to allow specific methods
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
        // If you need to allow specific headers
        header("Access-Control-Allow-Headers: Content-Type, Authorization");
        $datas = json_decode(file_get_contents("php://input"), true);
        
        $PermentAdmission=$datas['PermentAdmission'];
        $TempraryAdmission=$datas['TempraryAdmission'];
        $uid=$datas['uid'];

        try {
            
        if (!empty($PermentAdmission) || !empty($TempraryAdmission) && !empty($uid)) 
        {
            if(!empty($PermentAdmission))
            {
                $typeof_admission_want=$PermentAdmission;
            }else {
                $typeof_admission_want=$TempraryAdmission;
            }
            
            
            $MVPMAcademicYear = date("Y") . '-' . date('y', strtotime('+1 year'));
      
            $table = 'student';
            $data = array(
                'fk_login_id' => $uid,
                'typeof_admission_want' =>$typeof_admission_want,
                'created_date' => date('Y-m-d H:i:s'),
                'year' => date('Y'),
                'ip_address' => $_SERVER['REMOTE_ADDR'],
                'status' => '1',
                'password_change_status' => '1',
                'StudentAdmission' => 'newstudent',
                'MVPMAcademicYear' => $MVPMAcademicYear
            );


            $arrayUser=$this->Md_login->InsertLoginAction($table, $data);

            if (empty($arrayUser)) {
                
                $final = array('status' => 2, 
                'msg' =>'Sorry! something went wrong.',
                'url'=>'login',
                'logintype'=>'user');
                
                echo json_encode($final);
                exit();   

            }else if (!empty($arrayUser)) {

                $final = array('status' => 1, 
                'msg' =>'Your type of adminission is changed',
                'logintype'=>'user',
                'loginid'=>$uid,
                'app_id'=> $arrayUser);
                
                echo json_encode($final);
                exit();
            }

        } else {

            $final = array('status' => 2, 'msg' =>'Sorry...something went wrong.');
            echo json_encode($final);
            exit();
        }
        }catch(Exception $e) {

            $final = array('status' => 2, 'msg' =>$e);
            echo json_encode($final);
            exit();   
        }
    }
}
