<?php

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

class Home extends CI_Controller {

    public function __construct() {
        parent::__construct();
        ob_start();
        session_start();
        $this->load->model('site');
    }

    public function index() {
        $this->load->model('site');
        $this->load->view('header');
        $this->load->view('body');
        $this->load->view('footer');
    }

    public function login() {
        $surname = $this->input->post('surname');
        $regNo = $this->input->post('regNo');
        $check = $this->site->checkLogin($surname, $regNo);
        if ($check) {
            //retrieve all profile
            $profile = $this->site->profile($surname, $regNo);
            foreach ($profile as $row) {
                $_SESSION['memberNo'] = $row['memberNo'];
                $_SESSION['memberID'] = $row['memberID'];
            }
            redirect('home/home2', 'refresh');
        } else {
            $data['msg'] = 'Invalid Surname or Reg No';
            $this->load->view('header');
            $this->load->view('body', $data);
            $this->load->view('footer');
        }
    }

    public function home2() {
        $memberID = $_SESSION['memberID'];
        $memberNo = $_SESSION['memberNo'];
        $data['profile'] = $this->site->fullProfile($memberID);
        $data['payitem'] = $this->site->loadPayItem();
        $data['financial'] = $this->site->financial($memberNo);
        $profile=$this->site->fullProfile($memberID);
        foreach($profile as $row){
            $checkEmail=$row['memberEmail'];
            $checkPhone=$row['memberPhone'];
            $checkAddress=$row['memberAddress'];
            $checkChapter=$row['memberState'];
            $checkNationality=$row['memberNationality'];
        }
       
        $this->load->view('header2');
        if(empty($checkEmail) || empty($checkPhone) ||empty($checkAddress) || empty($checkChapter) || empty($checkNationality) ){
         redirect('home/profile','refresh');
        }else{
        $this->load->view('home', $data);
        }
        $this->load->view('footer');
    }
    
    public function profile($msg=NULL){
        if(!empty($msg)){
            $data['msg']='Profile update success';
        }
        $memberID = $_SESSION['memberID'];
        $memberNo = $_SESSION['memberNo'];
        $data['profile'] = $this->site->fullProfile($memberID);
        $data['chapter']=$this->site->getAll('state');
        $data['nationality']=$this->site->getAll('countries');
        $this->load->view('header2');
         $this->load->view('updateProfile',$data);
         $this->load->view('footer');
    }
    
    public function updateProfile2(){
        $id=$this->input->post('id');
        $address=$this->input->post('address');
        $email=$this->input->post('email');
        $phone=$this->input->post('phone');
        $dob=$this->input->post('dob');
        $othernames=$this->input->post('othernames');
        $surname=$this->input->post('surname');
        $title=$this->input->post('title');
        $nat=$this->input->post('nat');
        $chapter=$this->input->post('chapter');
        $update=$this->site->updateProfile($id,$address,$email,$phone,$dob,$othernames,$surname,$title,$nat,$chapter);
        if($update){
            redirect('home/profile/1','refresh');
        }
    }

    public function payDues() {
        $memberID = $_SESSION['memberID'];
        $memberNo = $_SESSION['memberNo'];
        $data['profile'] = $this->site->fullProfile($memberID);
        $data['financial'] = $this->site->financial($memberNo);
        $this->load->view('header2');
        $this->load->view('paydues', $data);
        $this->load->view('footer');
    }

    public function payDues2() {
        $memberID = $_SESSION['memberID'];
        $memberNo = $_SESSION['memberNo'];
        $it = array_values($this->input->post('items'));
        $transNo = $this->randomString(11);
        $date = date('Y-m-d');
        //deletes previous items in temptrans
        $this->site->deleteTempTrans($memberNo);
        if (empty($it)) {
            echo "An item must be selected";
            redirect('home/payDues', 'refresh');
            //exit();
        } else {
            foreach ($it as $item) {
                $itemName = $this->site->getItemName($item);
                $itemAmount = $this->site->itemAmount($memberNo, $itemName);
                $insert = $this->site->insertItem($memberNo, $item, $itemAmount, $itemName, $date);
                //insert into dues transaction
                
            }
            $insert2=$this->site->insertDuesTransaction($transNo,$itemAmount,$date,$status='Pending',$memberID);
            if ($insert && $insert2) {
                redirect('home/payduesQuick/'.$transNo, 'refresh');
            }
        }

        /* $idd=$_SESSION['idd'];
          $nseregno=$_SESSION['nseregno'];
          $data['profile']=$this->site->fullProfile($idd);
          $data['financial']=$this->site->financial($nseregno);
          $this->load->view('header2');
          $this->load->view('paydues2',$data);
          $this->load->view('footer'); */
    }

    public function payduesQuick($transNo) {
        $memberID = $_SESSION['memberID'];
        $memberNo = $_SESSION['memberNo'];
        $data['profile'] = $this->site->fullProfile($memberID);
        $data['financial'] = $this->site->getTrans($memberID,$transNo);
        $this->load->view('header2');
        $this->load->view('paydues2', $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 = "portal.niqs.org.ng";
        //$secretKey = "E9300DJLXKJLQJ2993N1190023";
        $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 "<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);
            $memberID=$this->site->getAny('duestransaction',$transID,'transRef','transAppID');
            $email=$this->site->getAny('members',$memberID,'memberID','memberEmail');
            $surname=$this->site->getAny('members',$memberID,'memberID','memberSurname');
            $othernames=$this->site->getAny('members',$memberID,'memberID','memberOthernames');
            $memberNo=$this->site->getAny('members',$memberID,'memberID','memberNo');
            $message='Dear '.$surname." ".$othernames.",<br> Your payment for Membership Dues was successful.<br />Your Transaction Reference No:<strong>".$transID."</strong><br /><br />Best regards.<br />Membership Officer ";
            //$this->sendEmail($email,$message);
            //update dues table
            $oldAmount=$this->site->getAny('dues',$memberNo,'memberNo','outstanding');
            $newAmount=$oldAmount-$amount;
            $update=$this->site->updateDues($newAmount,$memberNo);
            redirect('home/printReceipt/'.$transID,'refresh');
        } else {
            $update = $this->site->updateTrans($transID, $responseCode, $responseDescription, $amount, $paymentRef, $transactionDate, $status = "FAILED");
            //output response
            redirect('home/paymentFailed/'.$responseCode,'refresh');
            
            //$this->load->view('header');
            $this->load->view('output', $data);
        }
        //output receipt or response
    }
    public function sendEmail($email,$message) {
        $this->load->library('email');
        $this->email->from('info@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 Probationer Membership Application');
        $this->email->message($message);
//mail()
        $this->email->send();
        //$this->email->print_debugger();
    }
    public function printReceipt($transRef){
        $data['trans']=$this->site->getTransaction($transRef);
        $this->load->view('receipt',$data);
    }
    public function paymentFailed($responseCode){
        $data['output'] = $this->outputResponse($responseCode);
        $this->load->view('paymentFailed',$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 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 contact(){
        
        $this->load->view('header');
        
        $this->load->view('contact');
        $this->load->view('footer');
    }
    public function transactions(){
        $memberID=$_SESSION['memberID'];
        $data['transactions']=$this->site->retrieveTransaction($memberID);
        $this->load->view('header2');
        $this->load->view('transaction',$data);
        $this->load->view('footer');
    }
    public function contact2(){
        
        $this->load->view('header2');
        
        $this->load->view('contact2');
        $this->load->view('footer');
    }
    public function guide(){
        $this->load->view('header');
        $this->load->view('payguide');
        $this->load->view('footer');
    }
    public function payGuide(){
        $this->load->view('header2');
        $this->load->view('payguide2');
        $this->load->view('footer');
    }

    public function quickteller() {
        $this->load->library('soap_client_view');
        $email = $this->site->getAny("nsemem", $_SESSION['idd'], "idd", "email");
        $phone = $this->site->getAny("nsemem", $_SESSION['idd'], "idd", "mobilephone");
        $lastname = $this->site->getAny("nsemem", $_SESSION['idd'], "idd", "lastname");
        $middlename = $this->site->getAny("nsemem", $_SESSION['idd'], "idd", "middlename");
        $firstname = $this->site->getAny("nsemem", $_SESSION['idd'], "idd", "firstname");

        if (empty($middlename)) {
            $middlename = 'NA';
        }
        if (empty($firstname)) {
            $firstname = 'NA';
        }
        $regNo = $this->site->getAny("nsemem", $_SESSION['idd'], "idd", "nseregno");
        if (empty($email)) {
            $myemail = 'info@nse.org.ng';
        } else {
            $myemail = $email;
        }

        $transID = '3061' . $this->randomString(11);
        $param['applicant_id'] = $_SESSION['nseregno'];
        $param['email'] = $myemail;
        $param['trans_no'] = $transID;
        $param['trans_name'] = "Payment of Dues";
        $param['trans_amount'] = $this->input->post('amount');
        $amount = $this->input->post('amount');


        $transCharge = 300.00;

        $portalFee = 200.00;
        $bankShare = 100.00;
        $schoolShare = $amount - $portalFee - $bankShare;
        $totalAmount = $portalFee + $bankShare + $schoolShare;
        //$names=explode(" ",$this->input->post('name'));
        $surname = $this->site->getAny("nsemem", $_SESSION['idd'], "idd", "lastname");
        $email = $myemail;
        $phone = $phone;
        $applicantID = $_SESSION['idd'];

        $soapParam = array(
            'portalFee' => $portalFee,
            'bankShare' => $bankShare,
            'schoolShare' => $schoolShare,
            'transCharge' => ($portalFee + $bankShare),
            'surname' => $surname,
            'firstname' => $firstname,
            'othernames' => $middlename,
            'email' => $email,
            'phone' => $phone,
            'totalAmount' => $totalAmount,
            'applicantID' => $applicantID,
            'transactionID' => $transID,
            'transYear' => date('Y'),
            'itemCode' => 'NSE01',
            'description' => 'Payment of Dues',
            'installmentID' => 2
        );

        $response = $this->soap_client_view->logTransaction($soapParam);
        // print_r($response);
        if (!isset($response)) {
            throw new Exception("Web Service Error");
        }
        if ($response['responseCode'] == "00") {
            $date = date('Y-m-d');
            $insert = $this->site->insertTrans($_SESSION['nseregno'], $transID, $date, $schoolShare, 'NOT PAID', '2014', 'Paychoice');

            if ($insert) {
                //select from temptrans table
                $tranx = $this->site->getTempTrans2($_SESSION['nseregno'], $date);
                foreach ($tranx as $t) {
                    //updates individual item   
                    $name = $t['name'];
                    $itemAmount = $this->site->amountItem($name, $_SESSION['nseregno']);
                    $updateTrans = $this->site->updateTrans($name, $_SESSION['nseregno'], $transID, $itemAmount);
                }
                //delete from temptrans
                $this->site->deleteTempTrans($_SESSION['nseregno']);
                redirect('home/payslip/' . $transID, 'refresh');
            }
        }
    }

    public function ups() {
        $date = date('Y-m-d');
        $transID = "1403" . $this->randomString(11);
        $schoolShare = $this->input->post('amount');
        $insert = $this->site->insertTrans($_SESSION['nseregno'], $transID, $date, $schoolShare, 'NOT PAID', '2014', 'UPS');

        if ($insert) {
            //select from temptrans table
            $tranx = $this->site->getTempTrans2($_SESSION['nseregno'], $date);
            foreach ($tranx as $t) {
                //updates individual item   
                $name = $t['name'];
                $itemAmount = $this->site->amountItem($name, $_SESSION['nseregno']);
                $updateTrans = $this->site->updateTrans($name, $_SESSION['nseregno'], $transID, $itemAmount);
            }
            $this->site->deleteTempTrans($_SESSION['nseregno']);
            redirect('home/ups2/'.$transID,'refresh');
        }
        
    }
    public function ups2($transID){
        $idd = $_SESSION['idd'];
        $data['profile'] = $this->site->fullProfile($idd);
        $data['transID'] = $transID;
        $data['details']=$this->site->retrieveTransDetails($transID);
        $this->load->view('header2');
        $this->load->view('ups', $data);
        $this->load->view('footer');
    }

    public function payslip($transID) {
        $idd = $_SESSION['idd'];
        $nseregno = $_SESSION['nseregno'];
        $data['profile'] = $this->site->fullProfile($idd);

        $data['transID'] = $transID;

        $data['details'] = $this->site->retrieveTransDetails($transID);
        $this->load->view('header2');
        $this->load->view('payslip', $data);
        $this->load->view('footer');
    }

    public function logout() {
        session_destroy();
        echo "You are now been logged out, redirecting to login";
        redirect('home/index', 'refresh');
    }

    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');
        $this->load->library('pagination');
        $config['base_url'] = site_url('home/finStand');
        $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['stand'] = $this->site->standing($config['per_page'], $page);
        //$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 searchFin($surname) {
        $data['stand'] = $this->site->searchFin($surname);
        $this->load->view('searchFin', $data);
    }

    public function searchFin2($regNo) {
        $data['stand'] = $this->site->searchFin2($regNo);
        $this->load->view('searchFin', $data);
    }

    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');
    }

    
}

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