<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Loan extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
    }
    public function index()
    {
        //If currency not set retrieve from DB
        if (!$this->session->has_userdata('currency')) {
            $q1 = $this->db->query("SELECT a.currency_name,a.currency,a.currency_code,a.exchange_rate,a.symbol,b.currency_placement FROM db_currency a,db_sitesettings b WHERE a.id=b.currency_id AND b.id=1");
            $currency = $q1->row()->currency;
            $currency_placement = $q1->row()->currency_placement;
            $currency_code = $q1->row()->currency_code;
            $exchange_rate = $q1->row()->exchange_rate;
            $this->session->set_userdata(array('currency'  => $currency, 'currency_placement'  => $currency_placement, 'currency_code'  => $currency_code, 'exchange_rate' => $exchange_rate));
        }
        //end 
        $query = $this->db->select('site_name,version,language_id,timezone,time_format,date_format')->where('id', 1)->get('db_sitesettings');
        date_default_timezone_set(trim($query->row()->timezone));
        $time_format = (trim($query->row()->time_format) == '24') ? date("h:i:s") : date("h:i:s a");
        $date_view_format = trim($query->row()->date_format);
        $this->session->set_userdata(array('view_date'  => $date_view_format));
        $this->session->set_userdata(array('view_time'  => $query->row()->time_format));


        //CHECK LANGUAGE IN SESSION ELSE FROM DB
        if (!$this->session->has_userdata('language') && $this->session->has_userdata('logged_in')) {
            $this->load->model('language_model');
            $this->language_model->set($query->row()->language_id);
        }
        if ($this->session->has_userdata('logged_in')) {
            $this->lang->load($this->session->userdata('language'), $this->session->userdata('language'));
        }
        //End

        $data = array(
            'theme_link'    => base_url() . 'theme/',
            'base_url'      => base_url(),
            'SITE_TITLE'    => $query->row()->site_name,
            'VERSION'       => $query->row()->version,
            'CURRENCY'       => $this->session->userdata('currency'),
            'CURRENCY_PLACE' => $this->session->userdata('curre
			ncy_placement'),
            'CURRENCY_CODE' => $this->session->userdata('currency_code'),
            'EXHCHANGE_RATE' => $this->session->userdata('exchange_rate'),
            'CUR_DATE'      => date("Y-m-d"),
            'VIEW_DATE'      => $date_view_format,
            'CUR_TIME'      => $time_format,
            'SYSTEM_IP'     => $_SERVER['REMOTE_ADDR'],
            'SYSTEM_NAME'   => gethostbyaddr($_SERVER['REMOTE_ADDR']),
            'CUR_USERNAME'  => $this->session->userdata('inv_username'),
            'CUR_USERID'    => $this->session->userdata('inv_userid'),
        );
        $data['account'] = $this->get_loan();

        $data['page_title'] = 'Loan';
        $this->load->view('loan-list', $data);
    }
    public function get_loan()
    {
        $query = $this->db->get('db_loan');
        return $query->result();
    }

    public function ajax_list()
    {
        $query = $this->db->get('db_loan');
        $list =  $query->result();
        $data = array();
        $no = $_POST['start'];
        foreach ($list as $loan) {
            $no++;
            $row = array();
            $row[] = $no;      
            $row[] = $loan->referance; 
            $authority_query = $this->db->get_where('db_authority', array('id' => $loan->loan_authority));
            $authority = $authority_query->row();
            $row[] = isset($authority->authority_name) ? $authority->authority_name : '';
            $account_query = $this->db->get_where('db_account', array('id' => $loan->account));
            $account = $account_query->row();
            $row[] = isset($account->bank_name) ? $account->bank_name : '';
            $row[] = $loan->amount; 
            $row[] = $loan->interest; 
            $row[] = $loan->payable_amount; 
            $row[] = $loan->per_month; 
            $row[] = $loan->amount; 
            $row[] = $loan->status == 1 ? '<span class="label label-success" style="cursor:pointer">Active </span>' : '<span class="label label-danger" style="cursor:pointer">Inactive </span>';
            $str2 = '<div class="btn-group" title="View Loan">
										<a class="btn btn-primary btn-o dropdown-toggle" data-toggle="dropdown" href="#">
											Action <span class="caret"></span>
										</a>
										<ul role="menu" class="dropdown-menu dropdown-light pull-right">';

            $str2 .= '<li>
												<a title="Edit Record ?" href="loan/edit/' . $loan->id . '">
													<i class="fa fa-fw fa-edit text-blue"></i>Edit
												</a>
											</li>';

            $str2 .= '<li>
												<a style="cursor:pointer" title="Delete Record ?" onclick="delete_loan(' . $loan->id . ')">
													<i class="fa fa-fw fa-trash text-red"></i>Delete
												</a>
											</li>
											
										</ul>
									</div>';

            $row[] = $str2;
            $data[] = $row;
        }

        $output = array(
            "draw" => $_POST['draw'],
            "recordsTotal" => count($list),
            "recordsFiltered" => 1,
            "data" => $data,
        );
        //output to json format
        echo json_encode($output);
    }

    public function add()
    {
        //If currency not set retrieve from DB
        if (!$this->session->has_userdata('currency')) {
            $q1 = $this->db->query("SELECT a.currency_name,a.currency,a.currency_code,a.exchange_rate,a.symbol,b.currency_placement FROM db_currency a,db_sitesettings b WHERE a.id=b.currency_id AND b.id=1");
            $currency = $q1->row()->currency;
            $currency_placement = $q1->row()->currency_placement;
            $currency_code = $q1->row()->currency_code;
            $exchange_rate = $q1->row()->exchange_rate;
            $this->session->set_userdata(array('currency'  => $currency, 'currency_placement'  => $currency_placement, 'currency_code'  => $currency_code, 'exchange_rate' => $exchange_rate));
        }
        //end 
        $query = $this->db->select('site_name,version,language_id,timezone,time_format,date_format')->where('id', 1)->get('db_sitesettings');
        date_default_timezone_set(trim($query->row()->timezone));
        $time_format = (trim($query->row()->time_format) == '24') ? date("h:i:s") : date("h:i:s a");
        $date_view_format = trim($query->row()->date_format);
        $this->session->set_userdata(array('view_date'  => $date_view_format));
        $this->session->set_userdata(array('view_time'  => $query->row()->time_format));


        //CHECK LANGUAGE IN SESSION ELSE FROM DB
        if (!$this->session->has_userdata('language') && $this->session->has_userdata('logged_in')) {
            $this->load->model('language_model');
            $this->language_model->set($query->row()->language_id);
        }
        if ($this->session->has_userdata('logged_in')) {
            $this->lang->load($this->session->userdata('language'), $this->session->userdata('language'));
        }
        //End

        $data = array(
            'theme_link'    => base_url() . 'theme/',
            'base_url'      => base_url(),
            'SITE_TITLE'    => $query->row()->site_name,
            'VERSION'       => $query->row()->version,
            'CURRENCY'       => $this->session->userdata('currency'),
            'CURRENCY_PLACE' => $this->session->userdata('curre
			ncy_placement'),
            'CURRENCY_CODE' => $this->session->userdata('currency_code'),
            'EXHCHANGE_RATE' => $this->session->userdata('exchange_rate'),
            'CUR_DATE'      => date("Y-m-d"),
            'VIEW_DATE'      => $date_view_format,
            'CUR_TIME'      => $time_format,
            'SYSTEM_IP'     => $_SERVER['REMOTE_ADDR'],
            'SYSTEM_NAME'   => gethostbyaddr($_SERVER['REMOTE_ADDR']),
            'CUR_USERNAME'  => $this->session->userdata('inv_username'),
            'CUR_USERID'    => $this->session->userdata('inv_userid'),
        );
        $data['page_title'] = 'Loan';
        $this->load->view('loan', $data);
    }
    public function save()
    {
        if (!$this->session->has_userdata('currency')) {
            $q1 = $this->db->query("SELECT a.currency_name,a.currency,a.currency_code,a.exchange_rate,a.symbol,b.currency_placement FROM db_currency a,db_sitesettings b WHERE a.id=b.currency_id AND b.id=1");
            $currency = $q1->row()->currency;
            $currency_placement = $q1->row()->currency_placement;
            $currency_code = $q1->row()->currency_code;
            $exchange_rate = $q1->row()->exchange_rate;
            $this->session->set_userdata(array('currency'  => $currency, 'currency_placement'  => $currency_placement, 'currency_code'  => $currency_code, 'exchange_rate' => $exchange_rate));
        }
        //end 
        $query = $this->db->select('site_name,version,language_id,timezone,time_format,date_format')->where('id', 1)->get('db_sitesettings');
        date_default_timezone_set(trim($query->row()->timezone));
        $time_format = (trim($query->row()->time_format) == '24') ? date("h:i:s") : date("h:i:s a");
        $date_view_format = trim($query->row()->date_format);
        $this->session->set_userdata(array('view_date'  => $date_view_format));
        $this->session->set_userdata(array('view_time'  => $query->row()->time_format));


        //CHECK LANGUAGE IN SESSION ELSE FROM DB
        if (!$this->session->has_userdata('language') && $this->session->has_userdata('logged_in')) {
            $this->load->model('language_model');
            $this->language_model->set($query->row()->language_id);
        }
        if ($this->session->has_userdata('logged_in')) {
            $this->lang->load($this->session->userdata('language'), $this->session->userdata('language'));
        }
        //End

        $data = array(
            'theme_link'    => base_url() . 'theme/',
            'base_url'      => base_url(),
            'SITE_TITLE'    => $query->row()->site_name,
            'VERSION'       => $query->row()->version,
            'CURRENCY'       => $this->session->userdata('currency'),
            'CURRENCY_PLACE' => $this->session->userdata('curre
            ncy_placement'),
            'CURRENCY_CODE' => $this->session->userdata('currency_code'),
            'EXHCHANGE_RATE' => $this->session->userdata('exchange_rate'),
            'CUR_DATE'      => date("Y-m-d"),
            'VIEW_DATE'      => $date_view_format,
            'CUR_TIME'      => $time_format,
            'SYSTEM_IP'     => $_SERVER['REMOTE_ADDR'],
            'SYSTEM_NAME'   => gethostbyaddr($_SERVER['REMOTE_ADDR']),
            'CUR_USERNAME'  => $this->session->userdata('inv_username'),
            'CUR_USERID'    => $this->session->userdata('inv_userid'),
        );
        $data = array( 
            'loan_authority' => $this->input->post('loan_authority'),
            'account' => $this->input->post('account'), 
            'loan_reason' => $this->input->post('loan_reason'),
            'referance' => $this->input->post('referance'),
            'loan_type' => $this->input->post('loan_type'),
            'amount' => $this->input->post('amount'),
            'interest' => $this->input->post('interest'),
            'payment_type' => $this->input->post('payment_type'),
            'duration' => $this->input->post('duration'),
            'per_month' => $this->input->post('per_month'),
            'payable_amount' => $this->input->post('payable_amount'),
            'date' => date("Y-m-d", strtotime($this->input->post('date'))),
            'note' => $this->input->post('note'),
            'status' => $this->input->post('status'),
        );
        $this->db->insert('db_loan', $data);
        return 'success';
    }

    public function edit($id)
    {
        if (!$this->session->has_userdata('currency')) {
            $q1 = $this->db->query("SELECT a.currency_name,a.currency,a.currency_code,a.exchange_rate,a.symbol,b.currency_placement FROM db_currency a,db_sitesettings b WHERE a.id=b.currency_id AND b.id=1");
            $currency = $q1->row()->currency;
            $currency_placement = $q1->row()->currency_placement;
            $currency_code = $q1->row()->currency_code;
            $exchange_rate = $q1->row()->exchange_rate;
            $this->session->set_userdata(array('currency'  => $currency, 'currency_placement'  => $currency_placement, 'currency_code'  => $currency_code, 'exchange_rate' => $exchange_rate));
        }
        //end 
        $query = $this->db->select('site_name,version,language_id,timezone,time_format,date_format')->where('id', 1)->get('db_sitesettings');
        date_default_timezone_set(trim($query->row()->timezone));
        $time_format = (trim($query->row()->time_format) == '24') ? date("h:i:s") : date("h:i:s a");
        $date_view_format = trim($query->row()->date_format);
        $this->session->set_userdata(array('view_date'  => $date_view_format));
        $this->session->set_userdata(array('view_time'  => $query->row()->time_format));


        //CHECK LANGUAGE IN SESSION ELSE FROM DB
        if (!$this->session->has_userdata('language') && $this->session->has_userdata('logged_in')) {
            $this->load->model('language_model');
            $this->language_model->set($query->row()->language_id);
        }
        if ($this->session->has_userdata('logged_in')) {
            $this->lang->load($this->session->userdata('language'), $this->session->userdata('language'));
        }
        //End

        $data = array(
            'theme_link'    => base_url() . 'theme/',
            'base_url'      => base_url(),
            'SITE_TITLE'    => $query->row()->site_name,
            'VERSION'       => $query->row()->version,
            'CURRENCY'       => $this->session->userdata('currency'),
            'CURRENCY_PLACE' => $this->session->userdata('curre
			ncy_placement'),
            'CURRENCY_CODE' => $this->session->userdata('currency_code'),
            'EXHCHANGE_RATE' => $this->session->userdata('exchange_rate'),
            'CUR_DATE'      => date("Y-m-d"),
            'VIEW_DATE'      => $date_view_format,
            'CUR_TIME'      => $time_format,
            'SYSTEM_IP'     => $_SERVER['REMOTE_ADDR'],
            'SYSTEM_NAME'   => gethostbyaddr($_SERVER['REMOTE_ADDR']),
            'CUR_USERNAME'  => $this->session->userdata('inv_username'),
            'CUR_USERID'    => $this->session->userdata('inv_userid'),
        );
        $data['page_title'] = 'Loan';
        $query = $this->db->get_where('db_loan', array('id' => $id));
        $result = $query->row_array();
        $data['q_idd'] = $id;  
        $data['loan_authority'] = $result['loan_authority'];
        $data['account'] = $result['account']; 
        $data['loan_reason'] = $result['loan_reason'];
        $data['referance'] = $result['referance'];
        $data['loan_type'] = $result['loan_type'];
        $data['amount'] = $result['amount'];
        $data['interest'] = $result['interest'];
        $data['payment_type'] = $result['payment_type'];
        $data['duration'] = $result['duration'];
        $data['per_month'] = $result['per_month'];
        $data['payable_amount'] = $result['payable_amount'];
        $data['date'] = $result['date'];
        $data['notes'] = $result['note'];
        $data['statuss'] = $result['status'];
        $data = array_merge($data, $result);
        $this->load->view('loan', $data);
    }
    public function update()
    { 
        $this->load->library('form_validation'); 
        $this->form_validation->set_rules('loan_authority', 'Loan Authority', 'required');
        $this->form_validation->set_rules('account', 'Account Name', 'required'); 
        $this->form_validation->set_rules('loan_reason', 'Loan Reason', 'required');
        $this->form_validation->set_rules('referance', 'Regerance', 'required');
        $this->form_validation->set_rules('loan_type', 'Loan Type', 'required');
        $this->form_validation->set_rules('amount', 'Note', 'required');
        $this->form_validation->set_rules('interest', 'Interest', 'required');
        $this->form_validation->set_rules('payment_type', 'Payment Type', 'required');
        $this->form_validation->set_rules('duration', 'Duration', 'required');
        $this->form_validation->set_rules('per_month', 'Per Month', 'required');
        $this->form_validation->set_rules('payable_amount', 'Payable Amount', 'required');
        $this->form_validation->set_rules('date', 'Date', 'required');
        $this->form_validation->set_rules('note', 'Note', 'required');
        $this->form_validation->set_rules('status', 'Status', 'required');

        if ($this->form_validation->run() == FALSE) {
            // Validation failed
            $response['status'] = 'error';
            $response['message'] = validation_errors();
        } else {
            // Validation passed
            $id = $this->input->post('q_id');
            date_default_timezone_set('Asia/Kabul');
            // Data to be saved or updated
            $data = array(
                'loan_authority' => $this->input->post('loan_authority'),
                'account' => $this->input->post('account'),  
                'loan_reason' => $this->input->post('loan_reason'),
                'referance' => $this->input->post('referance'),
                'loan_type' => $this->input->post('loan_type'),
                'amount' => $this->input->post('amount'),
                'interest' => $this->input->post('interest'),
                'payment_type' => $this->input->post('payment_type'),
                'duration' => $this->input->post('duration'),
                'per_month' => $this->input->post('per_month'),
                'payable_amount' => $this->input->post('payable_amount'),
                'date' => date("Y-m-d", strtotime($this->input->post('date'))),
                'note' => $this->input->post('note'),
                'status' => $this->input->post('status'),
            );

            if (empty($id)) {
                // Insert new record
                $this->db->insert('db_loan', $data);
                $response['status'] = 'success';
                $response['message'] = 'Acccount type added successfully!';
            } else {
                // Update existing record
                $this->db->where('id', $id);
                $this->db->update('db_loan', $data);
                $response['status'] = 'success';
                $response['message'] = 'Loan updated successfully!';
            }
        }

        // Output JSON response
        echo json_encode($response);
    }

    public function delete()
    {

        if (!$this->session->has_userdata('currency')) {
            $q1 = $this->db->query("SELECT a.currency_name,a.currency,a.currency_code,a.exchange_rate,a.symbol,b.currency_placement FROM db_currency a,db_sitesettings b WHERE a.id=b.currency_id AND b.id=1");
            $currency = $q1->row()->currency;
            $currency_placement = $q1->row()->currency_placement;
            $currency_code = $q1->row()->currency_code;
            $exchange_rate = $q1->row()->exchange_rate;
            $this->session->set_userdata(array('currency'  => $currency, 'currency_placement'  => $currency_placement, 'currency_code'  => $currency_code, 'exchange_rate' => $exchange_rate));
        }
        //end 
        $query = $this->db->select('site_name,version,language_id,timezone,time_format,date_format')->where('id', 1)->get('db_sitesettings');
        date_default_timezone_set(trim($query->row()->timezone));
        $time_format = (trim($query->row()->time_format) == '24') ? date("h:i:s") : date("h:i:s a");
        $date_view_format = trim($query->row()->date_format);
        $this->session->set_userdata(array('view_date'  => $date_view_format));
        $this->session->set_userdata(array('view_time'  => $query->row()->time_format));


        //CHECK LANGUAGE IN SESSION ELSE FROM DB
        if (!$this->session->has_userdata('language') && $this->session->has_userdata('logged_in')) {
            $this->load->model('language_model');
            $this->language_model->set($query->row()->language_id);
        }
        if ($this->session->has_userdata('logged_in')) {
            $this->lang->load($this->session->userdata('language'), $this->session->userdata('language'));
        }
        //End

        $data = array(
            'theme_link'    => base_url() . 'theme/',
            'base_url'      => base_url(),
            'SITE_TITLE'    => $query->row()->site_name,
            'VERSION'       => $query->row()->version,
            'CURRENCY'       => $this->session->userdata('currency'),
            'CURRENCY_PLACE' => $this->session->userdata('curre
                ncy_placement'),
            'CURRENCY_CODE' => $this->session->userdata('currency_code'),
            'EXHCHANGE_RATE' => $this->session->userdata('exchange_rate'),
            'CUR_DATE'      => date("Y-m-d"),
            'VIEW_DATE'      => $date_view_format,
            'CUR_TIME'      => $time_format,
            'SYSTEM_IP'     => $_SERVER['REMOTE_ADDR'],
            'SYSTEM_NAME'   => gethostbyaddr($_SERVER['REMOTE_ADDR']),
            'CUR_USERNAME'  => $this->session->userdata('inv_username'),
            'CUR_USERID'    => $this->session->userdata('inv_userid'),
        );
        $this->db->where('id', $_POST['q_id']);
        $this->db->delete('db_loan');
        $response['status'] = 'success';
        $response['message'] = 'Loan deleted successfully!'; 
        echo json_encode($response); 
    }

    public function update_loan($id, $data)
    {
        $this->db->where('id', $id);
        $this->db->update('db_account', $data);
    }
}
