<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Loans extends CI_Controller
{
  public $page_data = array();

  function __construct()
  {
    parent::__construct();
    $this->initial();
  }
  public function initial()
  {
    ini_set('max_execution_time', 5000);
    ini_set("memory_limit", "-1");

    $this->load->model('User_model', 'User');
    $this->load->model('Work_model', 'Work');
    $this->load->model('Client_model', 'Client');
    $this->load->model('Account_model', 'Account');
    $this->load->model('Settings_model', 'Settings');
    $this->load->model('Loan_model', 'Loan');
    $this->load->model('Labour_model', 'Labour');
    $this->load->library('Projects_management','projects_management');

    //        Check User Logged in or Not
    $allowed_user_roles = array("madmin","admin","general_manager","accounts_manager","auditor");
    if($this->User->is_logged_in($allowed_user_roles)==false){
      redirect(base_url(), 'refresh');
    }
    //        File Directory
    $this->page_data['directory'] = "loans";

    $user_accounts_where = "ur.role_name='supervisor' or ur.role_name='general_manager'";
    $this->page_data['user_accounts'] = $this->Account->select_account_heads("",$user_accounts_where,"user")->result();
    if($this->config->item('Labour_group_member_payment')==0){
      $this->db->where('(l.labour_type=0 or (l.labour_type=1 and group_position=1))');
    }
    $this->page_data['labours_2'] = $this->Labour->select_labours()->result();
    if ($this->session->userdata('user_role') == 'supervisor') {
      //          Select Assigned Works Only
      $supervisor_id = $this->session->userdata('user_id');
      $this->db->where("FIND_IN_SET($supervisor_id, w.assigned_users)");
    }
    $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();
  }
  public function index($loan_type='')
  {
    $this->view($loan_type);
  }

  public function view($loan_type='')
  {
    if($loan_type=='receivable'){
      $this->page_data['page_name'] = 'loans_receivable';
    }else{
      $this->page_data['page_name'] = 'loans_payable';
    }

    if($this->session->userdata('user_role')=='supervisor') {
      //          Select Assigned Works Only
      $supervisor_id = $this->session->userdata('user_id');
      $this->db->where("FIND_IN_SET($supervisor_id, w.assigned_users)");
    }
    $this->page_data['work_contracts'] = $this->Work->select_work("*")->result();

    $this->page_data['clients'] = $this->Client->select_client()->result();
    $this->load->view('Index',$this->page_data);
  }
  public function provider($view,$id)
  {
    if($view=='profile' && $id!=''){
      $this->page_data['provider_data'] = $this->Loan->select_loan_provider("",array("loan_provider_id"=>$id));
      if($this->page_data['provider_data']->num_rows()==1){
        $this->page_data['provider_data'] = $this->page_data['provider_data']->row();
        $this->page_data['page_name'] = 'provider_profile';
        $this->load->view('Index',$this->page_data);
      }else{

      }
    }else{
      show_404();
    }

  }
  public function create_loan()
  {
    $redirect_url= $this->security->xss_clean($this->input->post('redirect_url'));
    $data2['loan_title'] = $this->security->xss_clean($this->input->post('title'));
    $data2['loan_type'] = $this->security->xss_clean($this->input->post('loan_type'));
    $data2['description'] = $this->security->xss_clean($this->input->post('description'));
    $data2['total_loan_amount'] = $this->security->xss_clean($this->input->post('loan_amount'));
    $data2['op_balance'] = $this->security->xss_clean($this->input->post('op_balance'));
    // $data2['current_balance_payable'] = $this->security->xss_clean($this->input->post('payable_balance'));
    $data2['current_balance_payable'] = $data2['total_loan_amount']+$data2['op_balance'];
    $data2['credit_ac'] = $this->security->xss_clean($this->input->post('credit_acc'));
    $data2['provider_id'] = $this->security->xss_clean($this->input->post('provider'));
    if($data2['loan_type']=='payable'){
      $data2['work_id'] = $this->security->xss_clean($this->input->post('work_id'));
      if($data2['work_id']!=''){
        $data2['project_stage_id'] = $this->projects_management->get_project_stage_id($data2['work_id']);
      }
    }

    if($this->input->post('loan_date')!=''){
      $data2['loan_date'] = date('Y-m-d',strtotime($this->input->post('loan_date')));
    }
    if($this->config->item('User_enable_data_entry_approval')==1 && $this->session->userdata('user_role_id')>2){
      $data2['entry_approval_status'] = 0;
    }
    if($this->config->item('User_enable_data_entry_approval_2_level')==1 && $this->session->userdata('user_role_id')>2){
      $data2['entry_approval_status_2'] = 0;
    }
    $data2['created_date'] = date('Y-m-d H:i:s');
    $data2['created_by'] = $this->session->userdata('user_id');

    $result2 = $this->Loan->create_loan($data2);
    $flash_data['status'] = $result2['status'];
    if ($flash_data['status'] == 1) {
      $provider_data = $this->Loan->select_loan_provider("",array("loan_provider_id"=>$data2['provider_id']));

      $transaction_data['reference_id'] = $result2['insert_id'];
      $transaction_data['reference_type'] = 'loan';
      $transaction_data['tr_reference_no'] = '';
      $transaction_data['tr_remarks'] = $data2['loan_title'];
      $transaction_data['created_date'] = date('Y-m-d H:i:s');
      $transaction_data['created_by'] = $this->session->userdata('user_id');
      if($data2['loan_type']=='receivable'){
        $transaction_data['tr_type'] = 'loan_transaction';
        $transaction_data['tr_debit_acc'] = $data2['credit_ac'];
        $transaction_data['tr_credit_acc'] = 13;//Loan Payment
      }else{
        $transaction_data['tr_type'] = 'loan_receipt_transaction';
        $transaction_data['tr_credit_acc'] = $data2['credit_ac'];
        $transaction_data['tr_debit_acc'] = 15;//Loan Receipts
      }
      $transaction_data['tr_description'] = ucwords(str_replace('_',' ',$transaction_data['tr_type']));
      $transaction_data['tr_amount'] = $data2['total_loan_amount'];
      if(isset($data2['loan_date']) && $data2['loan_date']!=''){
        $transaction_data['tr_date'] = $data2['loan_date'];
      }else{
        $transaction_data['tr_date'] = date('Y-m-d');
      }

      $transaction_result =  $this->Account->create_account_transaction($transaction_data);
      // Add Loan Receipt Transaction

      $flash_data['flashdata_msg'] = 'Loan Added Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';

    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    echo json_encode($flash_data);
  }
  public function update_loan()
  {
    $redirect_url= $this->security->xss_clean($this->input->post('redirect_url'));
    $data2['loan_type'] = $this->security->xss_clean($this->input->post('loan_type'));
    $data2['loan_id'] = $this->security->xss_clean($this->input->post('loan_id'));
    $data2['loan_title'] = $this->security->xss_clean($this->input->post('title'));
    $data2['description'] = $this->security->xss_clean($this->input->post('description'));
    $data2['total_loan_amount'] = $this->security->xss_clean($this->input->post('loan_amount'));
    $data2['op_balance'] = $this->security->xss_clean($this->input->post('op_balance'));
    // $data2['current_balance_payable'] = $this->security->xss_clean($this->input->post('payable_balance'));
    $data2['current_balance_payable'] = $data2['total_loan_amount']+$data2['op_balance'];
    $data2['credit_ac'] = $this->security->xss_clean($this->input->post('credit_acc'));
    $data2['provider_id'] = $this->security->xss_clean($this->input->post('provider'));
    if($data2['loan_type']=='payable'){
      $data2['work_id'] = $this->security->xss_clean($this->input->post('work_id'));
      if($data2['work_id']!=''){
        $data2['project_stage_id'] = $this->projects_management->get_project_stage_id($data2['work_id']);
      }
    }
    if($this->input->post('loan_date')!=''){
      $data2['loan_date'] = date('Y-m-d',strtotime($this->input->post('loan_date')));
    }
    $data2['updated_date'] = date('Y-m-d H:i:s');
    $data2['updated_by'] = $this->session->userdata('user_id');

    $result2 = $this->Loan->update_loan($data2);
    $flash_data['status'] = $result2;
    if ($flash_data['status'] == 1) {
      $flash_data['flashdata_msg'] = 'Loan Details Updated Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';

      //  Update Loan Receipt Transactions
      $transaction_data['reference_id'] = $data2['loan_id'];
      $transaction_data['reference_type'] = 'loan';
      $loan_tr_data = $this->Account->select_account_transaction("ats.*",$transaction_data);
      if($loan_tr_data->num_rows()==1){
        $provider_data = $this->Loan->select_loan_provider("",array("loan_provider_id"=>$data2['provider_id']));
        $transaction_data['transaction_id'] = $loan_tr_data->row()->transaction_id;
        $transaction_data['tr_remarks'] = $data2['loan_title'];
        if($data2['loan_type']=='receivable'){
          $transaction_data['tr_type'] = 'loan_transaction';
          $transaction_data['tr_debit_acc'] = $data2['credit_ac'];
          $transaction_data['tr_credit_acc'] = 13;//Loan Payment
        }else{
          $transaction_data['tr_type'] = 'loan_receipt_transaction';
          $transaction_data['tr_credit_acc'] = $data2['credit_ac'];
          $transaction_data['tr_debit_acc'] = 15;//Loan Receipts
        }
        $transaction_data['tr_amount'] = $data2['total_loan_amount'];
        if(isset($data2['loan_date']) && $data2['loan_date']!=''){
          $transaction_data['tr_date'] = $data2['loan_date'];
        }
        $this->Account->update_account_transaction($transaction_data);
      }
    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    echo json_encode($flash_data);
  }
  public function delete_loan()
  {
    $redirect_url= $this->security->xss_clean($this->input->post('redirect_url'));
    $data2['loan_id'] = $this->security->xss_clean($this->input->post('loan_id'));
    $data2['delete_status'] = 1;

    $result2 = $this->Loan->update_loan($data2);
    $flash_data['status'] = $result2;
    if ($flash_data['status'] == 1) {
      $flash_data['flashdata_msg'] = 'Loan Deleted Successfully!.';
      $flash_data['flashdata_type'] = 'success';
      $flash_data['alert_type'] = 'success';
      $flash_data['flashdata_title'] = 'Success !';

    } else {
      $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
      $flash_data['flashdata_type'] = 'error';
      $flash_data['alert_type'] = 'danger';
      $flash_data['flashdata_title'] = 'Error !!';
    }
    echo json_encode($flash_data);
  }
  public function select_loans($page_data_type=""){

    $json_data=array();
    $j=0;
    $sl_no=0;
    $total_op_balance=$total_loan_amount=$total_paid_amount=$total_balance_amount=0;
    $data=array();
    if($this->config->item('user_data_access_view_all')!=1){
      $data['l.created_by'] = $this->session->userdata('user_id');
    }
    if(isset($_POST['work']) && $_POST['work']!='' && $_POST['work']!='all'){
      $data['l.work_id'] = $_POST['work'];
    }
    if(isset($_POST['loan_provider']) && $_POST['loan_provider']!='' && $_POST['loan_provider']!='all'){
      $data['l.provider_id'] = $_POST['loan_provider'];
    }
    if(isset($_POST['loan_purpose']) && $_POST['loan_purpose']!='' && $_POST['loan_purpose']!='all'){
      $data['l.work_id'] = $_POST['loan_purpose'];
    }
    if(isset($_POST['start_date']) && $_POST['start_date']!=''){
      $data["l.loan_date >="]= date('Y-m-d', strtotime($_POST['start_date']));
    }
    if(isset($_POST['end_date']) && $_POST['end_date']!=''){
      $data["l.loan_date <="]= date('Y-m-d', strtotime($_POST['end_date']));
    }
    if(isset($_POST['user_id']) && $_POST['user_id']!='' && $_POST['user_id']!='all'){
      $data['l.created_by'] = $_POST['user_id'];
    }
    if(isset($_POST['loan_type']) && $_POST['loan_type']!='' && $_POST['loan_type']!='all'){
      $data['l.loan_type'] = $_POST['loan_type'];
    }
    $entry_approval = $entry_approval_2 = 1;
    if($this->config->item('User_enable_data_entry_approval')==1){//webapp users approval
      $entry_approval = $entry_approval_2 = 'all';
    }
    if($page_data_type=='approval_entries'){
      $entry_approval = 'all';
      $data['u.user_role >'] =2;
      if(isset($_POST['approval_status']) && $_POST['approval_status']!='' && $_POST['approval_status']!='all'){
        $entry_approval = $_POST['approval_status'];
      }
    }
    if($page_data_type=='approval_entries_2_level'){
      $entry_approval_2 = 'all';
      $data['u.user_role >'] =2;
      $data['l.entry_approval_status'] =1;
      if(isset($_POST['approval_status']) && $_POST['approval_status']!='' && $_POST['approval_status']!='all'){
        $entry_approval_2 = $_POST['approval_status'];
      }
    }
    $result	= $this->Loan->select_loan("l.*,u.user_alias as created_user,ah1.acc_head_name,wc.work_name,lp.loan_provider_name,u.user_role as created_user_role_id",$data,$entry_approval,$entry_approval_2);
    $result_array=$result->result();

    $json_data['draw']=5;
    $json_data['recordsTotal']=$result->num_rows();
    $json_data['recordsFiltered']=$result->num_rows();
    $array=array();


    foreach($result_array as $row):
      if($page_data_type!='approval_entries' && $this->session->userdata('user_role')!='accounts_manager' && ($this->session->userdata('user_role')=='admin' || $this->session->userdata('user_role')=='general_manager' || $this->session->userdata('user_id')==$row->created_by) && ($this->config->item('User_enable_data_entry_approval')!=1 || $row->entry_approval_status!=1 || $this->session->userdata('user_role')=='admin')) {
        $btn_edit = '<a style="margin-left: 5px;margin-right: 5px" id="loan_edit_btn" href="#loan_edit_modal" data-toggle="modal" class="btn btn-info m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
        <i class="la la-edit"></i>
        </a>';
        $btn_delete='<a style="margin-left: 5px;margin-right: 5px" id="loan_delete_btn" href="#loan_delete_modal" data-toggle="modal" class="btn btn-danger m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
        <i class="la la-trash"></i>
        </a>';
      }else{
        $btn_edit = '';
        $btn_delete='';
        $btn_add_payment = '';
      }

      if($page_data_type!='approval_entries' && ($this->session->userdata('user_role')=='admin' || $this->session->userdata('user_role')=='general_manager' || $this->session->userdata('user_role')=='accounts_manager' || ($this->session->userdata('user_role')!='admin' && $this->session->userdata('user_id')==$row->created_by) || ($this->session->userdata('user_role')=='auditor' && $this->session->userdata('user_data_permission')['adding']==1))) {
        if($row->loan_type=='receivable'){
          $btn_add_payment = '<a style="margin-left: 5px;margin-right: 5px" data-bill-type="loan" id="btn_add_loan_receipt" href="#loan_receipt_add_modal" data-toggle="modal" class="btn btn-warning m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
          <i class="la la-plus-circle"></i>
          </a>';
        }else{
          $btn_add_payment = '<a style="margin-left: 5px;margin-right: 5px" data-bill-type="loan" id="btn_add_bill_payment" href="#bill_payment_add_modal" data-toggle="modal" class="btn btn-warning m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
          <i class="la la-plus-circle"></i>
          </a>';
        }
      }

      if($row->loan_type=='receivable'){
        $payment_data['ats.tr_type'] = 'loan_receipt_transaction';
      }else{
        $payment_data['ats.tr_type'] = 'loan_transaction';
      }
      $payment_data['l.loan_id'] = $row->loan_id;
      $payment_data['ats.reference_type'] = 'loan';
      $paid_amount = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_amount",$payment_data,'loan')->row()->total_amount;
      $balance_amount = $row->current_balance_payable-$paid_amount;
      $loan_purpose ='';
      if($row->loan_type=='payable'){
        if($row->work_id==0){
          $loan_purpose = 'For Whole Business';
        }else{
          $loan_purpose = 'For Project : '.$row->work_name;
        }
      }

      $loan_date = '';
      if($row->loan_date!='0000-00-00'){
        $loan_date = date('d-m-Y',strtotime($row->loan_date));
      }

      $btn_approve = $entry_approval_status = '';
      if(($this->session->userdata('user_role')=='admin' || ($this->session->userdata('user_role')=='accounts_manager' && $row->created_user_role_id>2 && (($this->config->item('User_enable_data_entry_approval_2_level')==0 && $row->created_user_role_id != 16) || $this->config->item('User_enable_data_entry_approval_2_level')==1))) && $page_data_type=='approval_entries' && $this->config->item('Mobile_App_enable_data_entry_approval')==1){
        if($this->config->item('User_enable_data_entry_approval_2_level')==0 || ($this->config->item('User_enable_data_entry_approval_2_level')==1 && $row->entry_approval_status_2 == 0)){
          $btn_approve = '<a style="margin-left: 5px;margin-right: 5px" data-type="loan" data-approval-status="'.$row->entry_approval_status.'" data-id="'.$row->loan_id.'" id="btn_data_entry_approval" href="#data_entry_approve_modal" data-toggle="modal" class="btn btn-sm btn-warning m-btn m-btn--icon  m-btn--pill m-btn--air">
          <i class="la la-check-circle"></i> / <i class="la la-times-circle"></i>
          </a>';
        }
      }
      if($this->config->item('User_enable_data_entry_approval_2_level')==1 && $this->session->userdata('user_role')=='admin' && $page_data_type=='approval_entries_2_level'){
        $btn_approve = '<a style="margin-left: 5px;margin-right: 5px" data-type="loan" data-approval-status="'.$row->entry_approval_status_2.'" data-id="'.$row->loan_id.'" id="btn_data_entry_approval" href="#data_entry_approve_modal" data-toggle="modal" class="btn btn-sm btn-warning m-btn m-btn--icon  m-btn--pill m-btn--air">
        <i class="la la-check-circle"></i> / <i class="la la-times-circle"></i>
        </a>';
      }
      if(($page_data_type=='approval_entries' && $this->config->item('Mobile_App_enable_data_entry_approval')==1) || $this->config->item('User_enable_data_entry_approval')==1){
        $level='';
        if($this->config->item('User_enable_data_entry_approval_2_level')==1){
          $level='1st Level ';
        }
        if($row->entry_approval_status==1){
          $entry_approval_status="<br/><span class='m-badge m-badge--success m-badge--wide'><i class='fa fa-check'></i> ".$level."Approved</span>";
        }elseif($row->entry_approval_status==2){
          $entry_approval_status="<br/><span class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-check'></i> ".$level."Rejected</span>";
        }else{
          $entry_approval_status="<br/><span class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-times-circle'></i> ".$level."Pending</span>";
        }
        if($this->config->item('User_enable_data_entry_approval_2_level')==1 && $row->entry_approval_status == 1){
          if ($row->entry_approval_status_2 == 1) {
            $entry_approval_status .= "<br/><span style='margin-top:5px' class='m-badge m-badge--success m-badge--wide'><i class='fa fa-check'></i> 2nd Level Approved</span>";
          } elseif ($row->entry_approval_status_2 == 2) {
            $entry_approval_status .= "<br/><span style='margin-top:5px' class='m-badge m-badge--danger m-badge--wide'><i class='fa fa-check'></i> 2nd Level Rejected</span>";
          } else {
            $entry_approval_status .= "<br/><span style='margin-top:5px' class='m-badge m-badge--warning m-badge--wide'><i class='fa fa-times-circle'></i> 2nd Level Pending</span>";
          }
        }
      }
      $loan_title = $row->loan_title;
      if($page_data_type=='approval_entries'){
        $loan_title.="<br/>(".ucwords($row->loan_type)." Loan)";
      }

      $sl_no++;
      $array[$j][] = $sl_no;
      $array[$j][] = $row->loan_id;
      $array[$j][] = $loan_title;
      $array[$j][] = $row->description;
      $array[$j][] = $loan_date;
      $array[$j][] = '<a href="'.base_url().'loans/provider/profile/'.$row->provider_id.'" target="_blank">'.$row->loan_provider_name.'</a>';
      $array[$j][] = number_format($row->total_loan_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
      $array[$j][] = number_format($row->op_balance,$this->config->item('Currency_amount_decimals_2'),'.','');
      $array[$j][] = $this->config->item('currency_format')->formatCurrency($row->current_balance_payable,$this->config->item('Currency_currency_shortname'));
      $array[$j][] = $row->acc_head_name;
      $array[$j][] = number_format($paid_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
      $array[$j][] = number_format($balance_amount,$this->config->item('Currency_amount_decimals_2'),'.','');
      $array[$j][] = $loan_purpose;
      if ($this->config->item('UI_hide_created_date_field')==0){
        $array[$j][]='<ul style="padding: .75rem;margin-bottom: 0"><li>Created on : '.date('d-m-Y',strtotime($row->created_date))."</li><li>Created By : ".$row->created_user."</li>".$entry_approval_status;
      }else{
        $array[$j][]='<ul style="padding: .75rem;margin-bottom: 0"><li>Created By : '.$row->created_user.'</li>'.$entry_approval_status;
      }
      $array[$j][] = $btn_add_payment.$btn_edit.$btn_delete.$btn_approve;
      $array[$j][] = $row->credit_ac;
      $array[$j][] = $row->work_id;
      $array[$j][] = $row->provider_id;
      $array[$j][] = $row->entry_approval_status;
      $array[$j][] = $row->entry_approval_status_2;

      $total_loan_amount+=$row->total_loan_amount;
      $total_op_balance+=$row->op_balance;
      $total_paid_amount+=$paid_amount;
      $total_balance_amount+=$balance_amount;

      $j++;
    endforeach;
    if($result->num_rows()>0){
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]="<strong>Total</strong>";
      $array[$j][]="<strong>".$total_loan_amount."</strong>";
      $array[$j][]="<strong>".$total_op_balance."</strong>";
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]="<strong>".$total_paid_amount."</strong>";
      $array[$j][]="<strong>".$total_balance_amount."</strong>";
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][] = '';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
      $array[$j][]='';
    }

    $json_data['data']=$array;
    echo json_encode($json_data);  // send data as json format
  }
  public function create_provider()
  {
    $redirect_url= $this->security->xss_clean($this->input->post('redirect_url'));
    $data['loan_provider_name'] = $this->security->xss_clean($this->input->post('name'));
    $provider_data = $this->Loan->select_loan_provider("",array("loan_provider_name"=>$data['loan_provider_name']));
    if($provider_data->num_rows()==0){
      $result = $this->Loan->create_loan_provider($data);
      $flash_data['status'] = $result['status'];
      if ($flash_data['status'] == 1) {
        $flash_data['flashdata_msg'] = 'Loan Provider Added Successfully!.';
        $flash_data['flashdata_type'] = 'success';
        $flash_data['alert_type'] = 'success';
        $flash_data['flashdata_title'] = 'Success !';
      }else {
        $flash_data['flashdata_msg'] = 'Sorry.. There Have been Some Error Occurred. Please Try Again!';
        $flash_data['flashdata_type'] = 'error';
        $flash_data['alert_type'] = 'danger';
        $flash_data['flashdata_title'] = 'Error !!';
      }
    }else {
      $flash_data['flashdata_msg'] = 'Sorry.. Loan Provider with Same Name Already Exist!';
      $flash_data['flashdata_type'] = 'warning';
      $flash_data['alert_type'] = 'warning';
      $flash_data['flashdata_title'] = 'Already Exist !!';
    }

    echo json_encode($flash_data);
  }
  public function select_provider(){
    $data = array();
    $result = $this->Loan->select_loan_provider("",$data);
    if($result->num_rows()>0) {
      echo json_encode(array("count" => $result->num_rows(),"data" => $result->result()));
    }else{
      echo json_encode(array("count" => $result->num_rows()));
    }
  }
  public function select_provider_summary(){
    $data = array();
    if(isset($_POST['loan_provider_id']) && $_POST['loan_provider_id']!='' && $_POST['loan_provider_id']!='all'){
      $data['loan_provider_id'] = $_POST['loan_provider_id'];
    }
    $result = $this->Loan->select_loan_provider("",$data);
    if($result->num_rows()==1) {

      $payable_payment_data['l.provider_id'] = $result->row()->loan_provider_id;
      $payable_payment_data['ats.tr_type'] = 'loan_transaction';
      $payable_payment_data['ats.reference_type'] = 'loan';
      $payable_payment_data['l.loan_type'] = 'payable';
      $payable_paid_amount = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_amount",$payable_payment_data,'loan')->row()->total_amount;

      $payable_loan_data_where['l.loan_type'] = 'payable';
      $payable_loan_data_where['l.provider_id'] = $result->row()->loan_provider_id;
      $payable_loan_data = $this->Loan->select_loan("COALESCE(SUM(l.total_loan_amount),0) as total_loan_amount,COALESCE(SUM(l.current_balance_payable),0) as current_balance_payable,COALESCE(SUM(l.op_balance),0) as total_op_balance",$payable_loan_data_where)->row();

      $receivable_payment_data['l.provider_id'] = $result->row()->loan_provider_id;
      $receivable_payment_data['ats.tr_type'] = 'loan_receipt_transaction';
      $receivable_payment_data['ats.reference_type'] = 'loan';
      $receivable_payment_data['l.loan_type'] = 'receivable';
      $receivable_received_amount = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_amount",$receivable_payment_data,'loan')->row()->total_amount;

      $receivable_loan_data_where['l.loan_type'] = 'receivable';
      $receivable_loan_data_where['l.provider_id'] = $result->row()->loan_provider_id;
      $receivable_loan_data = $this->Loan->select_loan("COALESCE(SUM(l.total_loan_amount),0) as total_loan_amount,COALESCE(SUM(l.current_balance_payable),0) as current_balance_payable,COALESCE(SUM(l.op_balance),0) as total_op_balance",$receivable_loan_data_where)->row();

      $json_data['count'] = 1;
      $json_data['total_payable_loan_amount'] = $this->config->item('currency_format')->formatCurrency($payable_loan_data->total_loan_amount,$this->config->item('Currency_currency_shortname'));
      $json_data['total_op_balance_payable'] = $this->config->item('currency_format')->formatCurrency($payable_loan_data->total_op_balance,$this->config->item('Currency_currency_shortname'));
      $json_data['total_paid'] = $this->config->item('currency_format')->formatCurrency($payable_paid_amount,$this->config->item('Currency_currency_shortname'));
      $json_data['balance_to_pay'] = $this->config->item('currency_format')->formatCurrency(($payable_loan_data->current_balance_payable-$payable_paid_amount),$this->config->item('Currency_currency_shortname'));

      $json_data['total_receivable_loan_amount'] = $this->config->item('currency_format')->formatCurrency($receivable_loan_data->total_loan_amount,$this->config->item('Currency_currency_shortname'));
      $json_data['total_op_balance_receivable'] = $this->config->item('currency_format')->formatCurrency($receivable_loan_data->total_op_balance,$this->config->item('Currency_currency_shortname'));
      $json_data['total_received'] = $this->config->item('currency_format')->formatCurrency($receivable_received_amount,$this->config->item('Currency_currency_shortname'));
      $json_data['balance_to_receive'] = $this->config->item('currency_format')->formatCurrency(($receivable_loan_data->current_balance_payable-$receivable_received_amount),$this->config->item('Currency_currency_shortname'));

      echo json_encode($json_data);
    }else{
      echo json_encode(array("count" => $result->num_rows()));
    }
  }
  public function select_loan_providers(){


    $json_data=array();
    $j=0;
    $sl_no=0;
    $total_op_balance=$total_loan_amount=$total_paid_amount=$total_balance_amount=0;
    $data=array();
    $result	= $this->Loan->select_loan_provider("",$data);
    $result_array=$result->result();

    $json_data['draw']=5;
    $json_data['recordsTotal']=$result->num_rows();
    $json_data['recordsFiltered']=$result->num_rows();
    $array=array();


    foreach($result_array as $row):
      $btn_add_payment = '';
      if($this->session->userdata('user_role')=='admin') {
        $btn_add_payment = '<a style="margin-left: 5px;margin-right: 5px" data-bill-type="loan" id="btn_add_bill_payment" href="#bill_payment_add_modal" data-toggle="modal" class="btn btn-warning m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
        <i class="la la-plus-circle"></i>
        </a>';
      }

      $payment_data['l.provider_id'] = $row->loan_provider_id;
      if(isset($_POST['loan_type']) && $_POST['loan_type']!=''){
        $payment_data['l.loan_type'] = $_POST['loan_type'];
      }
      if(isset($_POST['loan_type']) && $_POST['loan_type']=='receivable'){
        $payment_data['ats.tr_type'] = "loan_receipt_transaction";
      }else{
        $payment_data['ats.tr_type'] = 'loan_transaction';
      }
      $payment_data['ats.reference_type'] = 'loan';
      $paid_amount = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_amount",$payment_data,'loan')->row()->total_amount;

      $loan_data_where['l.provider_id'] = $row->loan_provider_id;
      if(isset($_POST['loan_type']) && $_POST['loan_type']!=''){
        $loan_data_where['l.loan_type'] = $_POST['loan_type'];
      }
      $loan_data = $this->Loan->select_loan("COALESCE(SUM(l.total_loan_amount),0) as total_loan_amount,COALESCE(SUM(l.current_balance_payable),0) as current_balance_payable,COALESCE(SUM(l.op_balance),0) as total_op_balance",$loan_data_where)->row();

      $balance_amount = $loan_data->current_balance_payable-$paid_amount;
      $array[$j][] = $row->loan_provider_id;
      $array[$j][] = '<a href="'.base_url().'loans/provider/profile/'.$row->loan_provider_id.'" target="_blank">'.$row->loan_provider_name.'</a>';
      $array[$j][] = $this->config->item('currency_format')->formatCurrency($loan_data->total_loan_amount,$this->config->item('Currency_currency_shortname'));
      $array[$j][] = $this->config->item('currency_format')->formatCurrency($loan_data->total_op_balance,$this->config->item('Currency_currency_shortname'));
      $array[$j][] = $this->config->item('currency_format')->formatCurrency($loan_data->current_balance_payable,$this->config->item('Currency_currency_shortname'));
      $array[$j][] = $this->config->item('currency_format')->formatCurrency($paid_amount,$this->config->item('Currency_currency_shortname'));
      $array[$j][] = $this->config->item('currency_format')->formatCurrency($balance_amount,$this->config->item('Currency_currency_shortname'));

      $total_loan_amount+=$loan_data->total_loan_amount;
      $total_op_balance+=$loan_data->total_op_balance;
      $total_paid_amount+=$paid_amount;
      $total_balance_amount+=$balance_amount;


      $j++;
    endforeach;
    if($result->num_rows()>0){
      $array[$j][]='';
      $array[$j][]="<strong>Total</strong>";
      $array[$j][]="<strong>".$total_loan_amount."</strong>";
      $array[$j][]="<strong>".$total_op_balance."</strong>";
      $array[$j][] = '';
      $array[$j][]="<strong>".$total_paid_amount."</strong>";
      $array[$j][]="<strong>".$total_balance_amount."</strong>";
    }

    $json_data['data']=$array;
    echo json_encode($json_data);  // send data as json format
  }
}
?>
