<?php

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

class Cash_Balance extends CI_Controller {

    var $main_menu_name = "finance";
    var $sub_menu_name = "cash_balance";

    public function __construct() {
        parent::__construct();

        $this->load->model('Cash_Balance_Model');
       // $this->load->model('Supplier_Model');
        $this->load->model('Warehouse_Model');
        $this->load->model('Common_Model');
       $this->load->model('Transactions_Model');
        $this->load->model('Sales_Model');
//        $this->load->model('Sales_Return_Model');
//        $this->load->model('User_Model');
//        $this->load->model('Transfer_Model');
//        $this->load->model('Purchases_Model');
//        $this->load->model('Product_Damage_Model');
        //$this->load->model('Purchases_Model');
    }

    //Sales list page load
    public function index() {

//		$data['sales'] = $this->Sales_Model->get_all_sales('','','');
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name'] = $this->sub_menu_name;
		
		$srh_warehouse_id 	= $this->session->userdata('ss_warehouse_id');
		$srh_to_date		= date("Y-m-d 23:59:59");
		$srh_from_date		= date("Y-m-d 00:00:00");
		$srh_type			= '';
		$srh_payment_term	= 'Cash';
		$ss_user_id			= $this->session->userdata('ss_user_id');
		$srh_customer_id	= '';
		
		//echo $srh_to_date;
		
		$data['sale_cash_total']=$this->Cash_Balance_Model->get_cash_totals($srh_warehouse_id,$srh_to_date,$srh_from_date,'sale',$srh_payment_term,$ss_user_id,$srh_customer_id);
        $data['service_cash_total']=$this->Cash_Balance_Model->get_cash_totals($srh_warehouse_id,$srh_to_date,$srh_from_date,'service',$srh_payment_term,$ss_user_id,$srh_customer_id);
		$data['sale_return_cash_total']=$this->Cash_Balance_Model->get_cash_totals($srh_warehouse_id,$srh_to_date,$srh_from_date,'sale','Return_Cash',$ss_user_id,$srh_customer_id);
		$this->load->view('cash_balance', $data);
    }
	
	
    public function save_cash_balance() {
        
		$count_warehouse_id =		$this->session->userdata('ss_warehouse_id');// $this->input->post('warehouse_id');
        $warehouse_code = $this->Warehouse_Model->get_warehouse_info($count_warehouse_id);
        
        
        
        //update shift status
        $ss_user_id=$this->session->userdata('ss_user_id');
		$shift_date=date("Y-m-d");
		  $cash_in_hand = $this->input->post('cash_in_hand');
		$active_shift_des=$this->Common_Model->get_active_shift_by_user_id_date($ss_user_id,$shift_date);
		
		//print_r($this->input->post());
		
		//print_r($active_shift_des);
		if(count($active_shift_des)){
		    $acctrnss_id=$active_shift_des['acctrnss_id'];
		    $shift_status=0;
			    $data=array(
				'shift_end_datetime'=>date("Y-m-d H:i:s"),	
				'shift_status'=>$shift_status,
				'cash_in_hand'=>$cash_in_hand,
				'count_5000' => $this->input->post('count_5000'),
				'count_1000' => $this->input->post('count_1000'),
				'count_500' => $this->input->post('count_500'),
				'count_100' => $this->input->post('count_100'),
				'count_50' => $this->input->post('count_50'),
				'count_20' => $this->input->post('count_20'),
				'count_10' => $this->input->post('count_10'),
				'count_10_c' => $this->input->post('count_10_c'),
				'count_5' => $this->input->post('count_5'),
				'count_2' => $this->input->post('count_2'),
				'count_1' => $this->input->post('count_1'),
				'cheque_amount' => $this->input->post('cheque_amount'),
				'mc_amount' => $this->input->post('mc_amount'),
				'vc_amount' => $this->input->post('vc_amount'),
				'bank_deposit'=> $this->input->post('bank_deposit'),
					'cash_in'=> $this->input->post('cash_in'),
			);
			
			//print_r($data);
		//	echo "acctrnss_id:$acctrnss_id";
			$_insert=$this->Transactions_Model->save_transactions($data,$acctrnss_id);
		//	echo $this->db->last_query();
			
		}
        
        
        //end update shift status
        
/*
		$count_date = date('Y-m-d');
        $count_user_id = $this->input->post('count_user_id');
		$count_5000 = $this->input->post('count-5000');
		$count_1000 = $this->input->post('count-1000');
		$count_500 = $this->input->post('count-500');
		$count_100 = $this->input->post('count-100');
		$count_50 = $this->input->post('count-50');
		$count_20 = $this->input->post('count-20');
		$count_10 = $this->input->post('count-10');
		$count_10_c = $this->input->post('count-10-c');
		$count_5_c = $this->input->post('count-5-c');
		$count_2_c = $this->input->post('count-2-c');
		$count_1_c = $this->input->post('count-1-c');
*/

		$error = 0;
/*
echo "<pre>";
print_r($cash_count['count-5000'] );
echo "</pre>";
*/
        if (!$error) {
            $data = array(
				'count_warehouse_id'=>	$count_warehouse_id,
                'count_date'	=>	$this->input->post('srh_from_date'),
                'count_user_id' => $this->session->userdata('ss_user_id'),
				'cash_total_amount' =>$this->input->post('cash_in_hand'),
                'count-5000' => $this->input->post('count-5000'),
                'count-1000' => $this->input->post('count-1000'),
                'count-500' => $this->input->post('count-500'),
                'count-100' => $this->input->post('count-100'),
                'count-50' => $this->input->post('count-50'),
                'count-20' => $this->input->post('count-20'),
                'count-10' => $this->input->post('count-10'),
                'count-10-c' => $this->input->post('count-10-c'),
                'count-5-c' => $this->input->post('count-5-c'),
                'count-2-c' => $this->input->post('count-2-c'),
                'count-1-c' => $this->input->post('count-1-c'),
                'count_notes' => $this->input->post('count_notes')
            );
		//	print_r($this->session->userdata('cash_in_hand'));
           // $_insert = $this->Cash_Balance_Model->save_cash_balance($data);
           // $lastid = $this->db->insert_id();
           // $sale_id = $lastid;
            //insert user activity
           // $this->Common_Model->add_user_activitie("Added Cash Balance sheet, (Record_ID No:$sale_id)");
            $disMsg = 'Balance Sheet successfully added';

        } else {

            $disMsg = 'Please select these before adding any product:' . $disMsg;
        }

        $this->session->set_flashdata('message', 'Balance sheet successfully added!');
        $lastid=$acctrnss_id;
        echo json_encode(array('lastid' => $lastid, 'error' => $error, 'disMsg' => $disMsg,));
    }


    public function sale_items() {

//        $data['sales'] = $this->Sales_Model->get_all_sales();
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name'] = 'sale_items';
        if ($this->session->userdata('ss_group_id') < 3)
            $this->load->view('sales_items', $data);
        else
            show_404();
    }

    

    //Sales details view
    public function view() {
		
			$data['main_menu_name'] = $this->main_menu_name;
			$data['sub_menu_name'] = '';
	
			//get sale id
			$count_id = $this->uri->segment('3');
			$data['cash_count'] = $this->Cash_Balance_Model->get_counts_info($count_id);
			if($data['cash_count']){
				$data['warehouse_details'] = $this->Warehouse_Model->get_warehouse_info($data['cash_count']['count_warehouse_id']);
				$data['count_id'] = $count_id;
				$this->load->view('count_view', $data);
			} else
				show_404();
		
				
	} 
			
    



    /*//Sale details page
    public function sale_details() {
        $sale_type = 0;
        $sale_id = $this->input->get('sale_id');
        $sale_type = $this->input->get('type');

        $data['sale_details'] = $this->Sales_Model->get_sale_info($sale_id);
        $data['sale_type'] = $sale_type;
        //get sale item list
        $data['sale_item_list'] = $this->Sales_Model->get_sale_item_list_by_sale_id($sale_id);

        $data['customer_details'] = $this->Customer_Model->get_customer_info($data['sale_details']['customer_id']);
        $data['warehouse_details'] = $this->Warehouse_Model->get_warehouse_info($data['sale_details']['warehouse_id']);
        $data['sale_payments_list'] = $this->Sales_Model->get_sale_payments_by_sale_id($sale_id);

        if ($data['sale_details']['customer_id'] != 1)
            $data['total_sales'] = $this->Sales_Model->get_all_sales_for_view($data['sale_details']['warehouse_id'], $data['sale_details']['customer_id']);
        if ($data['sale_details']['customer_id'] != 1)
            $data['total_return'] = $this->Sales_Model->get_all_sales_return_for_view($data['sale_details']['warehouse_id'], '', '', $data['sale_details']['customer_id']);

        $data['total_payments'] = $this->Sales_Model->getPaymentsForView($data['sale_details']['warehouse_id'], '', '', 'sale', 'Return_Cash', '', $data['sale_details']['customer_id']);

        //get old payments amounts
        if ($data['sale_details']['customer_id'] != 1)
            $cus_sales_details = $this->Sales_Model->get_sale_info_by_customer_id($data['sale_details']['customer_id']);
        //print_r($cus_sales_details);
        $old_payment_tot = 0;
        $retured_payment_tot = 0;
        $retured_payment_msg_this = '';
        $old_payments_dis_msg_this = '';

        if ($data['sale_details']['customer_id'] != 1)
            foreach ($cus_sales_details as $row) {
                //echo "sale id:$row->sale_id";
                //echo "sale_total:$row->sale_total";
                if ($row->sale_id != $sale_id) {
                    //get paid amount
                    $paid_amount = $this->Sales_Model->get_total_paid_by_sale_id($row->sale_id);
                    if ($row->sale_total != $paid_amount) {
                        //$this_balance_pament=$row->sale_total-$paid_amount;
                        //$old_payment_tot=$old_payment_tot+$this_balance_pament;
                        //echo "sale_total:$row->sale_total , ";
                        //$old_payments_dis_msg_this=$old_payments_dis_msg_this.''.$this_balance_pament.' ,';
                    }
                }
            }

        //check return payments
        if ($data['sale_details']['customer_id'] != 1)
            $return_sales_details = $this->Sales_Return_Model->get_return_sale_info_sale_id($sale_id);

        if ($data['sale_details']['customer_id'] != 1)
            foreach ($return_sales_details as $row) {
                //echo "sale id:$row->sale_id";
                //echo "sale_total:$row->sale_total";

                $this_balance_pament = 0;
                $this_trn_amt = $row->sl_rtn_total;
                $retured_payment_tot = $retured_payment_tot + $this_trn_amt;

                $retured_payment_msg_this = $retured_payment_msg_this . ' -' . $this_trn_amt . ' ,';
            }


        $old_payment_tot = $old_payment_tot - $retured_payment_tot;

        $data['old_payments'] = $old_payment_tot;
        $data['old_payments_dis_msg'] = "Return Total Amount ($old_payments_dis_msg_this $retured_payment_msg_this)";


        $data['cr_limit_list'] = $this->Common_Model->get_all_cr_limit();
        $this->load->view('models/view_sales', $data);
    }

    //Sales list
    public function list_sales() {
        $requestData = $_REQUEST;

        $columns = array(
            0 => 'sale_id',
            1 => 'sale_reference_no',
            2 => 'sale_id',
            3 => 'sale_id',
            4 => 'sale_id',
            5 => 'sale_id'
        );

        $data = array();

        $search_key = $this->input->get('search');
        $search_key_val = $search_key['value'];
        $start = $this->input->get('start');
        $length = $this->input->get('length');
		$string = $this->input->get('string');

		$sales = '';//$this->Sales_Model->get_all_sales($start, $length, $search_key_val);
       // $sales_count = $this->Sales_Model->get_all_sales('', '', '');

        $totalData = 0;

        if ($search_key_val) {
			$sales = $this->Sales_Model->get_all_sales($start, $length, $search_key_val,$string);
            $sales_c = $this->Sales_Model->get_all_sales('', '', $search_key_val,$string);
            $totalData = count($sales_c);
        } else{
			$sales = $this->Sales_Model->get_all_sales($start, $length, '',$string);
        	$sales_c = $this->Sales_Model->get_all_sales_c('','', '');
			$sales_c = $sales_c[0]['count_s'];
            $totalData = $sales_c;
		}

        $totalFiltered = $totalData;
        $style = '';
        if ($this->session->userdata('ss_group_id') == 3) {
            $style = 'display:none';
        }
		if(!empty($sales)){
        foreach ($sales as $row) {
            $nestedData = array();
            $sale_id = $row['sale_id'];
            $total_paid_amount = 0;
            $total_paid_amount = $this->Sales_Model->get_total_paid_by_sale_id($sale_id);
            $return_tot_amt = 0;

            $to_be_paid = $row['sale_total'] - $return_tot_amt;
            $nestedData[] = $row['sale_id'];
            $nestedData[] = display_date_time_format($row['sale_datetime']);
            $nestedData[] = $row['sale_reference_no'];
            $nestedData[] = $row['cus_name'];
            $nestedData[] = $row['sale_total'];
            $nestedData[] = $row['sale_total'] - $total_paid_amount;
            $nestedData[] = $total_paid_amount;

            if (empty($total_paid_amount)) {
                $pay_st = '<span class="label label-warning">Pending</span>';
            } else {
                if ($total_paid_amount >= $to_be_paid) {
                    $pay_st = '<span class="label label-success">Paid</span>';
                } else {
                    $pay_st = '<span class="label label-info">Partial</span>';
                }
            }

            $nestedData[] = $pay_st;



            $actionTxtDisble = '';
            $actionTxtEnable = '';
            $actionTxtUpdate = '';
            $actionTxtDelete = '';

            $url = base_url("sales/sale_details?sale_id=$sale_id");
            $actionTxtUpdate = '<a onClick="fbs_click(' . $row['sale_id'] . ')" data-toggle="modal" href="#" class="btn btn-xs btn-blue tooltips" data-placement="top" data-original-title="Edit suppliers"><i class="clip-zoom-in-2"></i></a> &nbsp;';

            $actionTxtViewDetails = '<a href="' . base_url() . 'sales/view/' . $sale_id . '" class="btn btn-xs btn-blue tooltips" data-placement="top" data-original-title="Edit suppliers"><i class="fa fa-file-text-o"></i></a> &nbsp;';

            $nestedData[] = '<div class="btn-group text-left">
                            <button data-toggle="dropdown" class="btn btn-default btn-xs btn-primary dropdown-toggle" type="button">Actions <span class="caret"></span></button>
                            <ul role="menu" class="dropdown-menu pull-right">
                            <li><a href="' . base_url() . 'sales/view/' . $sale_id . '"><i class="fa fa-file-text-o"></i> Sale Details</a></li>
                            <li><a onClick="fbs_click(' . $row['sale_id'] . ')" data-toggle="modal" href="#" data-placement="top" data-original-title="Edit suppliers"><i class="fa fa-print"></i> Print Sale</a></li>
							 
							 <!--<li><a href="' . base_url() . 'sales_return/sales_return_add/' . $sale_id . '"><i class="fa fa-angle-double-left"></i></i> Return Sale</a></li>-->
							 <li style="' . $style . '"><a href="#" onClick ="delete_invoice(' . $sale_id . ')"><i class="fa fa-trash-o"></i></i> Delete Invoice</a></li>					
							 <li style="' . $style . '"><a href="#" onClick ="delete_payments(' . $sale_id . ')"><i class="fa fa-trash-o"></i>    Delete Payments</a></li>
                            </ul></div>';

            $data[] = $nestedData;
        }

        $json_data = array(
            //"draw"            => intval( $requestData['draw'] ),  
            "recordsTotal" => intval($totalData),
            "recordsFiltered" => intval($totalFiltered),
            "data" => $data
        );
		
		

        echo json_encode($json_data);
		}else{
				$json_data = array(
					"recordsTotal" => '',
					"recordsFiltered" => '',
					"data" => ''
				);

        echo json_encode($json_data);
			}
    }

    public function sales_delete() {

        $sale_id = $this->input->get('sale_id');

        $result = $this->Sales_Model->delete_sales($sale_id);

        return $result;
    }
	
	function price_filter($amount='')
		{
			$s = explode("Rs.",$amount);
			return str_replace(',', '', $s[1]);
		}
		
	public function demo(){
		$pw = $this->input->get('pw');
		$data['pw']= $pw;
		$this->load->view('demo');
		}*/
	
	function get_drawer_cash_total(){
			$date	= $this->input->post('srh_from_date');
			$drawer_cash_total	=$this->Cash_Balance_Model->get_drawer_cash_total($date);
			//print_r($drawer_cash_total);
			echo json_encode(
				array(
				'drawer_cash_total' => $drawer_cash_total['cash_total_amount'],
				'count_5000' => $drawer_cash_total['count-5000'],
				'count_1000' => $drawer_cash_total['count-1000'],
				'count_500' => $drawer_cash_total['count-500'],
				'count_100' => $drawer_cash_total['count-100'],
				'count_50' => $drawer_cash_total['count-50'],
				'count_20' => $drawer_cash_total['count-20'],
				'count_10' => $drawer_cash_total['count-10'],
				'count_10c' => $drawer_cash_total['count-10-c']
				
				)
			);
		}
}