<?php

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

class Admin extends CI_Controller {

    public function __construct() {
        error_reporting(E_ALL ^ (E_NOTICE | E_WARNING));
        ini_set('display_errors', 1);
        ini_set('memory_limit', '-1');
        $ci = &get_instance();
        //$this->load->library('excel');
        parent::__construct();
        $this->load->model('admin_m');
        $this->load->model('site');
        $this->load->library('form_validation');
        session_start();
    }

function cleanData(&$str)
  {
   // escape tab characters
    $str = preg_replace("/\t/", "\\t", $str);

    // escape new lines
    $str = preg_replace("/\r?\n/", "\\n", $str);

    // convert 't' and 'f' to boolean values
    if($str == 't') $str = 'TRUE';
    if($str == 'f') $str = 'FALSE';

    // force certain number/date formats to be imported as strings
    if(preg_match("/^0/", $str) || preg_match("/^\+?\d{8,}$/", $str) || preg_match("/^\d{4}.\d{1,2}.\d{1,2}/", $str)) {
      $str = "'$str";
    }

    // escape fields that include double quotes
    if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
  }

function export_excel(){
  // filename for download
  $filename = "NIQS Cert" . date('Ymdhis') . ".xls";

  header("Content-Disposition: attachment; filename=\"$filename\"");
  header("Content-Type: application/vnd.ms-excel");

  $flag = false;
echo '<table cellpadding="1" border="1"><tr><th>Name</th><th>Category</th><th>Receipt. No.</th><th>Participation Mode</th><th>Email</th><th>Phone</th> <th>Amount</th><th>Bank</th><th>Date</th></tr>';

$rows = $this->admin_m->exportExcel();
  foreach($rows as $row) {
        echo "<tr><td>".$row['confName']."</td><td>".$row['cat_name']."</td><td>".$row['confAuthNum']."</td><td>".$row['confLocation']."</td><td>".$row['confEmail']."</td><td>".$row['confPhone']."</td><td>". number_format($row['transAmount'],2)."</td><td>".$row['bank']."</td><td>".$row['confRegDate']."</td></tr>";          

 } 
             
echo '</table> ';

/*
$rows = $this->admin_m->exportExcel();
  foreach($rows as $row) {
    if(!$flag) {
      // display field/column names as first row
      echo implode("\t", array_keys($row)) . "\r\n";
      $flag = true;
    }
    array_walk($row, __NAMESPACE__ . '\cleanData');
    echo implode("\t", array_values($row)) . "\r\n";
  }
  */

}
    public function index() {
       $this->login2();
    }

   
    //fellowship by application
    public function application() {
        $data['countries'] = $this->admin_m->getAll("nationality");
        $data['identity'] = $this->admin_m->getAll("identity");
        $data['employment'] = $this->admin_m->getAll("employmenttype");
        $data['categories'] = $this->admin_m->getAll("categories");
        $data['contributionFees'] = $this->admin_m->getAll("contributionFees");
        $this->load->view('admin/header');
        $this->load->view('admin/application', $data);
        $this->load->view('admin/footer');
    }

//get fee amount
    public function getAmount($fee_id) {
        $data['email'] = $this->admin_m->getAny("contributionFees", $fee_id, "id", "amount");
        $this->load->view('admin/emailCheck', $data);
    }

    public function payContribution() {
        $data['contribution'] = $this->admin_m->getAll("contributionFees");
        $data['fee'] = $this->input->post('fee');
        $data['amount'] = $this->input->post('amount');
        $this->load->view('admin/headerProfile');
        $this->load->view('admin/leftNav');
        $this->load->view('admin/contributionsConfirm', $data);
        $this->load->view('admin/footer');
    }

    public function insertContribution() {
        $profileID = $_SESSION['id'];
        $transName = $this->input->post('transName');
        $transNo = "3061" . $this->randomString(8);
        $transAmount = $this->input->post('amount');
        $transStatus = 'Pending';
        $transDate = date('Y-m-d');
        $transYear = date('Y');
        $paymentMode = 'Online';
        $feeItemId = $this->input->post('fee');
        $insert = $this->admin_m->insertTransact($profileID, $transName, $transNo, $transAmount, $transStatus, $transDate, $transYear, $paymentMode, $feeItemId);
        if ($insert) {

            redirect('admin/paychoice/' . $insert, 'refresh');
        }
    }

    public function paychoice($transId) {
        $data['profile'] = $this->admin_m->getMany('members', $_SESSION['id'], 'profileID');
        $data['trans'] = $this->admin_m->getMany('transaction', $transId, 'transID');
        $this->load->view('admin/headerProfile');
        $this->load->view('admin/leftNav');
        $this->load->view('admin/paychoice', $data);
        $this->load->view('admin/footer');
    }

    public function contributionReport() {
        $data['contribution'] = $this->admin_m->getAllContribution($_SESSION['id']);
        $this->load->view('admin/headerProfile');
        $this->load->view('admin/leftNav');
        $this->load->view('admin/contributionReport', $data);
        $this->load->view('admin/footer');
    }

    public function updateProfile() {
        $title = $this->input->post('title');
        $surname = $this->input->post('surname');
        $othernames = $this->input->post('othernames');
        $password = $this->input->post('password');
        //$string = "NIP";
        //$authNum = str_shuffle($string) . $this->randomString(8);
        $update = $this->admin_m->update($_SESSION['id'], $title, $surname, $othernames, $password);
        //$update2 = $this->admin_m->updateEmployment($_SESSION['id'], $employment, $employer, $employerPhone, $employerAddress, $employerEmail);
        if ($update) {
            redirect('admin/profile/1', 'refresh');
        }
    }

    public function changePassport() {
        $this->load->view('admin/header');
        $this->load->view('admin/changePassport');
    }

    public function uploadPassport() {
        $id = $_SESSION['id'];
        $name = $this->randomString(8);
        $data['passport'] = $name;
        //$this->uploadsApply($this->input->post('passport'),$name);      
        $config['upload_path'] = 'application/views/uploads/';
        $config['file_name'] = $name . ".jpg";
        $config['allowed_types'] = 'jpg';
        $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());
        } else { //else, set the success message
            //update database
            $update = $this->admin_m->updatePassport($id, $name);
            if ($update) {
                $this->load->view('admin/header');
                $this->load->view('admin/success233');
            }
            //$data = array('msg' => "Upload success!");
            //$data['upload_data'] = $this->upload->data();
        }
    }

    public function success() {
        $this->load->view('admin/header');
        $this->load->view('admin/success');
    }

    public function success23() {
        //$this->load->view('admin/headerProfile');
        $this->load->view('admin/success23');
    }

    public function dues() {
        $data['dues'] = $this->admin_m->dues($_SESSION['regNo']);
        $this->load->view('admin/headerProfile');
        $this->load->view('admin/leftNav');
        $this->load->view('admin/dues', $data);
    }

    public function paydues() {
        $data['amount'] = $this->input->post('amount');
        $this->load->view('admin/headerProfile');
        $this->load->view('admin/leftNav');
        $this->load->view('admin/paydues', $data);
    }

    public function payonquickteller() {
        $this->load->library('soap_client_view');
        $email = $this->admin_m->getAny("members", $_SESSION['id'], "id", "email");
        $phone = $this->admin_m->getAny("members", $_SESSION['id'], "id", "mobilephone");
        $regNo = $this->admin_m->getAny("members", $_SESSION['id'], "id", "reg_no");
        if (empty($email)) {
            $myemail = 'info@nistructe.org.ng';
        } else {
            $myemail = $email;
        }
        if (empty($phonr)) {
            $myphone = '08032518766';
        } else {
            $myphone = $phone;
        }
        $others = $this->admin_m->getAny("members", $_SESSION['id'], "id", "othernames");
        $oth = explode(" ", $others);
        $firstname = $oth[0];
        if (empty($firstname)) {
            $firstname = "NA";
        } else {
            $firstname = $firstname;
        }
        $othernames = $oth[1];
        if (empty($othernames)) {
            $othernames = "NA";
        } else {
            $othernames = $othernames;
        }
        $this->load->library('soap_client_view');
        $transID = '3061' . $this->randNum(11);
        $param['applicant_id'] = $_SESSION['id'];
        $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');
        //$totalAmount = $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->admin_m->getAny("members", $_SESSION['id'], "id", "surname");
        // $firstname = $this->admin_m->getAny("members", $_SESSION['id'], "id", "firstname");
        //$othernames = $this->input->post('othernames');
        // $matric = $this->input->post('matric');
        //$docTypeName=$this->input->post('docTypeName');
        //$docType = '1';
        //$surname = $this->input->post('surname');;
        //$firstname = $this->input->post('firstname');;
        //$othername = $this->input->post('othernames');;
        $email = $myemail;
        $phone = $myphone;
        $applicantID = $_SESSION['id'];

        $soapParam = array(
            'portalFee' => $portalFee,
            'bankShare' => $bankShare,
            'schoolShare' => $schoolShare,
            'transCharge' => ($portalFee + $bankShare),
            'surname' => $surname,
            'firstname' => $firstname,
            'othernames' => $othernames,
            'email' => $email,
            'phone' => $phone,
            'totalAmount' => $totalAmount,
            'applicantID' => $applicantID,
            'transactionID' => $transID,
            'transYear' => date('Y'),
            'itemCode' => 'NISE01',
            '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") {
            //log transaction locally
            $data['surname'] = $surname;
            $data['firstname'] = $firstname;
            $data['othernames'] = $othernames;
            $data['amount'] = $amount;
            $data['trans_no'] = $transID;

            $reference_id = md5($response['referenceID']);
            date_default_timezone_set('UTC');
            $date = date('Y-m-d');
            $inst = $this->admin_m->insertTrans22($regNo, $date, $transID, 'Pending', $amount, $reference_id);
            //if($inst){
            //redirect("admin/displayResult/".$transID."/".$regNo,"Refresh");
            //}
            $data['transID'] = $transID;
            $this->load->view('admin/headerProfile');
            $this->load->view('admin/leftNav');
            $this->load->view('admin/dispResult', $data);
            //echo "Transaction Successsfully Logged";
            //$this->insertTrxn2($applicantID, $surname, $firstname, $othernames, $email, $totalAmount, $transID, $reference_id, $date, $matric, $docType);
            //$this->ApplicantModel->logTransaction($applicantID,$surname,$firstname,$othernames,$email,$totalAmount,$transID,$reference_id,$date);
        } else {
            echo "Payment Error";
        }
    }

    public function displayResult($transID, $regNo) {
        $data['transID'] = $transID;
        $data['regNo'] = $regNo;
        $this->load->view('admin/displayResult', $data);
    }

    //displays payment page
    public function fees() {
        $type = 1;
        $grade = $_SESSION['grade'];
        $data['surname'] = $_SESSION['surname'];
        $data['othernames'] = $_SESSION['othernames'];
        $data['email'] = $_SESSION['email'];
        $data['phone'] = $_SESSION['phone'];
        $data['trxn'] = $_SESSION['trnxId'];
        $date = date('Y-m-d');
        if ($date <= '2014-10-10') {
            $data['fees'] = $this->admin_m->fees(1);
        } else {
            $data['fees'] = $this->admin_m->fees(2);
        }
        $this->load->view('admin/header');
        $this->load->view('admin/fees', $data);
        $this->load->view('admin/footer');
    }

    public function register() {
        $this->load->view('admin/headerReg');
        $this->load->view('admin/register');
        $this->load->view('admin/footer');
    }

    public function checkEmail($email) {
        $data['email'] = $this->admin_m->checkEmail($email);
        $this->load->view('admin/emailCheck', $data);
    }

    public function enrollmentProcedure() {
        $this->load->view('admin/procedures');
    }

    public function checkReport() {
        $data['transaction'] = $this->admin_m->report($_SESSION['id']);
        // $this->load->view('admin/header2');
        $this->load->view('admin/checkReport', $data);
        //$this->load->view('admin/footer');
    }

    public function report() {
        $data['transaction'] = $this->admin_m->report($_SESSION['id']);
        $this->load->view('admin/header2');
        $this->load->view('admin/report', $data);
        $this->load->view('admin/footer');
    }

    public function searchReport() {
        $from = $this->input->post('from');
        $to = $this->input->post('to');
        $data['transaction'] = $this->admin_m->reportSearch($_SESSION['id'], $from, $to);
        $this->load->view('admin/header2');
        $this->load->view('admin/report', $data);
        $this->load->view('admin/footer');
    }

    public function randNum($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);
    }

    //generates random numbers for captcha
    public function randomNum() {
        $_SESSION['rand'] = '';
        $num = rand(1000000, 9000000);
        $_SESSION['rand'] = $num;
        $data['num'] = $num;
        $this->load->view('admin/random', $data);
    }

    public function confirmReg() {
        $this->load->library('form_validation');
        $compName = $this->input->post('comp-name');
        $compAddress = $this->input->post('comp-address');
        $compEmail = $this->input->post('comp-email');
        $compPhone = $this->input->post('comp-phone');
        $contact = $this->input->post('contact');
        $compPassword = $this->input->post('comp-password');
        $confPassword = $this->input->post('conf-password');
        $captcha = $this->input->post('captcha');
        $confCaptcha = $this->input->post('conf-captcha');

        $this->form_validation->set_rules('comp-name', 'Enter Company Name', 'required');
        $this->form_validation->set_rules('comp-address', 'Enter Company Address', 'required');
        $this->form_validation->set_rules('comp-email', 'Email Address', 'required|valid_email');
        $this->form_validation->set_rules('comp-phone', 'Company Phone', 'required|numeric');
        $this->form_validation->set_rules('contact', 'Contact Person', 'required');
        $this->form_validation->set_rules('comp-password', 'Password', 'required|matches[conf-password]');
        $this->form_validation->set_rules('captcha', 'Captcha', 'required|matches[confirm-captcha]');

        if ($this->form_validation->run() == FALSE) {
            $this->register();
        } else {
            $data['compName'] = $compName;
            $data['compAddress'] = $compAddress;
            $data['compEmail'] = $compEmail;
            $data['compPhone'] = $compPhone;
            $data['contact'] = $contact;
            $data['password'] = $compPassword;
            $this->load->view('admin/header');
            $this->load->view('admin/confirmDetails', $data);
            $this->load->view('admin/footer');
        }
    }

    public function insertRegDetails() {
        $compName = $this->input->post('comp-name');
        $compAddress = $this->input->post('comp-address');
        $compEmail = $this->input->post('comp-email');
        $compPhone = $this->input->post('comp-phone');
        $contact = $this->input->post('contact');
        $date = date('Y-m-d');
        $compPassword = md5($this->input->post('comp-password'));
        $insert = $this->admin_m->createProfile($compName, $compAddress, $compEmail, $compPhone, $contact, $compPassword, $date);
        if ($insert) {
            //send mail with details
            $data['type'] = '1';
            $data['msg'] = 'Profile Created Successfully,login to continue';
            $data['url'] = 'index';
            $this->load->view('admin/header');
            $this->load->view('admin/result', $data);
            $this->load->view('admin/footer');
        } else {
            $data['type'] = '0';
            $data['msg'] = 'Error creating profile';
            $data['url'] = 'index';
            $this->load->view('admin/header');
            $this->load->view('admin/result', $data);
            $this->load->view('admin/footer');
        }
    }

    //updates profile
    public function updateRegDetails() {
        $compName = $this->input->post('comp-name');
        $compAddress = $this->input->post('comp-address');
        $compEmail = $this->input->post('comp-email');
        $compPhone = $this->input->post('comp-phone');
        $contact = $this->input->post('contact');
        $date = date('Y-m-d');
        $compId = $_SESSION['id'];
        $compPassword = md5($this->input->post('comp-password'));
        $update = $this->admin_m->updateProfile($compName, $compAddress, $compEmail, $compPhone, $contact, $compPassword, $compId);
        if ($update) {
            //send mail with details
            $data['type'] = '1';
            $data['msg'] = 'Profile Successfully Updated';
            $data['url'] = 'profile';
            $this->load->view('admin/result', $data);
        } else {
            $data['type'] = '0';
            $data['msg'] = 'Error updating profile';
            $data['url'] = 'profile';
            $this->load->view('admin/result', $data);
        }
    }

    //displays checkout
    public function checkOut() {
        if (!empty($_SESSION['transid'])) {
            $transId = $_SESSION['transid'];
        } else {
            $transid = '0000';
        }
        if (!empty($_SESSION['id'])) {
            $compId = $_SESSION['id'];
        } else {
            $compId = 'o90bw2';
        }
        /* $this->load->library('pagination');
          $config['base_url'] = admin_url('home/checkOut');
          $config['total_rows'] = $this->admin_m->checkoutCount($transId,$compId);
          $config['per_page'] = 15;
          $config["uri_segment"] = 3;
          $data['sno']=$config['per_page'];
          $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0; */

        //$data['chart']=$this->home_model->dispChart($config['per_page'],$page);
        //$this->pagination->initialize($config);
        //$data['pages']=$this->pagination->create_linkss
        $data['amount'] = $this->admin_m->dispTotalAmount($transId, $compId);
        $this->load->view('admin/header2');
        $this->load->view('admin/checkout', $data);
        $this->load->view('admin/footer');
    }

    public function emptyCart() {
        $transId = $_SESSION['transid'];
        $empty = $this->admin_m->emptyCart($transId);
        if ($empty) {
            $_SESSION['transid'] = '';
            $data['type'] = 1;
            $data['msg'] = 'Cart Successfully emptied';
            $data['url'] = 'transaction';
            $this->load->view('admin/result', $data);
        }
    }

    //process checkout
    public function processCheckout() {
        if (!empty($_SESSION['transid'])) {
            $transId = $_SESSION['transid'];
            //retrieve transaction details
            $details = $this->admin_m->retrieveTransDetails($transId);
            $amount = 0;
            $check = $this->admin_m->checkTransaction($transId);
            $myAmount = $this->admin_m->checkAmount($transId);
            if (!$check) {
                foreach ($details as $row) {
                    $nseregno = $row['nseregno'];
                    $date = date('Y-m-d');
                    $total = $row['amount'];
                    $status = 'NOT PAID';
                    $item_id = $row['item_id'];
                    //$year=$this->admin_m->getCurrentYear();
                    $year = 2014;
                    //inserts into transaction table
                    //this checks if there the transaction has been captured before       
                    $insert = $this->admin_m->insertTransaction($nseregno, $date, $total, $status, $transId, $year);
                    $amount+=$row['amount'];
                }



                if ($insert) {
                    //retrieve trans_details again
                    $date = date('Y-m-d');
                    $transDetails = $this->admin_m->retrieveTransDetailsAgain($transId, $date);
                    foreach ($transDetails as $row) {
                        $nseregno = $row['nseregno'];
                        $item_id = $row['item_id'];
                        $name = $this->admin_m->itemNames($item_id);
                        $amount = $row['amount'];

                        $this->admin_m->updateTransDetails($name, $amount, $nseregno, $transId);
                        //retrieves the item name
                    }
                }

                // $data['profile']=$this->admin_m->profile($_SESSION['id']);
                $names = $this->admin_m->getAny('company', $_SESSION['id'], "id", "mycomp_name");
                $n = explode(" ", $names);
                $data['surname'] = $n[0];
                $data['firstname'] = $n[1];
                $data['othernames'] = $n[2];
                $data['member_email'] = $this->admin_m->getAny('company', $_SESSION['id'], "id", "mycomp_email");
                $data['phone'] = $this->admin_m->getAny('company', $_SESSION['id'], "id", "mycomp_phone");
                $data['valid_user'] = $_SESSION['id'];
                $data['amount'] = $myAmount;
                $data['trxn'] = $transId;
                $this->load->view('admin/header2');
                $this->load->view('admin/chooseMode', $data);
                $this->load->view('admin/footer');
            } else {
                $names = $this->admin_m->getAny('company', $_SESSION['id'], "id", "mycomp_name");
                $n = explode(" ", $names);
                $data['surname'] = $n[0];
                $data['firstname'] = $n[1];
                $data['othernames'] = $n[2];
                $data['member_email'] = $this->admin_m->getAny('company', $_SESSION['id'], "id", "mycomp_email");
                $data['phone'] = $this->admin_m->getAny('company', $_SESSION['id'], "id", "mycomp_phone");
                $data['valid_user'] = $_SESSION['id'];
                $data['amount'] = $myAmount;
                $data['trxn'] = $transId;
                $data['surname'] = $this->admin_m->getName($_SESSION['id']);
                $this->load->view('admin/header2');
                $this->load->view('admin/chooseMode', $data);
                $this->load->view('admin/footer');
            }
        } else {
            echo "Session Time out, please login to continue";
            redirect('admin/index', 'refresh');
        }
    }

    //Recovers password
    public function recoverPassword() {
        $email = $this->input->post('forg-email');
        $check = $this->admin_m->checkEmail($email);
        $password = rand(10000, 900000);
        if ($check) {
            //resets password
            $update = $this->admin_m->resetPassword($email, md5($password));
            // send new password
            $data['type'] = '1';
            $data['msg'] = 'Password has been reset and sent to your email';
            $data['url'] = 'index';
            $this->load->view('admin/header');
            $this->load->view('admin/result', $data);
            $this->load->view('admin/footer');
        } else {
            $data['msg'] = 'Invalid Password Recovery Email';
            $data['url'] = 'index';
            $this->load->view('admin/header');
            $this->load->view('admin/body', $data);
            $this->load->view('admin/footer');
        }
    }

    public function login() {
        $username = $this->input->post('username');
        $password = $this->input->post('password');
        //echo $coopNo;
        //$pass=md5($password);
        $check = $this->admin_m->authenticate($username, $password);
        $confirm = $this->admin_m->checkMyLogin($username, $password);

        if ($confirm >= 1) {
            foreach ($check as $row) {
                $_SESSION['id'] = $row['id'];
                $_SESSION['surname'] = $row['surname'];
                $_SESSION['othernames'] = $row['othernames'];
                $_SESSION['username'] = $row['username'];
                $_SESSION['email'] = $row['email'];
                $_SESSION['roles_id'] = $row['roles_id'];
            }
            redirect('admin/home', 'refresh');
        } else {
            $data['msg'] = 'Wrong Username or Password';
            $data['url'] = 'index';
            //$this->load->view('admin/header');
            $this->load->view('admin/loginFail', $data);
            $this->load->view('admin/footer');
        }
    }

    public function login2() {
        $this->load->view('admin/loginFail', $data);
        $this->load->view('admin/footer');
    }

    //apply for mortgage
    public function applyMortgage() {
        $data['profile'] = $this->admin_m->getMany('members', $_SESSION['id'], 'profileID');
        $coopNo = $this->admin_m->getAny('members', $_SESSION['id'], 'profileID', 'coopNo');
        $category = $this->admin_m->getAny('members', $_SESSION['id'], 'profileID', 'category');
        $conType = $this->admin_m->getAny('members', $_SESSION['id'], 'profileID', 'contType');
        $data['criteria'] = $this->admin_m->getCriteria($category, $conType);
        $data['coopNo'] = $coopNo;
        $data['balance'] = $this->admin_m->getAny('contributionBalance', $coopNo, 'coopNo', 'balance');
        $data['categories'] = $this->admin_m->getAll('categories');
        $this->load->view('admin/headerProfile');
        $this->load->view('admin/leftNav');
        $this->load->view('admin/applyMortgage', $data);
        $this->load->view('admin/footer');
    }

    public function addOfficer($msg = NULL) {
        if (!empty($msg)) {
            $data['msg'] = 'Officer Added';
        }
        $data['roles'] = $this->admin_m->getAll('confroles');
        $this->load->view('admin/headerProfile');
        $this->load->view('admin/addOfficer', $data);
    }

    public function verify() {
        $this->load->view('admin/headerProfile');
        if ($_SESSION['roles_id'] == '1') {
            $this->load->view('admin/leftNav');
        } else {
            $this->load->view('admin/leftNav2');
        }
        $this->load->view('admin/verify');
        $this->load->view('admin/footer');
    }

    public function printBadge($transNo) {
        //$transID=$this->input->post('transactionID');
        $data['details'] = $this->admin_m->paymentDetails($transNo);
        //$this->load->view('admin/header');
        $this->load->view('admin/badge', $data);
        //$this->load->view('admin/footer');
    }

    public function getMemberDetails($niqsNo) {
        $data['details'] = $this->admin_m->getMemberDetails($niqsNo);

        $this->load->view('admin/output', $data);
    }

   /* public function add() {
        $data['categories'] = $this->admin_m->getAll('confcat');
        $data['grade'] = $this->admin_m->getAll('grade');
        $data['state'] = $this->admin_m->getAll('state');
        $data['country'] = $this->admin_m->getAll('countries');
        $this->load->view('admin/headerProfile');
        if ($_SESSION['roles_id'] == '1') {
            $this->load->view('admin/leftNav');
        } else {
            $this->load->view('admin/leftNav2');
        }
        $this->load->view('admin/addAttendee', $data);
    }*/

    public function confirm() {
        $data['categories']=$this->site->getAll('project26_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');
		$data['amount'] = $this->input->post('amount');
        $this->load->view('admin/headerProfile');
        if ($_SESSION['roles_id'] == '1') {
            $this->load->view('admin/leftNav');
        } else {
            $this->load->view('admin/leftNav2');
        }
        $this->load->view('admin/confirm', $data);
        $this->load->view('admin/footer');
    }
	#################################
	## my code#########
	#################################
	public function add(){
		$data['categories'] = $this->site->getAll('project26_category');
        $this->load->view('admin/headerProfile');
        if ($_SESSION['roles_id'] == '1') {
            $this->load->view('admin/leftNav');
        } else {
            $this->load->view('admin/leftNav2');
        }
        $this->load->view('admin/addGuest', $data);
	}
    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');
        $postal=$this->input->post('postal');
        //$authNum=$this->randomString(9);
        //$date=date('Y-m-d');
        $authNum = $this->input->post('tellerNo');
        $date = $this->input->post('payDate');
		##############################################
		## my code starts here 
		#############################################
		$bank = $this->input->post('bank');
		$paymode = $this->input->post('paymode');
		$form_no = $this->input->post('form_no');
		##############################################
		## my code ends here 
		#############################################
       // $grade = ($this->input->post('grade')) ? $this->input->post('grade') : 'Other';
        //$amount = $this->admin_m->getAny('confcat', $category, 'confcatID', 'confcatFee');
		$amount = $this->input->post('amount');
        //$insert = $this->admin_m->insertDetails($category, $niqsNo, $names, $chapter, $phone, $email, $company, 
		//	$address, $postal, $country, $authNum, $date, $grade);
		##############################################
		## my code starts here 
		#############################################
		$insert = $this->admin_m->insertDetails($category, $niqsNo, $names, $phone, $email, $company, 
 $authNum, $date, $grade, $bank, $paymode, $form_no, $amount, $postal);
		##############################################
		## my code ends here 
		#############################################
		
        if ($insert) {
       // $date=date('Y-m-d');
$date = $this->input->post('payDate');
            $this->admin_m->insertTrans($date, $appType = 999, $amount, 'PAID', $insert, $authNum);
           
		   // redirect('admin/printBadge/' . $authNum, 'refresh');
 if (!empty($niqsNo)){ $this->admin_m->insertCPD($niqsNo); }
			
			##############################################
			## my code starts here 
			#############################################
			redirect('admin/add', 'refresh');
			##############################################
			## my code ends here 
			#############################################
        }
    }
	
    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 verify2() {
        $transNo = $this->input->post('transNo');
        //check if payment has been made
        $check = $this->admin_m->checkPayment($transNo);
        if ($check) {
            $data['applicants'] = $this->admin_m->paymentDetails($transNo);
            $this->load->view('admin/headerProfile');
            if ($_SESSION['roles_id'] == '1') {
                $this->load->view('admin/leftNav');
            } else {
                $this->load->view('admin/leftNav2');
            }
            //check if collected materials
            $confID = $this->admin_m->getAny('project26_conference', $transNo, 'confAuthNum', 'confID');
            $data['materials'] = $this->admin_m->getAll('conferencematerial');
            $data['materialCollection'] = $this->admin_m->checkMaterialCollection($confID);
            $data['matRemaining'] = $this->admin_m->checkMaterial2($confID);
            $this->load->view('admin/verify', $data);
            $this->load->view('admin/footer');
        } else {
            redirect('admin/verify', 'refresh');
        }
    }

    public function addConfMaterial() {
        $confID = $this->input->post('confID');
        $material = array_values($this->input->post('material'));
        foreach ($material as $values) {
            //insert conference material
            $insert = $this->admin_m->insertMaterial($confID, $values);
        }
        if ($insert) {
            redirect('admin/verify', 'refresh');
        }
    }

    public function insertOfficer() {
        $title = $this->input->post('title');
        $surname = $this->input->post('surname');
        $othernames = $this->input->post('othernames');
        $username = $this->input->post('username');
        $password = $this->input->post('password');
        $role = $this->input->post('role');

        $insert = $this->admin_m->insertOfficer($title, $surname, $othernames, $username, $password, $role);
        if ($insert) {
            redirect('admin/addOfficer/1', 'refresh');
        }
    }

    public function updateOfficer() {
        $title = $this->input->post('title');
        $surname = $this->input->post('surname');
        $othernames = $this->input->post('othernames');
        $username = $this->input->post('username');
        $password = $this->input->post('password');
        $role = $this->input->post('role');
        $id = $this->input->post('id');

        $update = $this->admin_m->updateOfficer($title, $surname, $othernames, $username, $password, $role, $id);
        if ($update) {
            redirect('admin/editOfficer/' . $id, 'refresh');
        }
    }

    public function editOfficer($id, $msg = NULL) {
        if (!empty($msg)) {
            $data['msg'] = 'Officer Details Updated';
        }
        $data['profile'] = $this->admin_m->editOfficer($id);
        $data['roles'] = $this->admin_m->getAll('confroles');
        $this->load->view('admin/headerProfile');
        $this->load->view('admin/editOfficer', $data);
    }

    public function officers() {
        $data['officers'] = $this->admin_m->officers($_SESSION['id']);
        $this->load->view('admin/headerProfile');
        if ($_SESSION['roles_id'] == '1') {
            $this->load->view('admin/leftNav');
        } else {
            $this->load->view('admin/leftNav2');
        }
        $this->load->view('admin/officers', $data);
        $this->load->view('admin/footer');
    }
public function editAttendee($msg=NULL){
    if(!empty($msg)){
        $data['msg']=$msg;
    }
    $this->load->view('admin/headerProfile');
        if ($_SESSION['roles_id'] == '1') {
            $this->load->view('admin/leftNav');
        } else {
            $this->load->view('admin/leftNav2');
        }
        $this->load->view('admin/editAttendee', $data);
        $this->load->view('admin/footer');
}
public function editAttendee2(){
    $data['categories'] = $this->site->getAll('recon3_category');
    $transNo=htmlspecialchars($this->input->post('transId'));
    $app_name=htmlspecialchars($this->input->post('app_name'));
    $this->load->view('admin/headerProfile');
        if ($_SESSION['roles_id'] == '1') {
            $this->load->view('admin/leftNav');
        } else {
            $this->load->view('admin/leftNav2');
        }
       if (empty($app_name)){
    $data['transaction']=$this->admin_m->paymentDetails($transNo,false);
    } elseif (empty($transNo)){
    $data['transaction']=$this->admin_m->paymentDetails(false,$app_name);
    }
       $this->load->view('admin/editAttendee2', $data);
       $this->load->view('admin/footer');
}
public function updateAttendee(){
    $confID=$this->input->post('confID');
    $name=$this->input->post('name');
    $email=$this->input->post('email');
    $phone=$this->input->post('phone');
$amount=$this->input->post('amount');
$transId=$this->input->post('transId');
$formNo = $this->input->post('formNo');
//$location = $this->input->post('location');
$category = $this->input->post('category');
$niqsNo = $this->input->post('niqsNo');
    $update=$this->admin_m->updateAttendee($confID,$name,$email,$phone,$amount,$transId,$niqsNo,$category,$formNo);
    if($update){
        redirect('admin/editAttendee/1','refresh');
    }
}

function bootstrap_paginate_template(){
        $config['first_link']       = 'First';
        $config['first_tag_open']   = '<li>';
        $config['first_tag_close']  = '</li>';
        $config['last_link']        = 'Last';
        $config['last_tag_open']    = '<li>';
        $config['last_tag_close']   = '</li>';

        $config['full_tag_open']    = '<nav class="pull-right"><ul class="pagination  pagination-sm">';
        $config['full_tag_close']   = '</ul><nav>';
        $config['cur_tag_open']     = '<li class="active"><a href="#">';
        $config['cur_tag_close']    = '</a></li>';

        $config['num_tag_open']     = '<li>';
        $config['num_tag_close']    = '</li>';

        $config['prev_link']        = '&laquo;';
        $config['prev_tag_open']    = '<li>';
        $config['prev_tag_close']   = '</li>';

        $config['next_link']        = '&raquo;';
        $config['next_tag_open']    = '<li>';
        $config['next_tag_close']   = '</li>';
        return $config;
    }
    public function home($field='confName', $by='ASC', $page=0){
        $data['profile'] = $this->admin_m->profile($_SESSION['id']);
        $data['transaction'] = $this->admin_m->transactions(30,$page, $field, $by);

        $this->load->library('pagination');

        $config['base_url']    = site_url().'/admin/home/'.$field.'/'.$by.'/';
        $config['total_rows']  = $this->admin_m->count_transactions();
        $config['per_page']    = 30;
        $config['uri_segment'] = 5;
        $this->bootstrap_paginate_template();
        $this->pagination->initialize($config);


        $data['page'] = $page;
        $data['field']  = $field;
        $data['by']   = $by;

        $this->load->view('admin/headerProfile');
        if ($_SESSION['roles_id'] == '1') {
            $this->load->view('admin/leftNav');
        } else {
            $this->load->view('admin/leftNav2');
        }
        $this->load->view('admin/home', $data);
        $this->load->view('admin/footer');
    }

//application for mortgage
    public function mortgageApply() {
        $coopNo = $this->input->post('coopNo');
        $date = date('Y-m-d');
        $insert = $this->admin_m->insertMortgageApply($coopNo, $date);
        if ($insert) {
            redirect('admin/applySuccess', 'refresh');
        }
    }

    public function applySuccess() {
        $data['msg'] = 'You have successfully applied for mortgage';
        $this->load->view('admin/headerProfile');
        $this->load->view('admin/applySuccess', $data);
    }

    //contributions
    public function contributions() {
        $data['contribution'] = $this->admin_m->getAll("contributionFees");
        $data['contType'] = $this->admin_m->getAny('members', $_SESSION['id'], 'profileID', 'contType');
        $this->load->view('admin/headerProfile');
        $this->load->view('admin/leftNav');
        $this->load->view('admin/contributions', $data);
        $this->load->view('admin/footer');
    }

    //checks mortgage qualifications
    public function qualification() {
        $data['profile'] = $this->admin_m->getMany('members', $_SESSION['id'], 'profileID');
        $coopNo = $this->admin_m->getAny('members', $_SESSION['id'], 'profileID', 'coopNo');
        $category = $this->admin_m->getAny('members', $_SESSION['id'], 'profileID', 'category');
        $conType = $this->admin_m->getAny('members', $_SESSION['id'], 'profileID', 'contType');
        $data['criteria'] = $this->admin_m->getCriteria($category, $conType);
        $data['coopNo'] = $coopNo;
        $data['balance'] = $this->admin_m->getAny('contributionBalance', $coopNo, 'coopNo', 'balance');
        $data['categories'] = $this->admin_m->getAll('categories');
        $this->load->view('admin/headerProfile');
        $this->load->view('admin/leftNav');
        $this->load->view('admin/qualification', $data);
        $this->load->view('admin/footer');
    }

    public function checkStatus() {
        $data['application'] = $this->admin_m->applicationStatus($_SESSION['coopNo']);
        $this->load->view('admin/headerProfile');
        $this->load->view('admin/leftNav');
        $this->load->view('admin/status', $data);
        $this->load->view('admin/footer');
    }

    //shows the transaction page
    public function transaction() {
        $this->load->view('admin/header2');
        $this->load->view('admin/transaction');
        $this->load->view('admin/footer');
    }

    public function membersProfile($nseregno) {
        $data['details'] = $this->admin_m->membersProfile($nseregno);
        $this->load->view('admin/details', $data);
    }

    public function displayUploads($name) {
        $data['name'] = $name;
        $this->load->view('admin/uploads', $data);
    }

    public function uploadsApply($passport, $name) {

        $config['upload_path'] = 'application/views/uploads/';
        $config['file_name'] = $name . ".jpg";
        $config['allowed_types'] = 'jpg';
        $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());
        } else { //else, set the success message
            $data = array('msg' => "Upload success!");

            $data['upload_data'] = $this->upload->data();
        }
    }

    public function uploads() {

        $type = $this->input->post('type');
//$pics=$this->input->post('pics');
        $config['upload_path'] = 'application/views/uploads/';
        $config['file_name'] = $type . $_SESSION['id'] . ".jpg";

        // 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('ssce')) {
            $data = array('msg' => $this->upload->display_errors());
        } else { //else, set the success message
            $data = array('msg' => "Upload success!");

            $data['upload_data'] = $this->upload->data();
        }
        // $this->load->view('admin/result', $data);

        /* $config['upload_path'] = './uploads';
          $config['file_name'] = $type . $_SESSION['id'] . ".jpg";
          $config['allowed_types'] = 'jpg';
          $config['max_size'] = '1000';
          $config['max_width']='1024';
          $config['max_height']='600';


          $this->load->library('upload', $config);
          if (!$this->upload->do_upload()) {
          echo "failure";
          $data['result'] = array('error' => $this->upload->display_errors());
          $this->load->view('admin/result',$data);
          // redirect('admin/home2/'.$error, 'refresh');

          } else {
          echo "success";
          $data['result'] = array('upload_data' => $this->upload->data());
          $this->load->view('admin/result',$data);
          // redirect('admin/home2', 'refresh');
          } */
    }

    public function download() {
        $this->load->helper('download');
        $data = file_get_contents("./Training.pdf");
        $name = 'Training Experience.pdf';
        force_download($name, $data);
        $data['message'] = 'File Downloaded';
        $this->load->view('admin/mydownloads', $data);
    }

    public function download2() {
        $this->load->helper('download');
        $data = file_get_contents("./undertaking.pdf");
        $name = 'Undertaking Form.pdf';
        force_download($name, $data);
        $data['message'] = 'File Downloaded';
        $this->load->view('admin/mydownloads', $data);
    }

    public function addToCart() {
        $nseregno = $this->input->post('nseregno');
        //if(!empty($this->input->post('item'))){
        $it = array_values($this->input->post('item'));
        //}
        $advance = $this->input->post('advance');
        //$transid=$_SESSION['transid'];
        $id = $_SESSION['id'];
        $date = date('Y-m-d');
        if (empty($_SESSION['transid'])) {
            $transid = str_shuffle("NSE") . $this->randomString(8);
            $_SESSION['transid'] = $transid;
        } else {
            $transid = $_SESSION['transid'];
        }
        $check = $this->admin_m->checkMembersExistCart($nseregno, $transid);
        if (!$check) {
            if (!empty($advance)) {

                $insert = $this->admin_m->insertItem($nseregno, '8', $id, $advance, $transid, $date);
            } else {
                foreach ($it as $items) {
                    //echo $items;
                    //get item name
                    $itemName = $this->admin_m->getItemName($items);
                    //echo "Item Name: ".$itemName;
                    //get Item amount
                    $itemAmount = $this->admin_m->itemAmount($nseregno, $itemName);
                    // echo "Item Amount: ".$itemAmount; 
                    //Inserts into company transaction table
                    //echo $transid;



                    $insert = $this->admin_m->insertItem($nseregno, $items, $id, $itemAmount, $transid, $date);
                }
            }
            if ($insert) {
                $data['type'] = 1;
                $data['msg'] = 'Item Added to cart successfully';
                $data['url'] = 'transaction';
                //$this->load->view('admin/header2');
                $this->load->view('admin/result', $data);
                //$this->load->view('admin/footer');
            } else {
                $data['type'] = 0;
                $data['msg'] = 'Error adding to cart';
                $data['url'] = 'index';
                //$this->load->view('admin/header2');
                $this->load->view('admin/result', $data);
                //$this->load->view('admin/footer');
            }
        } else {
            echo "Member Dues already added to cart";
            header("refresh: 3; url=transaction");
            // header(“Refresh:seconds;url=“your path”);
            //redirect('admin/transaction','refresh');
        }
    }

    public function contact() {
        $this->load->view('admin/header2');
        $this->load->view('admin/contact');
        $this->load->view('admin/footer');
    }

    //displays total amount in cart
    public function dispTotalAmount() {
        if (!empty($_SESSION['transid'])) {
            $transid = $_SESSION['transid'];
        } else {
            $transid = '0000';
        }
        if (!empty($_SESSION['id'])) {
            $compId = $_SESSION['id'];
        } else {
            $compId = 'o90bw2';
        }
        $data['totalAmount'] = $this->admin_m->dispTotalAmount($transid, $compId);
        $_SESSION['amount'] = $this->admin_m->dispTotalAmount($transid, $compId);
        $this->load->view('admin/dispTotalAmount', $data);
    }

    public function transSummary() {
        if (!empty($_SESSION['transid'])) {
            $transid = $_SESSION['transid'];
        } else {
            $transid = '9s2890';
        }
        if (!empty($_SESSION['id'])) {
            $compId = $_SESSION['id'];
        } else {
            $compId = 'o90bw2';
        }
        $data['transSummary'] = $this->admin_m->transSummary($transid, $compId);
        $this->load->view('admin/transSummary', $data);
    }

    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 logout() {
        $_SESSION['id'] = '';
        $_SESSION['surname'] =  '';
        $_SESSION['othernames'] =  '';
        $_SESSION['username'] =  '';
        $_SESSION['email'] =  '';
        $_SESSION['roles_id'] =  '';
        session_destroy();
        session_unset();
     //  $this->load->view('admin/logout');
     $this->login2();
    //redirect('admin/login', refresh);
    }

    public function viewCart() {
        if (!empty($_SESSION['transid'])) {
            $transid = $_SESSION['transid'];
        } else {
            $transid = '9s2890';
        }
        if (!empty($_SESSION['id'])) {
            $compId = $_SESSION['id'];
        } else {
            $compId = 'o90bw2';
        }

        $data['summary'] = $this->admin_m->cartSummary($transid, $compId);
        $this->load->view('admin/header2');
        $this->load->view('admin/viewCart', $data);
        $this->load->view('admin/footer');
    }

    //deletes an item off the cart
    public function deleteItem($id) {
        $delete = $this->admin_m->deleteItem($id);
        if ($delete) {
            $data['type'] = 1;
            $data['msg'] = 'Item successfully deleted';
            $data['url'] = 'viewCart';
            //$this->load->view('admin/header2');
            $this->load->view('admin/deleteItem', $data);
            //$this->load->view('admin/footer');
        }
    }

    //individual details for members
    public function viewDetails($regno) {
        if (!empty($_SESSION['transid'])) {
            $transid = $_SESSION['transid'];
        } else {
            $transid = '9s2890';
        }
        if (!empty($_SESSION['id'])) {
            $compId = $_SESSION['id'];
        } else {
            $compId = 'o90bw2';
        }
        $data['summary'] = $this->admin_m->viewDetails($transid, $compId, $regno);
        //$this->load->view('admin/header2');
        $this->load->view('admin/viewDetails', $data);
        //$this->load->view('admin/footer');
    }

    //displays profile 
    public function profile($msg = NULL) {
        //if (!empty($_SESSION['id'])) {
        $id = $_SESSION['id'];
        if (!empty($msg)) {
            $data['msg'] = 'Profile Successfully Updated';
        }
        $data['profile'] = $this->admin_m->profile($id);

        $this->load->view('admin/headerProfile');
        if ($_SESSION['roles_id'] == 1) {
            $this->load->view('admin/leftNav');
        } else {
            $this->load->view('admin/leftNav2');
        }
        $this->load->view('admin/profile', $data);
        $this->load->view('admin/footer');
        //}
    }

    public function conference($field='confName', $by='ASC', $page=0){
    
        $data['profile'] = $this->admin_m->profile($_SESSION['id']);
        $data['transaction'] = $this->admin_m->transactions(30,$page, $field, $by);

        $this->load->library('pagination');

        $config['base_url']    = site_url().'/admin/conference/'.$field.'/'.$by.'/';
        $config['total_rows']  = $this->admin_m->count_transactions();
        $config['per_page']    = 30;
        $config['uri_segment'] = 5;
        $this->bootstrap_paginate_template();
        $this->pagination->initialize($config);


        $data['page'] = $page;
        $data['field']  = $field;
        $data['by']   = $by;

        $this->load->view('admin/headerProfile');
        if ($_SESSION['roles_id'] == '1') {
            $this->load->view('admin/leftNav');
        } else {
            $this->load->view('admin/leftNav2');
        }
        $this->load->view('admin/home', $data);
        $this->load->view('admin/footer');
    }

    //confirms profile update
    public function confirmUpdateReg() {
        $data['compName'] = $this->input->post('comp-name');
        $data['compAddress'] = $this->input->post('comp-address');
        $data['compEmail'] = $this->input->post('comp-email');
        $data['compPhone'] = $this->input->post('comp-phone');
        $data['contact'] = $this->input->post('contact');
        $data['password'] = $this->input->post('comp-password');
        $this->load->view('admin/header2');
        $this->load->view('admin/confirmDetailsUpdate', $data);
        $this->load->view('admin/footer');
    }

}

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