<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Welcome extends CI_Controller {

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     * 		http://example.com/index.php/welcome
     * 	- or -  
     * 		http://example.com/index.php/welcome/index
     * 	- or -
     * Since this controller is set as the default controller in 
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see http://codeigniter.com/user_guide/general/urls.html
     */
    public function __construct() {
        parent::__construct();
        $this->load->model('site');
    }

    public function index() {
        $this->load->view('header');
        $data['categories']=$this->site->getAll('ticket_category');
        // $data['grade']=$this->site->getAll('grade');
        // $data['state']=$this->site->getAll('state');
        // $data['country']=$this->site->getAll('countries');        
        $this->load->view('body',$data);
        $this->load->view('footer');
    }
    
    public function confirm(){
        $data['categories']=$this->site->getAll('ticket_category');
        $data['category']=$this->input->post('category');
        $data['niqsNo']=$this->input->post('niqsNo');
        $data['names']=$this->input->post('names');
        $data['phone']=$this->input->post('phone');
        $data['email']=$this->input->post('email');
        $data['company']=$this->input->post('company');
        $data['address']=$this->input->post('address');
       // $data['location']=$this->input->post('location');
        $this->load->view('header');
        $this->load->view('confirm',$data);
        $this->load->view('footer');
    }
    
    public function insertDetails(){
        $category=$this->input->post('category');
        $niqsNo=$this->input->post('niqsNo');
        $names=$this->input->post('names');
        $phone=$this->input->post('phone');
        $email=$this->input->post('email');
        $company=$this->input->post('company');
        //$location=$this->input->post('location');
        $authNum=$this->randomString(9);
        $date=date('Y-m-d');
        $amount=$this->site->getAny('ticket_category',$category,'cat_id','cat_amount');
        
        $insert=$this->site->insertDetails($category,$niqsNo,$names,$phone,$email,$company,$authNum);
        if($insert){
            //redirect to payment page
             /* $passport = 'passport';
     
        $photo = "passConf" . $insert . ".jpg";
        $config['upload_path'] = "./pictures/";
        $config['file_name'] = $photo;
        $config['max_size'] = '1000';
        $config['overwrite'] = TRUE;


        // set the filter image types
        $config['allowed_types'] = 'jpg';

        //load the upload library
        $this->load->library('upload', $config);

        $this->upload->initialize($config);

        $this->upload->set_allowed_types('*');

        $data['upload_data'] = '';
        if (!$this->upload->do_upload($passport)) {
            $data = array('msg' => $this->upload->display_errors());
            echo $this->upload->display_errors();
            
        } */
            
            
            
            
            $this->site->insertTrans($date, $appType=999, $amount, 'Pending', $insert, $authNum);
            redirect('welcome/pay/'.$authNum,'refresh');
        }
        
        
    }
       public function set_barcode($code)
	{
		//load library
		$this->load->library('zend');
		//load in folder Zend
		$this->zend->load('Zend/Barcode');
		//generate barcode
		Zend_Barcode::render('code128', 'image', array('text'=>$code), array());
	}
    
    public function printBadge(){
        $transID=$this->input->post('transactionID');
        $data['details']=$this->site->getTransaction($transID);
        //$this->load->view('header');
        $this->load->view('badge',$data);
        //$this->load->view('footer');
    }
    public function printCert(){
        $this->load->view('header');
        $this->load->view('printCert');
        $this->load->view('footer');
    }
    public function printCert2(){
        $transID=$this->input->post('transNo'); //$this->downloadCert($transID);
        if (isset($_POST['print'])){
        $data['details']=$this->site->getTransaction($transID);
        //$this->load->view('header');
        $this->load->view('cert',$data);
	} elseif (isset($_POST['pdf'])){
	 $this->downloadCert($transID);
	}
    }
public function downloadCert($transID){
        $details= $this->site->getTransaction($transID);

       if(!empty($details)){
         foreach($details as $row){}
         if($row['transStatus'] =='PAID'){

$html = '<?php ob_start(); ?><html>
    <head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
            <link href="http://fonts.googleapis.com/css?family=Oleo+Script" rel="stylesheet" type="text/css">
<style>
body{background: no-repeat  url("./images/cert.jpg") center; height:800px !important;}
* {margin:2px; padding:2px;}
body{font:24px Georgia, serif;}
    #printArea { position: fixed; left: 5px; top: 340px; right: 5px; height: 120px; text-align: center; }
</style>
        </head>
         <body>
            <div id="printArea">

                <div style="font: 400 20px/1.3 "Arial"; position:fixed; top: 275px; text-align:center;">
                    '.strtoupper($row['confName']).'</div>
                
            </div>
         </body></html> <?php ob_end_flush(); ?>';

        $this->load->library('dompdf_gen'); 
        $this->dompdf->load_html($html);
        $this->dompdf->set_paper("A4", "Landscape");
        $this->dompdf->render();
        $filename = "Makurdi_Certificate20160728".date('his');
            if( !empty($filename)) {
            $this->dompdf->stream($filename.".pdf"); // to Download PDF
            } else if ($stream) {            
            $this->dompdf->stream($filename.".pdf",array('Attachment'=>0));// to open in a window
            } else {
                return $this->dompdf->output();
            }
            return $this->dompdf->output();
            //file_put_contents("/path/to/file.pdf", $output);
         }
                                
        else { echo "Invalid form/Receipt Number";}
        }
    }
    public function pay($transID) {
        //send Email with App;ication Number
        $email=$this->site->getAny('ticket_conference',$transID,'confAuthNum','confEmail');
        $names=$this->site->getAny('ticket_conference',$transID,'confAuthNum','confName');
        $message='Dear '.$names.",<br> Thank you for registering for Nigerian Institute of Quantity Surveyors Conference.<br />Your Application No:<strong>".$transID."</strong><br /><br />Best regards.<br /><br />Conferenec Committee ";
        //$this->sendEmail($email,$message);
        $data['application'] = $this->site->getApplication($transID);

        $this->load->view('header');
        $this->load->view('pay', $data);
        $this->load->view('footer');
    }
     public function payResult($transID) {
        //echo $transID;
        $ref = $this->input->post('tx_ref');
        //$transID=$this->input->post('transID');
        //echo $ref;
        //$clientId = "localhost";
        //$secretKey = "E9300DJLXKJLQJ2993N1190023";
       //$secretKey="E7VELRHBJ6FWKE2ZK861L4F5HDKCDY";
	   $clientId = "portal.niqs.org.ng";
       $secretKey = "E7VELRHBJ6FWKE2ZK861L4F5HDKCDY";

// perform sha512 hash
        $hashValue = hash('sha512', ($ref . $secretKey));

// interswitch webservice url remember to add the saved transaction reference variable
        //$url = "https://stageserv.interswitchng.com/quicktellercheckout/api/v2/transaction.json?transRef=$ref";
		$url ="https://paywith.quickteller.com/api/v2/transaction.json?transRef=$ref";
// append the header putting the secret key and hash
        $headers = array(
            "GET /HTTP/1.1",
            "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1",
            "Content-type: text/xml;charset=\"utf-8\"",
            "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Language: en-us,en;q=0.5",
            "Accept-Encoding: gzip,deflate",
            "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7",
            "Keep-Alive: 300",
            "Connection: keep-alive",
            "clientid: $clientId",
            "Hash: $hashValue");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $data = curl_exec($ch);
        if (curl_errno($ch)) {
            print "Error: " . curl_error($ch);
        } else {
            // Show me the result
            $json = json_decode($data, TRUE);
            //var_dump($data);
            // print_r($json);
            curl_close($ch);
        }
        $responseCode = $json['ResponseCode'];
		//echo $responseCode;
        // echo "<br>Response Code:".$responseCode;
        $responseDescription = $json['ResponseDescription'];
        $amount = $json['Amount'] / 100;
        $paymentRef = $json['PaymentReference'];
        $transactionDate = $json['TransactionDate'];
        //$transID=$_SESSION['transID'];
        //echo "<br>TRANSID:".$transID;
        //update payment table


        if ($responseCode == '00') {
            $update = $this->site->updateTrans($transID, $responseCode, $responseDescription, $amount, $paymentRef, $transactionDate, $status = "PAID");
            //send Receipt as Mail and Print Receipt
            //$data['trans'] = $this->site->getApplication($transID);
            //$data['trans']=$this->site->getTransaction($transID);
            //$this->load->view('receipt', $data);
            $email=$this->site->getAny('conference',$transID,'confAuthNum','confEmail');
            $name=$this->site->getAny('conference',$transID,'confAuthNum','confName');
            $message='Dear '.$name.",<br> Your payment for NIQS Conference was successful.<br />Your Application No:<strong>".$transID."</strong><br />You can use ypur application no to print your Conference Badge.<br />Best regards.<br />Conference Committee ";
            //$this->sendEmail($email,$message);
            redirect('welcome/printReceipt/'.$transID,'refresh');
        } else {
            $update = $this->site->updateTrans($transID, $responseCode, $responseDescription, $amount, $paymentRef, $transactionDate, $status = "FAILED");
            //output response
            redirect('welcome/paymentFailed/'.$responseCode,'refresh');
            
            //$this->load->view('header');
            $this->load->view('output', $data);
        }
        //output receipt or response
    }
    public function paymentFailed($responseCode){
        $data['output'] = $this->outputResponse($responseCode);
        $this->load->view('paymentFailed',$data);
    }
    public function printReceipt($transRef){
		if(!$this->site->getTransaction($transRef)){
			echo "<pre><span>Invalid Transaction Id</span></pre>";
		}else{
        $data['trans']=$this->site->getTransaction($transRef);
		$this->load->view('receipt',$data);
		}
        
    }
    public function printReceipt2(){
        $transRef=$this->input->post('transactionID');
		if(!$this->site->getTransaction($transRef)){
			echo "<pre><span>Invalid Transaction Id</span></pre>";
		}else{
        $data['trans']=$this->site->getTransaction($transRef);
		$this->load->view('receipt',$data);
		}
        
    }
    
     public function outputResponse($response) {
        switch ($response) {
            case "X00":
                $output = "Account error, please contact your bank";
                break;
            case "X03":
                $output = "The amount requested is above the limit permitted by your bank, please contact your bank";
                break;
            case "X04":
                $output = "The amount requested is too low";
                break;
            case "X05":
                $output = "The amount requested is above the limit permitted by your bank, please contact your bank";
                break;
            case "14":
                $output = "The card number inputted is invalid, please re-try with a valid card number";
                break;
            case "38":
                $output = "Incorrect security details provided. Pin tries exceeded.";
                break;
            case "55":
                $output = "Incorrect security details provided.";
                break;
            case "56":
                $output = "Incorrect card details, please verify that the expiry date inputted is correct";
                break;
            case "57":
                $output = "Your bank has prevented your card from carrying out this transaction, please contact your bank";
                break;
            case "61":
                $output = "Your bank has prevented your card from carrying out this transaction, please contact your bank";
                break;
            case "75":
                $output = "Incorrect security details provided. Pin tries exceeded.";
                break;
            case "01":
                $output = "Refer to Financial Institution";
                break;
            case "02":
                $output = "Refer to Financial Institution, Special Condition";
                break;
            case "03":
                $output = "Invalid Merchant";
                break;
            case "04":
                $output = "Pick-up card";
                break;
            case "05":
                $output = "Do Not Honor";
                break;
            case "06":
                $output = "Error";
                break;
            case "07":
                $output = "Pick-Up Card, Special Condition";
                break;
            case "08":
                $output = "Honor with Identification";
                break;
            case "09":
                $output = "Request in Progress";
                break;
            case "10":
                $output = "Approved by Financial Institution, Partial";
                break;
            case "11":
                $output = "Approved by Financial Institution, VIP";
                break;
            case "12":
                $output = "Invalid Transaction";
                break;
            case "13":
                $output = "Invalid Amount";
                break;
            case "15":
                $output = "No Such Financial Institution";
                break;
            case "16":
                $output = "Approved by Financial Institution, Update Track 3";
                break;
            case "17":
                $output = "Customer Cancellation";
                break;
            case "18":
                $output = "Customer Dispute";
                break;
            case "19":
                $output = "Re-enter Transaction";
                break;
            case "20":
                $output = "Invalid Response from Financial Institution";
                break;
            case "21":
                $output = "No Action Taken by Financial Institution";
                break;
            case "22":
                $output = "Suspected Malfunction";
                break;
            case "23":
                $output = "Unacceptable Transaction Fee";
                break;
            case "24":
                $output = "File Update not Supported";
                break;
            case "26":
                $output = "Duplicate Record";
                break;
            case "27":
                $output = "File Update Field Edit Error";
                break;
            case "28":
                $output = "File Update File Locked";
                break;
            case "20053":
                $output = "Data Verification Failed";
                break;
            case "70035":
                $output = "You have not been set up to make this call";
                break;
            case "70038":
                $output = "Missing Header";
                break;
            default:
                $output = "Something Went Wrong,Transaction Failed";
                break;
        }
        return $output;
    }
   
   
    public function sendEmail($email,$message) {
        $this->load->library('email');
        $this->email->from('applications@niqs.org.ng', 'The Nigerian Institute of Quantity Surveyors');
        $this->email->to($email);
        $this->email->set_mailtype("html");
//$this->email->cc('another@another-example.com'); 
//$this->email->bcc('them@their-example.com'); 

        $this->email->subject('The Nigerian Institute of Quantity Surveyors Conference Registration');
        $this->email->message($message);
//mail()
        $this->email->send();
        //$this->email->print_debugger();
    }

    
    public function randomString($randStringLength) {
        $timestring = microtime();
        $secondsSinceEpoch = (integer) substr($timestring, strrpos($timestring, " "), 100);
        $microseconds = (double) $timestring;
        $seed = mt_rand(0, 1000000000) + 10000000 * $microseconds + $secondsSinceEpoch;
        mt_srand($seed);
        $randstring = "";
        for ($i = 0; $i < $randStringLength; $i++) {
            $randstring .= mt_rand(0, 9);
        }
        return($randstring);
    }
    
    public function getMemberDetails($niqsNo){
        $data['details']=$this->site->getMemberDetails($niqsNo);
        //$details=$this->site->getMemberDetails($niqsNo);
        //foreach($details as $row){}
        //return $row['memberName'];
        $this->load->view('output',$data);
    }
    public function exams(){
        $this->load->view('header');
        $data['examTypes']=$this->site->getAll('examtype');
        $this->load->view('exam',$data);
        $this->load->view('footer');
    }

    public function page($id) {
        $data['news'] = $this->site->getNews();
        $data['content'] = $this->site->getContent($id);
        $data['membership'] = $this->site->getContent(44);
        $data['events'] = $this->site->getEvents();
        $this->load->view('header');
        $this->load->view('body2', $data);
        $this->load->view('footer');
    }
public function finStand(){
    $this->load->model('site');
    $data['stand']=$this->site->Standing();
    $this->load->view('header');
    $this->load->view('stand',$data);
    $this->load->view('footer');
}

    public function news($id) {
        $data['news'] = $this->site->getNews();
        $data['content'] = $this->site->newsDetails($id);
        $data['membership'] = $this->site->getContent(44);
        $data['events'] = $this->site->getEvents();
        $this->load->view('header');
        $this->load->view('news', $data);
        $this->load->view('footer');
    }

    public function events($id) {
        $data['news'] = $this->site->getNews();
        $data['content'] = $this->site->eventDetails($id);
        $data['membership'] = $this->site->getContent(44);
        $data['events'] = $this->site->getEvents();
        $this->load->view('header');
        $this->load->view('events', $data);
        $this->load->view('footer');
    }

    public function members() {
        $this->load->library('pagination');
        $config['base_url'] = site_url('welcome/members');
        $config['total_rows'] = $this->site->countMembers();
        $config['per_page'] = 30;
        $config["uri_segment"] = 3;
        
        $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        $data['sno'] = $page;
        $this->pagination->initialize($config);
        $data['pages']=$this->pagination->create_links();
        $data['news'] = $this->site->getNews();
        $data['membership'] = $this->site->getContent(44);
        $data['members'] = $this->site->members($config['per_page'],$page);
        $data['events'] = $this->site->getEvents();
        $this->load->view('header');
        $this->load->view('members', $data);
        $this->load->view('footer');
    }

    public function contact() {
        $data['news'] = $this->site->getNews();
        $data['membership'] = $this->site->getContent(44);
        $data['content'] = $this->site->getContent(45);
        $data['events'] = $this->site->getEvents();
        $this->load->view('header');
        $this->load->view('contact', $data);
        $this->load->view('footer');
    }

}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */