<?php
namespace App\Controllers;
use App\Models\Homem;
class Api extends \Core\Controller
{
    // {
    //     "apikey":"VsY1Nu70hbgZdGFv4JIHmSaeMxpRUDyoLkctrXW3", 
    //     "secrectkey":"89deBAchMkE0SynN1JlsGwCb6Tu3RtKIZ4aL2rQX", 
    //     "no":"232X1A0501", 
    //     "orgid":"3"
    //      "primary":"true",
    //      "usertype":"1",
    //      "mobiletype":"1",
    //      "mobileno":"",
    //      "studid":""
    //      "name"
    // }
    private $_success;
    private $_messages;
    private $_userdetails;
    private $_useraddress;
    private $_usereducation;
    private $_userwrkexp;
    private $_data;
    private $_httpStatusCode;
    private $_toCache = false;
    private $_responseData = array();
    public function setSuccess($success) {
        $this->_success = $success;
    }
    public function addMessage($message) {
        $this->_messages = $message;
    }
    public function addUserDetails($userdetails) {
        $this->_userdetails = $userdetails;
    }
    public function addUserAddress($useraddress) {
        $this->_useraddress = $useraddress;
    }
    public function addUserEducation($usereducation) {
        $this->_usereducation = $usereducation;
    }
    public function addUserWrkExp($userwrkexp) {
        $this->_userwrkexp = $userwrkexp;
    }
    public function setData($data) {
        $this->_data = $data;
    }
    public function setHttpStatusCode($httpStatusCode) {
        $this->_httpStatusCode = $httpStatusCode;
    }
    public function toCache($toCache) {
        $this->_toCache = $toCache;
    }
    public function send() 
    {
        if($_SERVER["CONTENT_TYPE"] == "application/json" || $_SERVER["CONTENT_TYPE"] == "text/plain" || $_SERVER["CONTENT_TYPE"] == "")
        {
            header('Content-type:application/json;charset=utf-8');
        }
        if($this->_toCache == true) {
            header('Cache-Control: max-age=60');
        }
        else 
        {
            header('Cache-Control: no-cache, no-store');
        }
        if(!is_numeric($this->_httpStatusCode) || ($this->_success !== false && $this->_success !== true )) {
            http_response_code(500);
            $this->_responseData['statusCode'] = 500;
            $this->_responseData['success'] = false;
            $this->addMessage("Response creation error");
            $this->_responseData['messages'] = $this->_messages;
        }
        else 
        {
            http_response_code($this->_httpStatusCode);
            $this->_responseData['statusCode'] = $this->_httpStatusCode;
            $this->_responseData['success'] = $this->_success;
            $this->_responseData['messages'] = $this->_messages;
            $this->_responseData['userdetails'] = $this->_userdetails;
            //$this->_responseData['useraddress'] = $this->_useraddress;
            // $this->_responseData['usereducationdetails'] = $this->_usereducation;
            // $this->_responseData['userworkexperirnce'] = $this->_userwrkexp;
            // $this->_responseData['data'] = $this->_data;
        }
        if($_SERVER["CONTENT_TYPE"] == "application/json" || $_SERVER["CONTENT_TYPE"] == "text/plain" || $_SERVER["CONTENT_TYPE"] == "")
        {
            echo json_encode($this->_responseData); //htmlentities()
            // use stripslashes() for getting actual html tages
        }
        if($_SERVER["CONTENT_TYPE"] == "application/xml")
        {
            header('content-type: text/xml;charset=utf-8');
            echo Api::arrayToXml($this->_responseData);
        }
    }
    function isJSON($string){
        return is_string($string) && is_array(json_decode($string, true)) && (json_last_error() == JSON_ERROR_NONE) ? true : false;
    }
    private static function apivalidation($apie, $sece)
    {
        $api = "VsY1Nu70hbgZdGFv4JIHmSaeMxpRUDyoLkctrXW3";
        $sec = "89deBAchMkE0SynN1JlsGwCb6Tu3RtKIZ4aL2rQX";
        if($api == $apie && $sec == $sece)
        {
            return "1";
        }
        else
        {
            return "0";
        }
    }
    public function getusername()
    {
        $json = file_get_contents('php://input');    
        $data = null;   
        if($this->isJSON($json))
        {
          $data = json_decode($json);
        }
        if($data != null)
        {
            $apikey = $data->apikey;
            $secretkey = $data->secrectkey;
            $no = $data->no;
            $orgid = $data->orgid;
            $_SESSION["org_id"]=$orgid;
            $apivalidation = static::apivalidation($apikey, $secretkey);
            if($apivalidation == 1)
            {
                $log = Homem::getdata("SELECT id, name FROM `user_master` WHERE `no`='$no'");
                if(sizeof($log) == 1)
                {
                    // $user_id = $log[0]['name'];
                    // $user = Apim::user($user_id);
                    // $user_edu = Apim::useredu($user_id);
                    // $user_workexperience = Apim::userwork($user_id);
                    $this->setSuccess(true);
                    $this->setHttpStatusCode(200);
                    $this->addMessage('The Request is Successfull.. Please Find The Details..');
                    $this->addUserDetails($log);
                }
                // else
                // {
                //     $this->setSuccess(false);
                //     $this->setHttpStatusCode(400); 
                // }
            }
        }
        else
        {
            $this->setSuccess(false);
            $this->setHttpStatusCode(400); 
        }
        $this->send();
    }
    public function getfeedues()
    {
        $json = file_get_contents('php://input');    
        $data = null;   
        if($this->isJSON($json))
        {
          $data = json_decode($json);
        }
        if($data != null)
        {
            $apikey = $data->apikey;
            $secretkey = $data->secrectkey;
            $no = $data->no;
            $orgid = $data->orgid;
            $_SESSION["org_id"]=$orgid;
            $apivalidation = static::apivalidation($apikey, $secretkey);
            if($apivalidation == 1)
            {
                $log = Homem::getdata("SELECT um.id, um.no, um.name, um.squota, COALESCE(sf.actual, 0) AS actual, COALESCE(sn.paid, 0) AS paid, (COALESCE(sf.actual, 0) - COALESCE(sn.paid, 0)) AS due FROM user_master um LEFT JOIN ( SELECT no, SUM(feeamount) AS actual FROM stdnt_feemaster WHERE year = '1' GROUP BY no ) sf ON um.id = sf.no LEFT JOIN ( SELECT no, SUM(amount) AS paid FROM stdnt_normalfee WHERE year = '1' GROUP BY no ) sn ON um.id = sn.no WHERE um.fk_course_id = '1' AND um.fk_dept_id = '5' AND um.fromyear = '2023'");
                if(sizeof($log) == 1)
                {
                    $this->setSuccess(true);
                    $this->setHttpStatusCode(200);
                    $this->addMessage('The Request is Successfull.. Please Find The Details..');
                    $this->addUserDetails($log);
                }
            }
        }
        else
        {
            $this->setSuccess(false);
            $this->setHttpStatusCode(400); 
        }
        $this->send();
    }
    public function whatappmobileotp()
    {
        $json = file_get_contents('php://input');    
        $data = null;   
        if($this->isJSON($json))
        {
          $data = json_decode($json);
        }
        if($data != null)
        {
            $apikey = $data->apikey;
            $secretkey = $data->secrectkey;
            $no = $data->no;
            $orgid = $data->orgid;
            $_SESSION["org_id"]=$orgid;
            $primary = $data->primary;
            $usertype = $data->usertype;// 1-Student , 2- Father 3 - mother 4 gaurdian
            $mobiletype = $data->mobiletype; // 1 whatspp 2 sms
            $studid = $data->studid;
            $mobile = $data->mobileno;
            $name = $data->name;
            $apivalidation = static::apivalidation($apikey, $secretkey);
            if($apivalidation == 1)
            {
                $otp = substr(number_format(time() * rand(),0,'',''),0,6);
                if($mobiletype == 1)
                {
                    $message = "Dear *".$name."*, OTP for Mobile Verification is *".$otp."*-Hindu College";
                    $sent = json_decode(static::whatsappmobileapi($mobile, $message), true);
                }
                if($mobiletype == 2)
                {
                    $sent = static::sendmobileotp($name, $otp, $mobile);
                }
            }

        }
    }
    public function whatappmobileotpverification()
    {
        $json = file_get_contents('php://input');    
        $data = null;   
        if($this->isJSON($json))
        {
          $data = json_decode($json);
        }
        if($data != null)
        {
            $apikey = $data->apikey;
            $secretkey = $data->secrectkey;
            $no = $data->no;
            $orgid = $data->orgid;
            $_SESSION["org_id"]=$orgid;
            $primary = $data->primary;
            $usertype = $data->usertype;// 1-Student , 2- Father 3 - mother 4 gaurdian
            $mobiletype = $data->mobiletype; // 1 whatspp 2 sms
            $studid = $data->studid;
            $mobile = $data->mobileno;
            $name = $data->name;
            $otp = $data->otp;
            $apivalidation = static::apivalidation($apikey, $secretkey);
            if($apivalidation == 1)
            {
                $otp = substr(number_format(time() * rand(),0,'',''),0,6);
                if($mobiletype == 1)
                {
                    $message = "Dear *".$name."*, OTP for Mobile Verification is *SUCCESSFULL*-Hindu College";
                    $sent = json_decode(static::whatsappmobileapi($mobile, $message), true);
                }
                if($mobiletype == 2)
                {
                    echo '{"status":"success"}';
                }
            }

        }
    }
    public static function whatsappmobileapi($mobile, $message)
    {
        $curl = curl_init();
        curl_setopt_array($curl, array(
          CURLOPT_URL => 'https://app2.wappapi.in/api/send',
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => '',
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 0,
          CURLOPT_FOLLOWLOCATION => true,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => 'GET',
          CURLOPT_POSTFIELDS =>'{"number": "91'.$mobile.'", "type":"text", "message": "'.$message.'", "instance_id":"656EE4156E5C8", "access_token":"6486cd78d440f"}',
          CURLOPT_HTTPHEADER => array(
            'Content-Type: application/json',
            'Cookie: stackpost_session=gtsjihe0imttusibhpnmlqrlmsi3kanl'
          ),
        ));
        
        $response = curl_exec($curl);
        curl_close($curl);
        echo $response;

    }
    public static function shortname($name)
    {
        $size =  strlen($name);
        if($size<50)
        {
            return $name;
        }
        else
        {
            return 'Student';
        }
        
    }
    public static function sendmobileotp($name, $otp, $mobile)
    {
        $name = static::shortname($name);
        $input = 'Dear '.$name.', OTP for Mobile Verification is '.$otp.' - Hindu College';
        $url = 'https://api.mylogin.co.in/api/v2/SendSMS?ApiKey=9FYw45bZk/traX4phb0DCEb9KFiQkNOD8suGLWVgzK8=&ClientId=38ee5f8c-f4e9-42a3-b671-9a8f02121553&SenderId=HNDGNT&Message='.rawurlencode($input).'&MobileNumbers=91'.$mobile.'&Is_Unicode=false&Is_Flash=false';
        $curl = curl_init();
        curl_setopt_array($curl, array(
          CURLOPT_URL => $url,
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => '',
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 0,
          CURLOPT_FOLLOWLOCATION => true,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => 'GET',
          CURLOPT_HTTPHEADER => array(
            'Content-Type: application/json'
          ),
        ));
        
        $response = curl_exec($curl);
        
        curl_close($curl);
        // echo $response;
        return 1;
    }

    public static function arrayToXml($array, $rootElement = null, $xml = null) { 
        $_xml = $xml; 
        
        // If there is no Root Element then insert root 
        if ($_xml === null) { 
            $_xml = new \SimpleXMLElement($rootElement !== null ? $rootElement : '<root/>'); 
        } 
        
        // Visit all key value pair 
        foreach ($array as $k => $v) { 
            
            // If there is nested array then 
            if (is_array($v)) {  
                
                // Call function for nested array 
                if(is_numeric($k)){$k = 'a'.$k;}
                static::arrayToXml($v, $k, $_xml->addChild($k)); 
                } 
                
            else { 
                
                // Simply add child element.  
                if(is_numeric($k)){$k = 'a'.$k;}
                $_xml->addChild($k, htmlspecialchars($v)); 
            } 
        } 
        
        return $_xml->asXML(); 
    } 
    public function testc($channel)
    {
     foreach ($channel as $element => $content) {
        print " <$element>";
        print htmlentities($content);
        print "</$element>\n";
     }
     
     print "</channel>";
    }
    public function test()
    {
        // header('content-type: text/xml;charset=utf-8');
        $curl = curl_init();
        curl_setopt_array($curl, array(
        CURLOPT_URL => "http://fms.hinduengg.com/Api/getfeedues",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "GET",
        CURLOPT_POSTFIELDS =>"{\"apikey\":\"VsY1Nu70hbgZdGFv4JIHmSaeMxpRUDyoLkctrXW3\", \"secrectkey\":\"89deBAchMkE0SynN1JlsGwCb6Tu3RtKIZ4aL2rQX\", \"no\":\"232X1A0501\", \"orgid\":\"3\"}",
        CURLOPT_HTTPHEADER => array(
            ": ",
            "Content-Type: application/json"//text/plain" // application/json // xml
        ),
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        //$data = $response;
        echo $response;
    }
    public static function testb()
    {
        $mobile= "9494470239";
        $message = "*test* from testb page api integration php";
        static::sendmobileotp("krish", "34567", "9494470239");
        static::whatsappmobileapi($mobile, $message);
    }
    
    public static function mail()
    {
        $subject = "Test mail";
          $to_email = "s.krishanrjuna@gmail.com";
          $to_fullname = "John Doe";
          $from_email = "noreply@hinduengg.com";
          $from_fullname = "Jane Doe";
          $headers  = "MIME-Version: 1.0\r\n";
          $headers .= "Content-type: text/html; charset=utf-8\r\n";
          // Additional headers
          // This might look redundant but some services REALLY favor it being there.
          $headers .= "To: $to_fullname <$to_email>\r\n";
          $headers .= "From: $from_fullname <$from_email>\r\n";
          $message = "<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">\r\n
          <head>\r\n
            <title>Hello Test</title>\r\n
          </head>\r\n
          <body>\r\n
            <p></p>\r\n
            <p style=\"color: #00CC66; font-weight:600; font-style: italic; font-size:14px; float:left; margin-left:7px;\">You have received an inquiry from your website.  Please review the contact information below.</p>\r\n
          </body>\r\n
          </html>";
          if (!mail($to_email, $subject, $message, $headers)) { 
            print_r(error_get_last());
          }
          else 
          { 
            echo '<h3 style="color:#d96922; font-weight:bold; height:0px; margin-top:1px;">Thank You For Contacting us!!</h3>';
          }
    }
    
    public static function gmail()
    {
        // 51289059599-en30pdqjb1j7km2f6p50lmh50jbve4og.apps.googleusercontent.com
        // Initialize the Gmail API client
        $client = new Google_Client();
        $client->setAuthConfig('path/to/client_credentials.json'); // Path to your downloaded credentials
        $client->setAccessType('offline');
        $client->addScope(Google_Service_Gmail::GMAIL_SEND);
        
        // Authorize the client
        $accessToken = '51289059599-en30pdqjb1j7km2f6p50lmh50jbve4og.apps.googleusercontent.com'; // Obtain access token using OAuth 2.0
        $client->setAccessToken($accessToken);
        
        // Create Gmail service
        $service = new Google_Service_Gmail($client);
        
        // Create email content
        $message = new Google_Service_Gmail_Message();
        $email = "To: s.krishnarjuna@gmail.com\r\n";
        $email .= "Subject: Test Email via Gmail API\r\n";
        $email .= "\r\n";
        $email .= "This is a test email sent from PHP using Gmail API.";
        $message->setRaw(base64_encode($email));
        
        // Send the email
        try {
            $service->users_messages->send("me", $message);
            echo "Email sent successfully!";
        } catch (Exception $e) {
            echo "Error: " . $e->getMessage();
        }
    }
    
    
    
    /*APP Api starting*/
    
    public function studentstrength()
    {
        $json = file_get_contents('php://input');    
        $data = null;   
        if($this->isJSON($json))
        {
          $data = json_decode($json);
        }
        if($data != null)
        {
            $apikey = $data->apikey;
            $secretkey = $data->secrectkey;
            $apivalidation = static::apivalidation($apikey, $secretkey);
            if($apivalidation == 1)
            {
                $_SESSION["org_id"]= "6";
                $data1 = Homem::getdata("SELECT * FROM `app_student_strength`");
                $this->setSuccess(true);
                $this->setHttpStatusCode(200);
                $this->addMessage('The Request is Successfull.. Please Find The Details..');
                $this->addUserDetails($data1);
            }
        }
        $this->send();
    }
    public function institutionprofile()
    {
        $json = file_get_contents('php://input');    
        $data = null;   
        if($this->isJSON($json))
        {
          $data = json_decode($json);
        }
        if($data != null)
        {
            $apikey = $data->apikey;
            $secretkey = $data->secrectkey;
            $apivalidation = static::apivalidation($apikey, $secretkey);
            if($apivalidation == 1)
            {
                $_SESSION["org_id"]= "6";
                $data1 = Homem::getdata("SELECT * FROM `app_instituion_profile`");
                // $data1 = str_replace('<', '\\', (json_encode('[{"id":"1","name":"Admission Fee"},{"id":"2","name":"TC Fee"},{"id":"3","name":"PCB Design Fee"},{"id":"4","name":"Embedded Systems & IoT Fee"},{"id":"5","name":"Coaching Fee"}]')));
                // // $data1 = "";str_replace('<', '//', (json_encode($data)))
                $this->setSuccess(true);
                $this->setHttpStatusCode(200);
                $this->addMessage('The Request is Successfull.. Please Find The Details..');
                $this->addUserDetails($data1);
            }
        }
        $this->send();
    }
    public function listofcourses()
    {
        $json = file_get_contents('php://input');    
        $data = null;   
        if($this->isJSON($json))
        {
          $data = json_decode($json);
        }
        if($data != null)
        {
            $apikey = $data->apikey;
            $secretkey = $data->secrectkey;
            $apivalidation = static::apivalidation($apikey, $secretkey);
            if($apivalidation == 1)
            {
                $_SESSION["org_id"]= "6";
                $data1 = Homem::getdata("SELECT * FROM `app_course_details`");
                // $data1 = str_replace('<', '\\', (json_encode('[{"id":"1","name":"Admission Fee"},{"id":"2","name":"TC Fee"},{"id":"3","name":"PCB Design Fee"},{"id":"4","name":"Embedded Systems & IoT Fee"},{"id":"5","name":"Coaching Fee"}]')));
                // // $data1 = "";str_replace('<', '//', (json_encode($data)))
                $this->setSuccess(true);
                $this->setHttpStatusCode(200);
                $this->addMessage('The Request is Successfull.. Please Find The Details..');
                $this->addUserDetails($data1);
            }
        }
        $this->send();
    }
    public function listofcoursesbyorgid()
    {
        $json = file_get_contents('php://input');    
        $data = null;   
        if($this->isJSON($json))
        {
          $data = json_decode($json);
        }
        if($data != null)
        {
            $apikey = $data->apikey;
            $secretkey = $data->secrectkey;
            $org = $data->orgid;
            $apivalidation = static::apivalidation($apikey, $secretkey);
            if($apivalidation == 1)
            {
                $_SESSION["org_id"]= "6";
                $data1 = Homem::getdata("SELECT * FROM `app_course_details` WHERE `org_id`='$org'");
                // $data1 = str_replace('<', '\\', (json_encode('[{"id":"1","name":"Admission Fee"},{"id":"2","name":"TC Fee"},{"id":"3","name":"PCB Design Fee"},{"id":"4","name":"Embedded Systems & IoT Fee"},{"id":"5","name":"Coaching Fee"}]')));
                // // $data1 = "";str_replace('<', '//', (json_encode($data)))
                $this->setSuccess(true);
                $this->setHttpStatusCode(200);
                $this->addMessage('The Request is Successfull.. Please Find The Details..');
                $this->addUserDetails($data1);
            }
        }
        $this->send();
    }
    public function aboutcoursebyid()
    {
        $json = file_get_contents('php://input');    
        $data = null;   
        if($this->isJSON($json))
        {
          $data = json_decode($json);
        }
        if($data != null)
        {
            $apikey = $data->apikey;
            $secretkey = $data->secrectkey;
            $id = $data->id;
            $apivalidation = static::apivalidation($apikey, $secretkey);
            if($apivalidation == 1)
            {
                $_SESSION["org_id"]= "6";
                $data1 = Homem::getdata("SELECT `course_name`, `dept_name`, `course_type`, `intake`, `noofyears`, `totalfee`, `tutionfee`, `addonfee`, `ncc`, `nss` FROM `app_course_details` WHERE `id`='$id' AND `status`='1'");
                $data2= Homem::getdata("SELECT `description` FROM `app_about_course` WHERE `fk_course_id`='$id' AND `status`='1'");
                $data4= Homem::getdata("SELECT `eligibility` FROM `app_course_eligibility` WHERE `fk_course_id`='$id' AND `status`='1'");
                $data5= Homem::getdata("SELECT `process` FROM `app_admission_process` WHERE `fk_course_id`='$id' AND `status`='1'");
                // $data3=array();
                $data3["course_name"] = $data1["0"]["course_name"];
                $data3["dept_name"] = $data1["0"]["dept_name"];
                $data3["course_type"] = $data1["0"]["course_type"];
                $data3["intake"] = $data1["0"]["intake"];
                $data3["noofyears"] = $data1["0"]["noofyears"];
                $data3["totalfee"] = $data1["0"]["totalfee"];
                $data3["tutionfee"] = $data1["0"]["tutionfee"];
                $data3["addonfee"] = $data1["0"]["addonfee"];
                $data3["ncc"] = $data1["0"]["ncc"];
                $data3["nss"] = $data1["0"]["nss"];
                $data3["aboutcourse"] = $data2;
                $data3["eligibility"] = $data4;
                $data3["process"] = $data5;
                $this->setSuccess(true);
                $this->setHttpStatusCode(200);
                $this->addMessage('The Request is Successfull.. Please Find The Details..');
                $this->addUserDetails($data3);
            }
        }
        $this->send();
    }
}