<?php
namespace App\Controllers;
use App\Models\Homem;
class Erp extends \Core\Controller
{
    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;
        }
        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 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;
            list($course, $dept, $joinyear, $year) = explode('-', $no);
            $_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 = '$year' GROUP BY no ) sf ON um.id = sf.no LEFT JOIN ( SELECT no, SUM(amount) AS paid FROM stdnt_normalfee WHERE year = '$year' GROUP BY no ) sn ON um.id = sn.no WHERE um.fk_course_id = '$course' AND um.fk_dept_id = '$dept' AND um.fromyear = '$joinyear'");
                if(sizeof($log) > 0)
                {
                    $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 studentfeedata()
    {
        $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)
            {
                $udata = Homem::getdata("SELECT * FROM `user_master` WHERE `no`='$no'");
                $id= $udata[0]["id"];
                $log["actual"] = Homem::getdata("SELECT * FROM `stdnt_feemaster` WHERE `no`='$id'");
                $log["paid"] = Homem::getdata("SELECT * FROM `stdnt_normalfee` WHERE `no`='$id'");
                $log["type"] = Homem::getdata("SELECT * FROM `fee_types`");
                $log["mode"] = Homem::getdata("SELECT * FROM `fee_mode`");
                $log["userdata"] = $udata;
                if(sizeof($log) > 0)
                {
                    $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 static function shortname($name)
    {
        $size =  strlen($name);
        if($size<50)
        {
            return $name;
        }
        else
        {
            return 'Student';
        }
        
    }


    public function test()
    {
        $curl = curl_init();
        curl_setopt_array($curl, array(
        CURLOPT_URL => "http://fms.hinduengg.com/Erp/studentfeedata",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS =>"{\"apikey\":\"VsY1Nu70hbgZdGFv4JIHmSaeMxpRUDyoLkctrXW3\", \"secrectkey\":\"89deBAchMkE0SynN1JlsGwCb6Tu3RtKIZ4aL2rQX\", \"no\":\"232X1A0501\", \"orgid\":\"3\"}",
        CURLOPT_HTTPHEADER => array(
            "Content-Type: application/json"
        ),
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        echo $response;
    }

}