<?php
defined('BASEPATH') OR exit('No direct script access allowed');
date_default_timezone_set('Asia/Kolkata');

class Admin extends CI_Controller {
    
    public function __construct()
    {
        parent::__construct();
        
        $this->load->library('session');
        
        $this->load->library('excel');
        $this->load->library('form_validation');
        $this->load->helper('form');
        $this->load->helper('url');
        $this->load->helper('html');
        $this->load->helper('sms');
        $this->load->model('admin_db');   
        
        $action_method = $this->router->fetch_method();
        if(!is_numeric($this->session->userdata('admin_id')) &&  !($action_method=='index' || $action_method=='admin_login')){
            redirect(base_url());
            exit;
        }
        
    }

    public function index()
    {
        $this->load->view('login/header');
        $this->load->view('login/index');
        $this->load->view('login/footer');
    }

    public function admin_login()
    {   
        $username = $this->input->post('username');
        $password = $this->input->post('password');
        
        $result = $this->admin_db->admin_login($username, $password);
        
        header('Content-Type: application/json');
        
        if ($result) {

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

            if ($this->agent->is_browser()) {
                $agent = $this->agent->browser() . ' ' . $this->agent->version();
            } elseif ($this->agent->is_robot()) {
                $agent = $this->agent->robot();
            } elseif ($this->agent->is_mobile()) {
                $agent = $this->agent->mobile();
            } else {
                $agent = 'Unidentified User Agent';
            }

            $this->admin_db->save_admin_user_log($agent, $this->agent->platform());
            
            $newdata = array('admin_login_time' => time());
            $this->session->set_userdata($newdata);
            
            $user_type = $this->session->userdata('user_type_id');
            echo json_encode(array("status" => "1", "user_type" => $user_type));
            exit;
        }else{
            echo json_encode(array("status" => "2"));
            exit;
        }
        
    }

    public function admin_logout()
    {
        //after admin is signout from the account
        $this->admin_db->log_out();
        $this->clear_cache();
        session_destroy();
        redirect(base_url());
    }

    public function clear_cache()
    {
        //clear cache
        $this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate, no-transform, max-age=0, post-check=0, pre-check=0");
        $this->output->set_header("Pragma: no-cache");
    }

    public function dashboard()
    {
        $data['title'] = 'Dashboard';
        
        $data['system_date'] = $system_date = date('Y-m-d');
        
        $data['stock_details'] = $this->admin_db->get_stock_details();
        $data['dxb_bank_balances'] = $this->admin_db->get_dxb_cash_at_bank();
        $data['box_bank_balances'] = $this->admin_db->get_box_cash_at_bank();
        $data['tot_sales'] = $this->admin_db->get_total_sales();
        $data['rate_details'] = $this->admin_db->get_rate_details();
        
//        $data['new_customers'] = $this->admin_db->get_latest_customers(10);
//        
//        $statuses = [2, 3];
//        $data['new_debtors'] = $this->admin_db->get_latest_debtors(10, $statuses);
//        $data['all_sales'] = $this->admin_db->get_latest_sales_by_status(10, null);
//        $data['pending_sales'] = $this->admin_db->get_latest_sales_by_status(10, 3);
//        $data['incomplete_sales'] = $this->admin_db->get_latest_sales_by_status(10, 2);
//        $data['completed_sales'] = $this->admin_db->get_latest_sales_by_status(10, 1);
        
        $one_week = date('Y-m-d',strtotime($system_date . "+7 days"));
        $two_weeks = date('Y-m-d',strtotime($system_date . "+14 days"));
        $four_weeks = date('Y-m-d',strtotime($system_date . "+28 days"));

        $data['one_week_cheques'] = $this->admin_db->get_pending_cheque_amount_within($system_date, $one_week);
        $data['two_week_cheques'] = $this->admin_db->get_pending_cheque_amount_within($one_week, $two_weeks);
        $data['four_week_cheques'] = $this->admin_db->get_pending_cheque_amount_within($two_weeks, $four_weeks);
        $data['more_than_four_week_cheques'] = $this->admin_db->get_pending_cheque_amount_more_than($four_weeks);
                        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/dashboard', $data);
        $this->load->view('dashboard/footer');
    }

    public function director_dashboard()
    {
        $data['title'] = 'Dashboard';
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/director_dashboard', $data);
        $this->load->view('dashboard/footer');
    }

    public function user_privileges()
    {
        $data['title'] = 'User Privileges';
        
        $data['active'] = "active";
        $data['inactive'] = "";
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/user_privileges', $data);
        $this->load->view('dashboard/footer');
    }

    public function user_module_privileges()
    {
        $data['title'] = 'User Module Privileges';
        
        $data['user_privileges'] = $this->admin_db->get_all_privileges();
                
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/user_module_privileges', $data);
        $this->load->view('dashboard/footer');
    }

    function admin_module_update() {
        //module state update
        $privilege = $this->input->post('privilege');
        $privilage_name= $this->input->post('privilage_name');
        $title = $this->input->post('title');
        $module_id = $this->input->post('module_id');
        $check = $this->input->post('check');

        if ($check == 1) {
            $on_off = "On";
        } else {
            $on_off = "Off";
        }

        $update = $this->admin_db->update_admin_module_status($privilege, $module_id, $check);
        if ($update) {
            echo '<p>' . $title . ' Module is ' . $on_off . ' for ' . $privilage_name . '</p>';
            $this->session->set_flashdata('msg', '<p>' . $title . ' Module is ' . $on_off . ' for ' . $privilage_name . '</p>');
        } else {
            echo '<p>Somthing went wrong when updating Module status</p>';
            $this->session->set_flashdata('msg', '<p>Somthing went wrong when updating Module status</p>');
        }
    }

    public function change_user_privilege_status()
    {
        $id = $this->input->get('id');
        $status = $this->input->get('status');
        
        $this->admin_db->change_user_privilege_status($id, $status);
        
        // 1 - active, 2 - inactive
        if ($status == 2) {

            $data['success_msg'] = 'User Privilege Inactivated';
            $data['inactive'] = "active";
            $data['active'] = "";
            
        } else if ($status == 1) {

            $data['success_msg'] = 'User Privilege Activated';
            $data['active'] = "active";
            $data['inactive'] = "";
        }

        $data['title'] = 'User Privileges';
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/user_privileges', $data);
        $this->load->view('dashboard/footer');

    }

    public function system_users()
    {
        $data['title'] = 'System Users';
        
        $data['active'] = "active";
        $data['inactive'] = "";
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/system_users', $data);
        $this->load->view('dashboard/footer');
    }

    public function change_user_status()
    {
        $id = $this->input->get('id');
        $status = $this->input->get('status');
        
        $this->admin_db->change_user_status($id, $status);
        
        // 1 - active, 2 - inactive, 3 - deleted
        if ($status == 2) {

            $data['success_msg'] = 'User Inactivated Successfully';
            $data['inactive'] = "active";
            $data['active'] = "";
            
        } else if ($status == 1) {

            $data['success_msg'] = 'User Activated Successfully';
            $data['active'] = "active";
            $data['inactive'] = "";
            
        } else if ($status == 3) {

            $data['success_msg'] = 'User Deleted Successfully';
            $data['active'] = "active";
            $data['inactive'] = "";
        }

        $data['title'] = 'System Users';
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/system_users', $data);
        $this->load->view('dashboard/footer');

    }

    public function view_user()
    {
        $id = $this->input->get('user_id');
        
        $data['user_details'] = $this->admin_db->get_user_by_id($id);
        
        $data['title'] = 'User Profile';
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/user_profile', $data);
        $this->load->view('dashboard/footer');
    }
    
    public function save_edit_user_details()
    {
        $id = $this->input->post('user_id');
        $data['user_type'] = $this->input->post('user_type');
        $data['contact_name'] = $this->input->post('contact_name');
        $data['contact_number'] = $this->input->post('contact_num');
        $username = $data['username'] = $this->input->post('username');
        
        header('Content-Type: application/json');
        
        $username_ext = $this->admin_db->check_username_existing($username, $id);
        
        if($username_ext == true){
            echo json_encode(array("message" => "This Username is already exist", "status" => "1"));
            exit;
        }else{
            $up_user = $this->admin_db->save_edit_user_details($id, $data);
        
            if($up_user == true){
                echo json_encode(array("message" => "User Details Successfully Edited", "status" => "1", "user_id" => $id));

            }else{
                echo json_encode(array("message" => "An Error Occured while Editing User Details", "status" => "0", "user_id" => $id));

            }
        }
        
        
    }
    
    public function change_user_password()
    {
        $id = $this->input->post('user_id');
        $data['password'] = $this->input->post('password');
        
        header('Content-Type: application/json');
        $up_user = $this->admin_db->update_user_password($id, $data);
        
        if($up_user == true){
            echo json_encode(array("message" => "User Password Changed Successfully", "status" => "1"));
            
        }else{
            echo json_encode(array("message" => "An Error Occured while Changing User Password", "status" => "0"));
            
        }
    }
    
    public function save_add_user_details()
    {
        $data['user_type'] = $this->input->post('user_type');
        $data['contact_name'] = $this->input->post('contact_name');
        $data['contact_number'] = $this->input->post('contact_num');
        $username = $data['username'] = $this->input->post('username');
        $data['password'] = $this->input->post('password');
        
        header('Content-Type: application/json');
        
        $username_ext = $this->admin_db->check_username_existing($username);
        
        if($username_ext == true){
            echo json_encode(array("message" => "This Username is already exist", "status" => "0"));
            exit;
        }else{
            $up_user = $this->admin_db->save_add_user_details($data);
        
            if($up_user == true){
                echo json_encode(array("message" => "User Added Successfully", "status" => "1"));

            }else{
                echo json_encode(array("message" => "An Error Occured while Adding User", "status" => "0"));

            }
        }
    }
    
    public function check_username_exist_add()
    {
        $username = $this->input->post('username');
        
        header('Content-Type: application/json');
        
        $username_ext = $this->admin_db->check_username_existing($username);
        
        if($username_ext == true){
            echo json_encode(array("message" => "This Username is already exist - ", "status" => "0", "username" => $username));
        }else{
            echo json_encode(array("message" => "This Username can be used - ", "status" => "1", "username" => $username));
        }
    }
    
    public function check_username_exist_edit()
    {
        $username = $this->input->post('username');
        $user_id = $this->input->post('user_id');
        
        header('Content-Type: application/json');
        
        $username_ext = $this->admin_db->check_username_existing($username, $user_id);
        
        if($username_ext == true){
            echo json_encode(array("message" => "This Username is already exist - ", "status" => "0", "username" => $username));
        }else{
            echo json_encode(array("message" => "This Username can be used - ", "status" => "1", "username" => $username));
        }
    }

    public function customers()
    {
        $data['title'] = 'Customers';
        
        $data['active'] = "active";
        $data['inactive'] = "";
        $data['hold_on'] = "";
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/customers', $data);
        $this->load->view('dashboard/footer');
    }

    public function change_customer_status()
    {
        $id = $this->input->get('id');
        $status = $this->input->get('status');
        
        $this->admin_db->change_customer_status($id, $status);
        
        // 1 - active, 2 - inactive, 3 - deleted, 4 - hold
        if ($status == 2) {

            $data['success_msg'] = 'Customer Inactivated Successfully';
            $data['inactive'] = "active";
            $data['active'] = "";
            $data['hold_on'] = "";
            
        } else if ($status == 1) {

            $data['success_msg'] = 'Customer Activated Successfully';
            $data['active'] = "active";
            $data['inactive'] = "";
            $data['hold_on'] = "";
            
        } else if ($status == 3) {

            $data['success_msg'] = 'Customer Deleted Successfully';
            $data['active'] = "active";
            $data['inactive'] = "";
            $data['hold_on'] = "";
        }

        $data['title'] = 'Customers';
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/customers', $data);
        $this->load->view('dashboard/footer');

    }
    
    public function save_add_customer_details()
    {
        $data['customer_type'] = $this->input->post('customer_type');
        $data['customer_name'] = $this->input->post('customer_name');
        $data['contact_number'] = $this->input->post('contact_num');
        $data['tel_number'] = $this->input->post('tel_number');
        
        $dxb_over_paid_gold = $this->input->post('dxb_over_paid_gold');
        $dxb_over_paid_cash = $this->input->post('dxb_over_paid_cash');
        $box_over_paid_gold = $this->input->post('box_over_paid_gold');
        $box_over_paid_cash = $this->input->post('box_over_paid_cash');
        
        if($dxb_over_paid_gold != ''){
            $data['over_paid_gold'] = $dxb_over_paid_gold;
        }else{
            $data['over_paid_gold'] = 0.000;
            
        }
        if($dxb_over_paid_cash != ''){
            $data['over_paid_cash'] = $dxb_over_paid_cash;
        }else{
            $data['over_paid_cash'] = 0.00;
            
        }
        
        if($box_over_paid_gold != ''){
            $data['box_over_paid_gold'] = $box_over_paid_gold;
        }else{
            $data['box_over_paid_gold'] = 0.000;
            
        }
        if($box_over_paid_cash != ''){
            $data['box_over_paid_cash'] = $box_over_paid_cash;
        }else{
            $data['box_over_paid_cash'] = 0.00;
            
        }
        
        header('Content-Type: application/json');
              
        $up_user = $this->admin_db->save_add_customer_details($data);

        if($up_user == true){
            echo json_encode(array("message" => "Customer Added Successfully", "status" => "1"));

        }else{
            echo json_encode(array("message" => "An Error Occured while Adding Customer", "status" => "0"));

        }
    }

    public function view_customer()
    {
        $id = $this->input->get('customer_id');
        
        $sale_statuses = [1, 2, 3, 4];
        $ret_statuses = [1, 2];
        
        $data['customer_details'] = $this->admin_db->get_customer_by_id($id);
        $data['tot_credit_sale_details'] = $this->admin_db->get_summery_debt_details_by_cus_id($id, $sale_statuses, 'Credit Sale');
        $data['tot_gold_sale_details'] = $this->admin_db->get_summery_debt_details_by_cus_id($id, $sale_statuses, 'Gold Sale');
        $data['tot_credit_ret_sale_details'] = $this->admin_db->get_summery_dxb_sale_return_details_by_cus_id($id, $ret_statuses, 'Credit Sale');
        $data['tot_gold_ret_sale_details'] = $this->admin_db->get_summery_dxb_sale_return_details_by_cus_id($id, $ret_statuses, 'Gold Sale');
        
        $data['title'] = 'Customer Profile';
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/customer_profile', $data);
        $this->load->view('dashboard/footer');
    }
    
    public function save_edit_customer_details()
    {
        $id = $this->input->post('customer_id');
        $data['customer_type'] = $this->input->post('customer_type');
        $data['customer_name'] = $this->input->post('customer_name');
        $data['contact_number'] = $this->input->post('contact_num');
        $data['tel_number'] = $this->input->post('tel_number');
        
        $data['over_paid_gold'] = $this->input->post('over_paid_gold');
        $data['over_paid_cash'] = $this->input->post('over_paid_cash');
        $data['box_over_paid_gold'] = $this->input->post('box_over_paid_gold');
        $data['box_over_paid_cash'] = $this->input->post('box_over_paid_cash');
        
        header('Content-Type: application/json');
        
        $up_user = $this->admin_db->save_edit_customer_details($id, $data);

        if($up_user == true){
            echo json_encode(array("message" => "Customer Details Successfully Edited", "status" => "1"));

        }else{
            echo json_encode(array("message" => "An Error Occured while Editing Customer Details", "status" => "0"));

        }
    }

    public function sales()
    {
        $data['title'] = 'Sales';
        
        $data['all'] = "active";
        $data['pay_completed'] = "";
        $data['pay_incompleted'] = "";
        $data['pay_pending'] = "";
        
        $data['user_type'] = $this->session->userdata('user_type_id');
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/sales', $data);
        $this->load->view('dashboard/footer');
    }

    public function do_sales()
    {
        $data['title'] = 'Do Sales';
        $data['k_rate'] = $this->admin_db->get_rate_detail_by_id(1)->item_rate;
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/do_sales', $data);
        $this->load->view('dashboard/footer');
    }

    public function ajax_get_customer_details()
    {
        $id = $this->input->post('customer_id');
        header('Content-Type: application/json');
        
        $customer_details = $this->admin_db->get_customer_by_id($id);
        
        echo json_encode(array("contact_number" => $customer_details->contact_number, "tel_number" => $customer_details->tel_number, "customer_type" => $customer_details->customer_type, "customer_status" => $customer_details->status));
    }

    public function ajax_get_last_added_stock_items()
    {
        $item_type = $this->input->post('item_type');
        header('Content-Type: application/json');
        
        $stock_items = $this->admin_db->get_last_added_stock_items_by_type($item_type);
        
        echo json_encode($stock_items);
    }

    public function save_do_sale()
    {                
        $invoice_date = $this->input->post('invoice_date');
        $data['invoice_number'] = $this->input->post('invoice_number');
        $data['sale_type'] = $sale_type = $this->input->post('sale_type');
        $data['24k_rate'] = $rate = $this->input->post('24k_rate');
        $select_customer = $this->input->post('select_customer');
        $total_sum_credit = $this->input->post('debit_sum_txt_credit');
        $total_sum_gold = $this->input->post('debit_sum_txt_gold');
        $discount = $this->input->post('discount');
        
        $sale_data_credit = $this->input->post('sale_data_credit');
        $sale_data_gold = $this->input->post('sale_data_gold');
        
        $user_type = $this->session->userdata('user_type_id');
        
        $data['date'] = date("Y-m-d", strtotime($invoice_date));
        
        header('Content-Type: application/json');
        
        try {
            if($sale_type == "Credit Sale"){
                $data['total_amount'] = $total_sum_credit;
                $data['24k_rate'] = $rate;
            }else if($sale_type == "Gold Sale"){
                $data['total_amount'] = $total_sum_gold;
                $data['24k_rate'] = '';
            }

            if($select_customer == "Add New Customer"){
                $data['customer_name'] = $customer_name = $this->input->post('customer_name');
                $data['contact_number'] = $customer_number = $this->input->post('contact_num');
                $data['customer_type'] = $customer_type = $this->input->post('customer_type');
                $data['tel_number'] = $this->input->post('tel_number');

                if($customer_type == 'Walk-In'){
                    $data['status'] = 4;
                }else if($customer_type == 'Priority'){
                    $data['status'] = 1;
                }

                if($sale_type == "Credit Sale"){
                    if($user_type == 1){
                        $data['debt_amount_cash'] = $total_sum_credit;
                    }else{
                        $data['debt_amount_cash'] = 0.00;
                    }
                    $data['debt_amount_gold'] = 0.000;

                    $data['over_paid_gold'] = 0.000;
                    $data['over_paid_cash'] = 0.00;
                }else if($sale_type == "Gold Sale"){
                    if($user_type == 1){
                        $data['debt_amount_gold'] = $total_sum_gold;
                    }else{
                        $data['debt_amount_gold'] = 0.000;
                    }

                    $data['debt_amount_cash'] = 0.00;

                    $data['over_paid_gold'] = 0.000;
                    $data['over_paid_cash'] = 0.00;
                }

                $data['box_debt_amount_gold'] = 0.000;
                $data['box_debt_amount_cash'] = 0.00;
                $data['box_over_paid_gold'] = 0.000;
                $data['box_over_paid_cash'] = 0.00;

                $added_customer = $this->admin_db->add_customer_details_sale($data);

                $data['customer_id'] = $added_customer['id'];

            }else{
                $data['customer_id'] = $select_customer;

                if($user_type == 1){

                    $customer_details = $this->admin_db->get_customer_by_id($select_customer);

                    if($customer_details->customer_type == 'Walk-In'){
                        $this->admin_db->change_customer_status($select_customer, 4);
                    }

                    $debt_amount_gold = $customer_details->debt_amount_gold + $total_sum_gold;
                    $debt_amount_cash = $customer_details->debt_amount_cash + $total_sum_credit;

                    if($sale_type == "Credit Sale"){
                        $amounts['debt_amount_cash'] = $debt_amount_cash;
                        $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold;
                    }else if($sale_type == "Gold Sale"){
                        $amounts['debt_amount_gold'] = $debt_amount_gold;
                        $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash;
                    }

                    $amounts['over_paid_gold'] = $customer_details->over_paid_gold;
                    $amounts['over_paid_cash'] = $customer_details->over_paid_cash;

                    $this->admin_db->update_customer_accounts($select_customer, $amounts);

                }
            }

            $data['sale_category'] = 'Normal';
            $data['description'] = NULL;

            if($user_type != 1){

                $data['status'] = 4;   
                $added_sale = $this->admin_db->add_sale($data);

                if($sale_type == "Credit Sale"){
                    $amount = 'Rs. '.number_format($total_sum_credit,2,'.',',');
                }else if($sale_type == "Gold Sale"){
                    $amount = number_format($total_sum_gold,3,'.',',').' g';
                }

                $data['item_id'] = $added_sale['id'];
                $data['item_type'] = 'Dxb Sale';
                $data['amount'] = $amount;
                $data['description'] = NULL;
                $this->admin_db->add_approval_requests($data);

            }else{
                $data['status'] = 3;   
                $added_sale = $this->admin_db->add_sale($data);

                if($select_customer == "Add New Customer"){
                    $customer_name = $customer_name;
                    $customer_number = $customer_number;
                    $send_msg = 'true';
                }else{
                    $customer_details = $this->admin_db->get_customer_by_id($select_customer);
                    $customer_name = $customer_details->customer_name;
                    $customer_number = $customer_details->contact_number;
                    if($customer_details->send_sms == 1){
                        $send_msg = 'true';
                    }else{
                        $send_msg = 'false';
                    }
                }

                if($customer_number != '' && $send_msg == 'true'){
                    $customer_number = preg_replace('/^0/','94',$customer_number); 

    //            print_r($customer_number);exit;

                    if($sale_type == "Credit Sale"){
                        $total_sum = 'Rs. '.number_format($total_sum_credit,2,'.',',');
                    }else if($sale_type == "Gold Sale"){
                        $total_sum = number_format($total_sum_gold,3,'.',',').' g';
                    }

                    $text = 'Hi '.$customer_name.'!<br>Thank you doing business of '.$total_sum.'<br>Ref. No : '.$data['invoice_number'].'<br>Bill Date : '.$data['date'].'<br><br>AVA Jewellers';

                    $user = "94777979679";
                    $password = "1739";
                    $text = urlencode($text);
                    $to = $customer_number;

                    $baseurl ="http://www.textit.biz/sendmsg";
                    $url = "$baseurl/?id=$user&pw=$password&to=$to&text=$text";
                    $ret = get_web_page($url);
                }

            }

            $total_sale_grams = 0;

            if($sale_type == "Credit Sale"){
                for ($x = 0; $x < count($sale_data_credit['description']); $x++) {

                    $data1['sale_id'] = $added_sale['id'];
                    $data1['item_name'] = $sale_data_credit['item_name'][$x];
                    $data1['description'] = $sale_data_credit['description'][$x];
                    $data1['selling_percentage'] = $sale_data_credit['selling_percentage'][$x];
                    $data1['selling_rate'] = $sale_data_credit['selling_rate'][$x];
                    $data1['sales_grams'] = $sale_data_credit['sales_grams'][$x];
                    $data1['amount'] = $sale_data_credit['sub_total'][$x];

                    $total_sale_grams += $sale_data_credit['sales_grams'][$x];

                    $this->admin_db->add_sale_items($data1);

                }

            }else if($sale_type == "Gold Sale"){
                for ($x = 0; $x < count($sale_data_gold['selling_percentage']); $x++) {

                    $data1['sale_id'] = $added_sale['id'];
                    $data1['item_name'] = $sale_data_gold['item_name'][$x];
                    $data1['description'] = $sale_data_gold['description'][$x];
                    $data1['selling_percentage'] = $sale_data_gold['selling_percentage'][$x];
                    $data1['selling_rate'] = null;
                    $data1['sales_grams'] = $sale_data_gold['sales_grams'][$x];
                    $data1['amount'] = $sale_data_gold['sub_total'][$x];

                    $total_sale_grams += $sale_data_gold['sales_grams'][$x];

                    $this->admin_db->add_sale_items($data1);

                }
            }

            if($user_type == 1){

                $stock_details = $this->admin_db->get_stock_details();

                $tt_gold_in_hand = $stock_details->tt_gold_in_hand;
                $new_tt_gold_in_hand = $tt_gold_in_hand - $total_sale_grams;

                $this->admin_db->update_stock_details('tt_gold_in_hand', $new_tt_gold_in_hand);

                $customer_details = $this->admin_db->get_customer_by_id($data['customer_id']);

                $account['item_type'] = 'sale';
                $account['item_id'] = $added_sale['id'];
                $account['action_type'] = 'Debited';
                $account['amount'] = $total_sale_grams;
                $account['description'] = 'Sold To '.$customer_details->customer_name;

                $this->admin_db->add_22k_gold_logs($account);

                if($discount != ''){
                    $sale_details = $this->admin_db->get_sale_details_by_id($added_sale['id']);

                    $sale_amounts['discount_amount'] = $sale_details->discount_amount + $discount;
                    $sale_amounts['balance_amount'] = $sale_details->balance_amount - $discount;

                    $customer_details = $this->admin_db->get_customer_by_id($sale_details->customer_id);

                    if($sale_amounts['balance_amount'] <= 0){

                        if($customer_details->status == 4 && $customer_details->customer_type == 'Walk-In'){
                            $this->admin_db->change_customer_status($sale_details->customer_id, 1);
                        }

                        $this->admin_db->change_sale_status($added_sale['id'], 1);
                    }else{

                        $this->admin_db->change_sale_status($added_sale['id'], 2);
                    }

                    $this->admin_db->update_sale_discount_amount($added_sale['id'], $sale_amounts);

                    if($sale_details->sale_type == "Credit Sale"){

                        $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash - $discount;

                        $amounts['over_paid_cash'] = $customer_details->over_paid_cash;
                        $amounts['over_paid_gold'] = $customer_details->over_paid_gold;
                        $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold;

                    }else if($sale_details->sale_type == "Gold Sale"){

                        $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold - $discount;

                        $amounts['over_paid_cash'] = $customer_details->over_paid_cash;
                        $amounts['over_paid_gold'] = $customer_details->over_paid_gold;
                        $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash;
                    }

                    $this->admin_db->update_customer_accounts($sale_details->customer_id, $amounts);

                    $data['sale_id'] = $added_sale['id'];
                    $data['customer_id'] = $sale_details->customer_id;
                    $data['discount_amount'] = $discount;
                    $this->admin_db->add_sale_discount($data);
                }

            }
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }
        
        if($added_sale['status'] == 1){
            echo json_encode(array("message" => "Sale Added Successfully", "status" => "1"));
            
        }
    }

    public function view_sale()
    {
        $id = $this->input->get('sale_id');
        
        $data['title'] = 'View Sale Details';
        
        $data['sale_details'] = $this->admin_db->get_sale_details_by_id($id);
        $data['sale_items'] = $this->admin_db->get_sale_items_by_sale_id($id);    
        $data['payment_items'] = $this->admin_db->get_payment_items_by_sale_id($id);
        $data['fixing_items'] = $this->admin_db->get_fixing_details_by_sale_id($id);
        
        if($data['sale_details']->status == 4){
            $data['approval_details'] = $this->admin_db->get_approval_by_item_type_id('Dxb Sale', $id);
        }
        
//        echo '<pre>'. print_r($data['returned_sale_details'],1). '</pre>'; exit;
        
//        print_r($data['sale_details']);exit;
                
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/view_sale', $data);
        $this->load->view('dashboard/footer');
    }

    public function view_returned_sale()
    {
        $return_sale_id = $this->input->get('return_sale_id');
        
        $data['title'] = 'View Returned Sale Details';
        
        $data['returned_sale_details'] = $this->admin_db->get_returned_sale_details_by_id($return_sale_id);
        
        if($data['returned_sale_details']){
            $data['returned_sale_items'] = $this->admin_db->get_returned_sale_items_by_returned_sale_id($return_sale_id);
            
        }else{
            $data['returned_sale_items'] = '';
            
        }
        
        if($data['returned_sale_details']->status == 2){
            $data['approval_details'] = $this->admin_db->get_approval_by_item_type_id('Return Dxb Sale', $return_sale_id);
        }
                
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/view_returned_sale', $data);
        $this->load->view('dashboard/footer');
    }

    public function print_returned_sale()
    {
        $return_sale_id = $this->input->get('return_sale_id');
        
        $data['title'] = 'View Returned Sale Details';
        
        $data['returned_sale_details'] = $this->admin_db->get_returned_sale_details_by_id($return_sale_id);
        
        $data['returned_sale_items'] = $this->admin_db->get_returned_sale_items_by_returned_sale_id($return_sale_id);
                
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/print_returned_sale', $data);
        $this->load->view('dashboard/footer');
    }

    public function save_make_normal_payment()
    {     
        
        $data['sale_id'] = $sale_id = $this->input->post('sale_id');
        $data['customer_id'] = $customer_id = $this->input->post('customer_id');
        $invoice_date = $this->input->post('invoice_date');
        $data['date'] = date("Y-m-d", strtotime($invoice_date));
        
        $data['payment_method'] = $payment_method = $this->input->post('payment_method');
        
        if($payment_method == 'Gold'){
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 1;
            
        }elseif($payment_method == 'Over Paid Gold'){
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 1;
            
        }elseif($payment_method == 'Over Paid Cash'){
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 1;
            
        }elseif($payment_method == 'Cash'){
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 1;
            
        }else if($payment_method == 'Cheque'){
            $data['cheq_bank'] = $this->input->post('cheq_bank');
            $data['cheq_cheque_number'] = $this->input->post('cheq_cheque_number');
            $cheq_deposit_date = $this->input->post('cheq_deposit_date');
            $data['cheq_deposit_date'] = date("Y-m-d", strtotime($cheq_deposit_date));
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 2;
            
        }else if($payment_method == 'Bank Deposit'){
            $data['deposit_bank_account'] = $bank_account_id = $this->input->post('deposit_bank_account');
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['status'] = 1;
            
        }
        
        $payment_total = $this->input->post('payment_total');
        $data['payment_amount'] = $payment_amount = $this->input->post('payment_amount');
        $data['payment_type'] = 'Normal';
        
        header('Content-Type: application/json');
        
        try {
            $added_payment = $this->admin_db->add_payment_details($data);

            $added_payment['status'] = 1;

            if($added_payment['status'] == 1){
                $data['payment_id'] = $added_payment['id'];
                $this->admin_db->add_payment_items($data);
                
                $sale_details = $this->admin_db->get_sale_by_id($sale_id);
                
                if($payment_method != 'Cheque'){

                    $balance_total = $payment_total - $payment_amount;

                    if($balance_total < 0){
                        $this->admin_db->update_sale_bal_amount($sale_id, 0);
                        $payment_amount = $payment_total;
                    }else{
                        $this->admin_db->update_sale_bal_amount($sale_id, $balance_total);

                    }

                    $customer_details = $this->admin_db->get_customer_by_id($customer_id);
                    
                    if($sale_details->status != 4){

                        if($balance_total <= 0){

                            if($customer_details->status == 4 && $customer_details->customer_type == 'Walk-In'){
                                $this->admin_db->change_customer_status($customer_id, 1);
                            }

                            $this->admin_db->change_sale_status($sale_id, 1);
                        }else{

                            $this->admin_db->change_sale_status($sale_id, 2);
                        }
                        
                        if($payment_method == "Gold"){

                            if($balance_total < 0){

                                $new_over_paid_gold = $customer_details->over_paid_gold + abs($balance_total);
                                $amounts['over_paid_gold'] = $new_over_paid_gold;

                            }else{

                                $amounts['over_paid_gold'] = $customer_details->over_paid_gold;

                            }

                            $amounts['over_paid_cash'] = $customer_details->over_paid_cash;
                            $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold - $payment_amount;
                            $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash;

                        }elseif($payment_method == "Over Paid Gold"){

                            $new_over_paid_gold = $customer_details->over_paid_gold - $payment_amount;
                            $amounts['over_paid_gold'] = $new_over_paid_gold;

                            if($balance_total < 0){

                                $over_paid_gold = $customer_details->over_paid_gold - $payment_amount;
                                $new_over_paid_gold = $over_paid_gold + ($payment_amount - $payment_total);

                                $amounts['over_paid_gold'] = $new_over_paid_gold;

                            }

                            $amounts['over_paid_cash'] = $customer_details->over_paid_cash;
                            $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold - $payment_amount;
                            $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash;

                        }elseif($payment_method == "Over Paid Cash"){

                            $new_over_paid_cash = $customer_details->over_paid_cash - $payment_amount;
                            $amounts['over_paid_cash'] = $new_over_paid_cash;

                            if($balance_total < 0){

                                $over_paid_cash = $customer_details->over_paid_cash - $payment_amount;
                                $new_over_paid_cash = $over_paid_cash + ($payment_amount - $payment_total);

                                $amounts['over_paid_cash'] = $new_over_paid_cash;

                            }

                            $amounts['over_paid_gold'] = $customer_details->over_paid_gold;
                            $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold;
                            $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash - $payment_amount;

                        }else{

                            if($balance_total < 0){

                                $new_over_paid_cash = $customer_details->over_paid_cash + abs($balance_total);
                                $amounts['over_paid_cash'] = $new_over_paid_cash;

                            }else{

                                $amounts['over_paid_cash'] = $customer_details->over_paid_cash;

                            }

                            $amounts['over_paid_gold'] = $customer_details->over_paid_gold;
                            $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold;
                            $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash - $payment_amount;

                        }

                        $this->admin_db->update_customer_accounts($customer_id, $amounts);
                    }

                }
                
                if($sale_details->status != 4){

                    $stock_details = $this->admin_db->get_stock_details();

                    if($payment_method == 'Cash'){
                        $cash_in_hand = $stock_details->cash_in_hand;
                        $new_cash_in_hand = $cash_in_hand + $payment_amount;

                        $this->admin_db->update_stock_details('cash_in_hand', $new_cash_in_hand);

                        $account['action_date'] = $data['date'];
                        $account['item_type'] = 'receipt amount';
                        $account['item_id'] = $added_payment['id'];
                        $account['action_type'] = 'Credited';
                        $account['amount'] = $payment_amount;
                        $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                        $this->admin_db->add_cash_logs($account);

                    }

                    if($payment_method == 'Cheque'){
                        $cheque['bank_id'] = $data['cheq_bank'];
                        $cheque['payment_id'] = $added_payment['id'];
                        $cheque['customer_id'] = $customer_id;
                        $cheque['cheque_type'] = 'Sale';
                        $cheque['cheque_number'] = $data['cheq_cheque_number'];
                        $cheque['cheque_amount'] = $payment_amount;
                        $cheque['deposit_date'] = $data['cheq_deposit_date'];

                        $this->admin_db->add_cheque_details($cheque);

                    }

                    if($payment_method == 'Gold'){
                        $tf_gold_in_hand = $stock_details->tf_gold_in_hand;
                        $new_tf_gold_in_hand = $tf_gold_in_hand + $payment_amount;

                        $this->admin_db->update_stock_details('tf_gold_in_hand', $new_tf_gold_in_hand);

                        $account['item_type'] = 'receipt amount';
                        $account['item_id'] = $added_payment['id'];
                        $account['action_type'] = 'Credited';
                        $account['amount'] = $payment_amount;
                        $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                        $this->admin_db->add_24k_gold_logs($account);

                    }

                    if($payment_method == 'Bank Deposit'){
                    $account_details = $this->admin_db->get_bank_account_by_id($bank_account_id);

                    $bank_balance = $account_details->bank_balance;
                    $new_bank_balance  = $bank_balance + $payment_amount;

                    $this->admin_db->update_bank_balance($bank_account_id, $new_bank_balance);

                    $account['account_id'] = $bank_account_id;
                    $account['item_type'] = 'receipt amount';
                    $account['item_id'] = $added_payment['id'];
                    $account['action_type'] = 'Credited';
                    $account['amount'] = $payment_amount;
                    $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                    $this->admin_db->add_bank_account_logs($account);

                }
                    
                }

                echo json_encode(array("message" => "Payment Made Successfully", "status" => "1", "sale_id" => $sale_id));

            }else{
                echo json_encode(array("message" => "Error Occured while making the payment", "status" => "0", "sale_id" => $sale_id));

            }
        }
        
        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }
    }

    public function save_make_fixing_payment()
    {        
        $data['sale_id'] = $sale_id = $this->input->post('sale_id');
        $data['customer_id'] = $customer_id = $this->input->post('customer_id');
        $invoice_date = $this->input->post('invoice_date');
        $data['date'] = date("Y-m-d", strtotime($invoice_date));
        $data['24k_rate'] = $this->input->post('k_rate_fixing');
        $fixing_payment_amount = $this->input->post('fixing_payment_amount');
        $payment_total_in_grams = $this->input->post('payment_total_in_grams');
        $fixing_balance_total_in_grams = $this->input->post('fixing_balance_total_in_grams');
        
        $data['payment_method'] = $payment_method = $this->input->post('payment_method');
        
        if($payment_method == 'Gold'){
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 1;
            
        }elseif($payment_method == 'Cash'){
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 1;
            
        }else if($payment_method == 'Cheque'){
            $data['cheq_bank'] = $this->input->post('cheq_bank');
            $data['cheq_cheque_number'] = $this->input->post('cheq_cheque_number');
            $cheq_deposit_date = $this->input->post('cheq_deposit_date');
            $data['cheq_deposit_date'] = date("Y-m-d", strtotime($cheq_deposit_date));
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 2;
            
        }else if($payment_method == 'Bank Deposit'){
            $data['deposit_bank_account'] = $bank_account_id = $this->input->post('deposit_bank_account');
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['status'] = 1;
            
        }
        
        $data['payment_amount'] = $payment_amount = $this->input->post('fixing_payment_amount');
        $data['payment_type'] = 'Fixing';
        
        header('Content-Type: application/json');
        
        try {
            $added_payment = $this->admin_db->add_payment_details($data);

            if($added_payment['status'] == 1){
                $data['payment_id'] = $added_payment['id'];
                $added_payment_item = $this->admin_db->add_payment_items($data);
                $data['payment_item_id'] = $added_payment_item['id'];

                $data['paid_amount_in_cash'] = $fixing_payment_amount;
                $data['paid_amount_in_gold'] = $payment_total_in_grams - $fixing_balance_total_in_grams;

    //            print_r($data);exit;
                $this->admin_db->add_fixing_payments($data);

                if($payment_method != 'Cheque'){

                    $balance_total = $this->input->post('fixing_balance_total_in_grams');

                    $this->admin_db->update_sale_bal_amount($sale_id, $balance_total);

                    $customer_details = $this->admin_db->get_customer_by_id($customer_id);

                    if($balance_total <= 0){

                        if($customer_details->status == 4 && $customer_details->customer_type == 'Walk-In'){
                            $this->admin_db->change_customer_status($customer_id, 1);
                        }

                        $this->admin_db->change_sale_status($sale_id, 1);
                    }else{

                        $this->admin_db->change_sale_status($sale_id, 2);
                    }

                    $debt_amount_gold = $customer_details->debt_amount_gold - $data['paid_amount_in_gold'];

                    $amounts['debt_amount_gold'] = $debt_amount_gold;
                    $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash;

                    $amounts['over_paid_gold'] = $customer_details->over_paid_gold;
                    $amounts['over_paid_cash'] = $customer_details->over_paid_cash;

                    $this->admin_db->update_customer_accounts($customer_id, $amounts);

                }

                $stock_details = $this->admin_db->get_stock_details();

                if($payment_method == 'Cash'){
                    $cash_in_hand = $stock_details->cash_in_hand;
                    $new_cash_in_hand = $cash_in_hand + $payment_amount;

                    $this->admin_db->update_stock_details('cash_in_hand', $new_cash_in_hand);

                    $account['action_date'] = $data['date'];
                    $account['item_type'] = 'receipt amount';
                    $account['item_id'] = $added_payment['id'];
                    $account['action_type'] = 'Credited';
                    $account['amount'] = $payment_amount;
                    $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                    $this->admin_db->add_cash_logs($account);

                }

                if($payment_method == 'Cheque'){
                    $cheque['bank_id'] = $data['cheq_bank'];
                    $cheque['payment_id'] = $added_payment['id'];
                    $cheque['customer_id'] = $customer_id;
                    $cheque['cheque_type'] = 'Sale';
                    $cheque['cheque_number'] = $data['cheq_cheque_number'];
                    $cheque['cheque_amount'] = $payment_amount;
                    $cheque['deposit_date'] = $data['cheq_deposit_date'];

                    $this->admin_db->add_cheque_details($cheque);

                }

                if($payment_method == 'Gold'){
                    $tf_gold_in_hand = $stock_details->tf_gold_in_hand;
                    $new_tf_gold_in_hand = $tf_gold_in_hand + $payment_amount;

                    $this->admin_db->update_stock_details('tf_gold_in_hand', $new_tf_gold_in_hand);

                    $account['item_type'] = 'receipt amount';
                    $account['item_id'] = $added_payment['id'];
                    $account['action_type'] = 'Credited';
                    $account['amount'] = $payment_amount;
                    $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                    $this->admin_db->add_24k_gold_logs($account);

                }

                if($payment_method == 'Bank Deposit'){
                    $account_details = $this->admin_db->get_bank_account_by_id($bank_account_id);

                    $bank_balance = $account_details->bank_balance;
                    $new_bank_balance  = $bank_balance + $payment_amount;

                    $this->admin_db->update_bank_balance($bank_account_id, $new_bank_balance);

                    $account['account_id'] = $bank_account_id;
                    $account['item_type'] = 'receipt amount';
                    $account['item_id'] = $added_payment['id'];
                    $account['action_type'] = 'Credited';
                    $account['amount'] = $payment_amount;
                    $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                    $this->admin_db->add_bank_account_logs($account);

                }

                echo json_encode(array("message" => "Payment Made Successfully", "status" => "1", "sale_id" => $sale_id));

            }else{
                echo json_encode(array("message" => "Error Occured while making the payment", "status" => "0", "sale_id" => $sale_id));

            }
        }   

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }
    }
    
    public function save_return_sale()
    {                
        $data['sale_id'] = $sale_id = $this->input->post('sale_id');
        $data['customer_id'] = $customer_id = $this->input->post('customer_id');
        $invoice_date = $this->input->post('return_date');
        $data['date'] = date("Y-m-d", strtotime($invoice_date));
        $data['invoice_number'] = $this->input->post('invoice_number');
        $data['sale_type'] = $sale_type = $this->input->post('sale_type');
        $data['description'] = $this->input->post('description');
        
        $sale_item_ids = $this->input->post('item_id_ret_sale');
        
        $item_amount = $this->input->post('txt_ret_sale_item_amount');
        $item_name = $this->input->post('item_name_ret_sale');
        $item_description = $this->input->post('item_description_ret_sale');
        $selling_percentage = $this->input->post('selling_percentage_ret_sale');
        $selling_rate = $this->input->post('selling_rate_ret_sale');
        $sales_grams = $this->input->post('sales_grams_ret_sale');
        $actual_grams = $this->input->post('actual_grams_ret_sale');
        
        $user_type = $this->session->userdata('user_type_id');
        
        header('Content-Type: application/json');
        
        $total_return_sale_amount = 0;
        $total_return_sale_grams = 0;
        
        for ($x = 0; $x < count($sale_item_ids); $x++) {
            if($item_amount[$x] != ''){
                $total_return_sale_amount += $item_amount[$x];
                $total_return_sale_grams += $sales_grams[$x];
            }
        }

        if($sale_type == 'Credit Sale'){
            $data['24k_rate'] = $this->input->post('k_rate_ret_sale');
        }else{
            $data['24k_rate'] = NULL; 
        }

        $data['amount'] = $total_return_sale_amount;
        
        try {
            
            if($user_type == 1 && $user_type == 3){
            
                $sale_details = $this->admin_db->get_sale_details_by_id($sale_id);

                $customer_details = $this->admin_db->get_customer_by_id($customer_id);

                $sale_amounts['balance_amount'] = $sale_details->balance_amount - $total_return_sale_amount;
                $sale_amounts['return_sale_amount'] = $sale_details->return_sale_amount + $total_return_sale_amount;

                if($sale_amounts['balance_amount'] <= 0){

                    if($customer_details->status == 4 && $customer_details->customer_type == 'Walk-In'){
                        $this->admin_db->change_customer_status($customer_id, 1);
                    }

                    $this->admin_db->change_sale_status($sale_id, 1);
                }else{

                    $this->admin_db->change_sale_status($sale_id, 2);
                }

                $this->admin_db->update_return_sale_amounts($sale_id, $sale_amounts);

                if($sale_type == "Credit Sale"){

                    if($customer_details->debt_amount_cash == '' || $customer_details->debt_amount_cash == 0.00){
                        $amounts['over_paid_cash'] = $customer_details->over_paid_cash + $total_return_sale_amount;
                        $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash;
                    }else{
                        $amounts['over_paid_cash'] = $customer_details->over_paid_cash;
                        $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash - $total_return_sale_amount;
                    }

                    $amounts['over_paid_gold'] = $customer_details->over_paid_gold;
                    $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold;

                }else if($sale_type == "Gold Sale"){

                    if($customer_details->debt_amount_gold == '' || $customer_details->debt_amount_gold == 0.00){
                        $amounts['over_paid_gold'] = $customer_details->over_paid_gold + $total_return_sale_amount;
                        $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold;
                    }else{
                        $amounts['over_paid_gold'] = $customer_details->over_paid_gold;
                        $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold - $total_return_sale_amount;
                    }

                    $amounts['over_paid_cash'] = $customer_details->over_paid_cash;
                    $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash;
                }

                $this->admin_db->update_customer_accounts($customer_id, $amounts);

                $data['status'] = 1; // Completed
                $added_return_sale = $this->admin_db->add_return_sale($data);

                $total_sale_grams = 0;

                for ($x = 0; $x < count($sale_item_ids); $x++) {
                    if($item_amount[$x] != ''){
                        $added_ret_sale_item['return_sale_id'] = $added_return_sale['id'];
                        $added_ret_sale_item['item_id'] = $sale_item_ids[$x];
                        $added_ret_sale_item['selling_percentage'] = $selling_percentage[$x];
                        $added_ret_sale_item['selling_rate'] = $selling_rate[$x];
                        $added_ret_sale_item['sales_grams'] = $sales_grams[$x];
                        $added_ret_sale_item['item_name'] = $item_name[$x];
                        $added_ret_sale_item['description'] = $item_description[$x];
                        $added_ret_sale_item['amount'] = $item_amount[$x];

                        $total_sale_grams += $sales_grams[$x];

                        $this->admin_db->add_return_sale_items($added_ret_sale_item);  

                        $actual_grams_after_ret = $actual_grams[$x] - $sales_grams[$x];

                        $this->admin_db->update_sale_item_actual_grams($sale_item_ids[$x], $actual_grams_after_ret); 

                    }
                }

                $stock_details = $this->admin_db->get_stock_details();

                $tt_gold_in_hand = $stock_details->tt_gold_in_hand;
                $new_tt_gold_in_hand = $tt_gold_in_hand + $total_sale_grams;

                $this->admin_db->update_stock_details('tt_gold_in_hand', $new_tt_gold_in_hand);

                $account['item_type'] = 'return sale';
                $account['item_id'] = $added_return_sale['id'];
                $account['action_type'] = 'Credited';
                $account['amount'] = $total_sale_grams;
                $account['description'] = 'Returned Sale From '.$customer_details->customer_name;

                $this->admin_db->add_22k_gold_logs($account);
                
            }else{
                
                $data['status'] = 2; // Requested    
                $added_return_sale = $this->admin_db->add_return_sale($data);

                $total_sale_grams = 0;

                for ($x = 0; $x < count($sale_item_ids); $x++) {
                    if($item_amount[$x] != ''){
                        $added_ret_sale_item['return_sale_id'] = $added_return_sale['id'];
                        $added_ret_sale_item['item_id'] = $sale_item_ids[$x];
                        $added_ret_sale_item['selling_percentage'] = $selling_percentage[$x];
                        $added_ret_sale_item['selling_rate'] = $selling_rate[$x];
                        $added_ret_sale_item['sales_grams'] = $sales_grams[$x];
                        $added_ret_sale_item['item_name'] = $item_name[$x];
                        $added_ret_sale_item['description'] = $item_description[$x];
                        $added_ret_sale_item['amount'] = $item_amount[$x];

                        $this->admin_db->add_return_sale_items($added_ret_sale_item); 
                    }
                }

                if($sale_type == "Credit Sale"){
                    $amount = 'Rs. '.number_format($total_return_sale_amount,2,'.',',');
                }else if($sale_type == "Gold Sale"){
                    $amount = number_format($total_return_sale_amount,3,'.',',').' g';
                }

                $data['item_id'] = $added_return_sale['id'];
                $data['item_type'] = 'Return Dxb Sale';
                $data['amount'] = $amount;
                $data['description'] = NULL;
                $this->admin_db->add_approval_requests($data);
            }
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }
            
        echo json_encode(array("message" => "Sale Return Added Successfully", "status" => "1", "sale_id" => $sale_id));

    }
    
    public function save_sale_discount()
    {        
        $data['sale_id'] = $sale_id = $this->input->post('sale_id');
        $data['customer_id'] = $customer_id = $this->input->post('customer_id');
        $discount_date = $this->input->post('discount_date');
        $data['date'] = date("Y-m-d", strtotime($discount_date));
        $data['discount_amount'] = $discount_amount = $this->input->post('discount_amount');
        $sale_type = $this->input->post('sale_type');
        
        $sale_details = $this->admin_db->get_sale_details_by_id($sale_id);
        
        $sale_amounts['discount_amount'] = $sale_details->discount_amount + $discount_amount;
        $sale_amounts['balance_amount'] = $sale_details->balance_amount - $discount_amount;
        
        $customer_details = $this->admin_db->get_customer_by_id($customer_id);
        
        try {

            if($sale_amounts['balance_amount'] <= 0){

                if($customer_details->status == 4 && $customer_details->customer_type == 'Walk-In'){
                    $this->admin_db->change_customer_status($customer_id, 1);
                }

                $this->admin_db->change_sale_status($sale_id, 1);
            }else{

                $this->admin_db->change_sale_status($sale_id, 2);
            }

            $this->admin_db->update_sale_discount_amount($sale_id, $sale_amounts);

            if($sale_type == "Credit Sale"){

                $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash - $discount_amount;

                $amounts['over_paid_cash'] = $customer_details->over_paid_cash;
                $amounts['over_paid_gold'] = $customer_details->over_paid_gold;
                $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold;

            }else if($sale_type == "Gold Sale"){

                $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold - $discount_amount;

                $amounts['over_paid_cash'] = $customer_details->over_paid_cash;
                $amounts['over_paid_gold'] = $customer_details->over_paid_gold;
                $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash;
            }

            $this->admin_db->update_customer_accounts($customer_id, $amounts);

            header('Content-Type: application/json');

            $this->admin_db->add_sale_discount($data);
        }
        
        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }
            
        echo json_encode(array("message" => "Discount Added Successfully", "status" => "1", "sale_id" => $sale_id));

    }

    public function delete_sale()
    {
        $id = $this->input->get('id');
        $status = $this->input->get('status');
        
        try {
            $status_updated = $this->admin_db->change_sale_status($id, $status);
            $status_updated = true;
            if($status_updated == true){

                // 6 - Deleted
                if ($status == 6) {

                    $data['success_msg'] = 'Sale Deleted Successfully';

                    $sale_items = $this->admin_db->get_sale_items_by_sale_id($id);

                    if ($sale_items) {

                        $total_sale_grams = 0;

                        foreach($sale_items as $sale_item){

                            $total_sale_grams += $sale_item['sales_grams'];

                        }

                        $stock_details = $this->admin_db->get_stock_details();

                        $tt_gold_in_hand = $stock_details->tt_gold_in_hand;
                        $new_tt_gold_in_hand = $tt_gold_in_hand + $total_sale_grams;

                        $this->admin_db->update_stock_details('tt_gold_in_hand', $new_tt_gold_in_hand);

                        $account['item_type'] = 'delete sale';
                        $account['item_id'] = $id;
                        $account['action_type'] = 'Credited';
                        $account['amount'] = $total_sale_grams;
                        $account['description'] = 'Sale Deleted. Sale No.'.$id;

                        $this->admin_db->add_22k_gold_logs($account);

                    }

                    $sale_details = $this->admin_db->get_sale_details_by_id($id);

                    $customer_details = $this->admin_db->get_customer_by_id($sale_details->customer_id);

                    $paid_amount = $sale_details->total_amount - $sale_details->balance_amount;

                    if($sale_details->sale_type == 'Credit Sale'){
                        if($paid_amount == 0){

                            $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash - $sale_details->balance_amount;
                            $amounts['over_paid_cash'] = $customer_details->over_paid_cash;
                            $amounts['over_paid_gold'] = $customer_details->over_paid_gold;
                            $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold;

                        }else{

                            $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash - $sale_details->balance_amount;
                            $amounts['over_paid_cash'] = $customer_details->over_paid_cash + $paid_amount;
                            $amounts['over_paid_gold'] = $customer_details->over_paid_gold;
                            $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold;

                        }
                    }elseif($sale_details->sale_type == 'Gold Sale'){
                        if($paid_amount == 0){

                            $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold - $sale_details->balance_amount;
                            $amounts['over_paid_gold'] = $customer_details->over_paid_gold;
                            $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash;
                            $amounts['over_paid_cash'] = $customer_details->over_paid_cash;

                        }else{

                            $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold - $sale_details->balance_amount;
                            $amounts['over_paid_gold'] = $customer_details->over_paid_gold + $paid_amount;
                            $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash;
                            $amounts['over_paid_cash'] = $customer_details->over_paid_cash;

                        }

                    }

                    $this->admin_db->update_customer_accounts($sale_details->customer_id, $amounts);

                }
            }

            redirect(base_url().'view_sale?sale_id='.$sale_details->id);
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }

    }

    public function print_sale()
    {
        $id = $this->input->get('sale_id');
        
        $data['title'] = 'View Sale Details';
        
        $data['sale_details'] = $this->admin_db->get_sale_details_by_id($id);
        $data['sale_items'] = $this->admin_db->get_sale_items_by_sale_id($id);    
        $data['payment_items'] = $this->admin_db->get_payment_items_by_sale_id($id);
        $data['fixing_items'] = $this->admin_db->get_fixing_details_by_sale_id($id);
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/print_sale', $data);
        $this->load->view('dashboard/footer');
    }

    public function debtors()
    {
        $data['title'] = 'Debtors';
        
        $data['active'] = "active";
        $data['inactive'] = "";
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/debtors', $data);
        $this->load->view('dashboard/footer');
    }

    public function view_debtor()
    {
        $id = $this->input->get('customer_id');
        $data['debtor_type'] = $debtor_type = $this->input->get('debtor_type');
        
        $data['title'] = 'View Debtor Details';
        
        if($debtor_type == 'credit'){
            $sales_type = 'Credit Sale';
        }elseif($debtor_type == 'gold'){
            $sales_type = 'Gold Sale';
        }
        
        $statuses = [2, 3];
        
        $data['customer_details'] = $this->admin_db->get_customer_by_id($id);
        $data['credit_sale_details'] = $this->admin_db->get_debt_details_by_cus_id($id, $statuses, 'Credit Sale');
        $data['gold_sale_details'] = $this->admin_db->get_debt_details_by_cus_id($id, $statuses, 'Gold Sale');
        $data['tot_credit_sale_details'] = $this->admin_db->get_summery_debt_details_by_cus_id($id, $statuses, 'Credit Sale');
        $data['tot_gold_sale_details'] = $this->admin_db->get_summery_debt_details_by_cus_id($id, $statuses, 'Gold Sale');
        $data['sale_items'] = $this->admin_db->get_sale_items_by_sale_id($id);
        $data['payment_items'] = $this->admin_db->get_payment_items_by_sale_id($id);
        $data['pending_cheques'] = $this->admin_db->get_dxb_sale_cheques_by_customer_id($id, 'Pending');
        
//        echo '<pre>'. print_r($data['customer_details'],1). '</pre>'; exit;
        
//        print_r($data['payment_items']);exit;
                
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/view_debtor', $data);
        $this->load->view('dashboard/footer');
    }

    public function save_make_normal_debtor_payment()
    {                  
        $data['customer_id'] = $customer_id = $this->input->post('customer_id');
        $invoice_date = $this->input->post('invoice_date');
        $data['date'] = date("Y-m-d", strtotime($invoice_date));
        
        $data['payment_method'] = $payment_method = $this->input->post('payment_method');
        
        if($payment_method == 'Gold'){
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 1;
            
        }elseif($payment_method == 'Over Paid Gold'){
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 1;
            
        }elseif($payment_method == 'Over Paid Cash'){
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 1;
            
        }elseif($payment_method == 'Cash'){
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 1;
            
        }else if($payment_method == 'Cheque'){
            $data['cheq_bank'] = $this->input->post('cheq_bank');
            $data['cheq_cheque_number'] = $this->input->post('cheq_cheque_number');
            $cheq_deposit_date = $this->input->post('cheq_deposit_date');
            $data['cheq_deposit_date'] = date("Y-m-d", strtotime($cheq_deposit_date));
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 2;
            
        }else if($payment_method == 'Bank Deposit'){
            $data['deposit_bank_account'] = $bank_account_id = $this->input->post('deposit_bank_account');
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['status'] = 1;
            
        }
        
        try {
            if($payment_method == 'Gold' || $payment_method == 'Over Paid Gold'){
                $data['payment_amount'] = $payment_amount = $this->input->post('payment_amount_gold');
                $payment_amounts = $this->input->post('debtor_payment_amount_gold');
                $balance_amounts = $this->input->post('debtor_balance_amount_gold');
                $tot_payment_amount = $this->input->post('tot_payment_amount_gold');
                $sale_ids = $this->input->post('sale_ids_gold');

                $tot_balance_amount = $payment_amount - $tot_payment_amount;

                if($tot_balance_amount > 0 && min($balance_amounts) > 0 || $tot_balance_amount > 0){

                    $customer_details = $this->admin_db->get_customer_by_id($customer_id);

                    $amounts['over_paid_gold'] = $customer_details->over_paid_gold + $tot_balance_amount;
                    $amounts['over_paid_cash'] = $customer_details->over_paid_cash;
                    $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold;
                    $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash;

                    $this->admin_db->update_customer_accounts($customer_id, $amounts);

                }

            }else{
                $data['payment_amount'] = $payment_amount = $this->input->post('payment_amount_credit');
                $payment_amounts = $this->input->post('debtor_payment_amount');
                $balance_amounts = $this->input->post('debtor_balance_amount');
                $tot_payment_amount = $this->input->post('tot_payment_amount');
                $sale_ids = $this->input->post('sale_ids');

                if($payment_method != 'Cheque'){

                    $tot_balance_amount = $payment_amount - $tot_payment_amount;

                    if(($tot_balance_amount > 0 && min($balance_amounts) > 0) || $tot_balance_amount > 0){

                        $customer_details = $this->admin_db->get_customer_by_id($customer_id);

                        $amounts['over_paid_cash'] = $customer_details->over_paid_cash + $tot_balance_amount;
                        $amounts['over_paid_gold'] = $customer_details->over_paid_gold;
                        $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold;
                        $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash;

                        $this->admin_db->update_customer_accounts($customer_id, $amounts);

                    }

                }
            }

            $data['payment_type'] = 'Normal';
            $added_payment = $this->admin_db->add_payment_details($data);

            $added_payment['status'] = 1;

            header('Content-Type: application/json');

            if($added_payment['status'] == 1){
                $data1['payment_id'] = $added_payment['id'];

                for ($x = 0; $x < count($sale_ids); $x++) {

                    if($payment_amounts[$x] != ''){
                        $payment_amounts[$x] = $payment_amounts[$x];
                    }else{
                        $payment_amounts[$x] = 0;
                    }


                    $data1['sale_id'] = $sale_ids[$x];
                    $data1['payment_amount'] = $payment_amounts[$x];

                    $this->admin_db->add_payment_items($data1);

                    if($payment_method != 'Cheque'){

                        if($balance_amounts[$x] < 0){
                            $this->admin_db->update_sale_bal_amount($sale_ids[$x], 0);
                            $payment_amounts[$x] = $payment_amounts[$x] - abs($balance_amounts[$x]);
                        }else{
                            $this->admin_db->update_sale_bal_amount($sale_ids[$x], $balance_amounts[$x]);

                        }

                        $customer_details = $this->admin_db->get_customer_by_id($customer_id);

                        if($balance_amounts[$x] <= 0){

                            if($customer_details->status == 4 && $customer_details->customer_type == 'Walk-In'){
                                $this->admin_db->change_customer_status($customer_id, 1);
                            }

                            $this->admin_db->change_sale_status($sale_ids[$x], 1);
                        }else{

                            $this->admin_db->change_sale_status($sale_ids[$x], 2);
                        }

                        if($payment_method == "Gold"){

                            if($balance_amounts[$x] < 0){

                                $new_over_paid_gold = $customer_details->over_paid_gold + abs($balance_amounts[$x]);
                                $amounts['over_paid_gold'] = $new_over_paid_gold;

                            }else{

                                $amounts['over_paid_gold'] = $customer_details->over_paid_gold;

                            }

                            $amounts['over_paid_cash'] = $customer_details->over_paid_cash;
                            $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold - $payment_amounts[$x];
                            $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash;


                        }elseif($payment_method == "Over Paid Gold"){

                            $new_over_paid_gold = $customer_details->over_paid_gold - $payment_amounts[$x];
                            $amounts['over_paid_gold'] = $new_over_paid_gold;

                            $amounts['over_paid_cash'] = $customer_details->over_paid_cash;
                            $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold - $payment_amounts[$x];
                            $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash;

                        }elseif($payment_method == "Over Paid Cash"){

                            $new_over_paid_cash = $customer_details->over_paid_cash - $payment_amounts[$x];
                            $amounts['over_paid_cash'] = $new_over_paid_cash;

                            $amounts['over_paid_gold'] = $customer_details->over_paid_gold;
                            $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold;
                            $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash - $payment_amounts[$x];

                        }else{
                            if($balance_amounts[$x] < 0){

                                $new_over_paid_cash = $customer_details->over_paid_cash + abs($balance_amounts[$x]);
                                $amounts['over_paid_cash'] = $new_over_paid_cash;

                            }else{

                                $amounts['over_paid_cash'] = $customer_details->over_paid_cash;

                            }

                            $amounts['over_paid_gold'] = $customer_details->over_paid_gold;
                            $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold;
                            $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash - $payment_amounts[$x];
                        }

                        $this->admin_db->update_customer_accounts($customer_id, $amounts);

                    }
                }

                $stock_details = $this->admin_db->get_stock_details();

                if($payment_method == 'Cash'){
                    $cash_in_hand = $stock_details->cash_in_hand;
                    $new_cash_in_hand = $cash_in_hand + $payment_amount;

                    $this->admin_db->update_stock_details('cash_in_hand', $new_cash_in_hand);

                    $account['action_date'] = $data['date'];
                    $account['item_type'] = 'receipt amount';
                    $account['item_id'] = $added_payment['id'];
                    $account['action_type'] = 'Credited';
                    $account['amount'] = $payment_amount;
                    $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                    $this->admin_db->add_cash_logs($account);

                }

                if($payment_method == 'Cheque'){
                    $cheque['bank_id'] = $data['cheq_bank'];
                    $cheque['payment_id'] = $added_payment['id'];
                    $cheque['customer_id'] = $customer_id;
                    $cheque['cheque_type'] = 'Sale';
                    $cheque['cheque_number'] = $data['cheq_cheque_number'];
                    $cheque['cheque_amount'] = $payment_amount;
                    $cheque['deposit_date'] = $data['cheq_deposit_date'];

                    $this->admin_db->add_cheque_details($cheque);

                }

                if($payment_method == 'Gold'){
                    $tf_gold_in_hand = $stock_details->tf_gold_in_hand;
                    $new_tf_gold_in_hand = $tf_gold_in_hand + $payment_amount;

                    $this->admin_db->update_stock_details('tf_gold_in_hand', $new_tf_gold_in_hand);

                    $account['item_type'] = 'receipt amount';
                    $account['item_id'] = $added_payment['id'];
                    $account['action_type'] = 'Credited';
                    $account['amount'] = $payment_amount;
                    $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                    $this->admin_db->add_24k_gold_logs($account);

                }

                if($payment_method == 'Bank Deposit'){
                    $account_details = $this->admin_db->get_bank_account_by_id($bank_account_id);

                    $bank_balance = $account_details->bank_balance;
                    $new_bank_balance  = $bank_balance + $payment_amount;

                    $this->admin_db->update_bank_balance($bank_account_id, $new_bank_balance);

                    $account['account_id'] = $bank_account_id;
                    $account['item_type'] = 'receipt amount';
                    $account['item_id'] = $added_payment['id'];
                    $account['action_type'] = 'Credited';
                    $account['amount'] = $payment_amount;
                    $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                    $this->admin_db->add_bank_account_logs($account);

                }

                echo json_encode(array("message" => "Payments Made Successfully", "status" => "1", "customer_id" => $customer_id));

            }else{
                echo json_encode(array("message" => "Error Occured while making the payment", "status" => "0", "customer_id" => $customer_id));

            }
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }
    }

    public function save_make_fixing_debtor_payment()
    {        
        $data['customer_id'] = $customer_id = $this->input->post('customer_id');
        $invoice_date = $this->input->post('invoice_date');
        $data['date'] = date("Y-m-d", strtotime($invoice_date));
        $data['24k_rate'] = $this->input->post('k_rate_debtor_fixing');
        
        $data['payment_method'] = $payment_method = $this->input->post('payment_method_debtor_fixing');
        
        if($payment_method == 'Gold'){
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 1;
            
        }elseif($payment_method == 'Cash'){
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 1;
            
        }else if($payment_method == 'Cheque'){
            $data['cheq_bank'] = $this->input->post('cheq_bank');
            $data['cheq_cheque_number'] = $this->input->post('cheq_cheque_number');
            $cheq_deposit_date = $this->input->post('cheq_deposit_date');
            $data['cheq_deposit_date'] = date("Y-m-d", strtotime($cheq_deposit_date));
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 2;
            
        }else if($payment_method == 'Bank Deposit'){
            $data['deposit_bank_account'] = $bank_account_id = $this->input->post('deposit_bank_account');
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['status'] = 1;
            
        }
        $data['payment_amount'] = $tot_payment_amount = $this->input->post('tot_debtor_fixing_payment_amount_cash');
        $data['payment_type'] = 'Fixing';
        
        try {
            $sale_ids = $this->input->post('debtor_fixing_sale_ids');
            $payment_amounts = $this->input->post('debtor_fixing_payment_amount');
            $total_balance_amounts_gold = $this->input->post('debtor_fixing_total_balance_amount_gold');
            $balance_amounts_gold = $this->input->post('debtor_fixing_balance_amount_gold');
    //        $balance_amounts_cash = $this->input->post('debtor_fixing_balance_amount_cash');
            $added_payment = $this->admin_db->add_payment_details($data);

            header('Content-Type: application/json');

            if($added_payment['status'] == 1){
                $data1['payment_id'] = $data['payment_id'] = $added_payment['id'];

                for ($x = 0; $x < count($sale_ids); $x++) {
                    $data1['sale_id'] = $data['sale_id'] = $sale_ids[$x];
                    $data1['payment_amount'] = $payment_amounts[$x];

                    $added_payment_item = $this->admin_db->add_payment_items($data1);
                    $data['payment_item_id'] = $added_payment_item['id'];

                    $data['paid_amount_in_cash'] = $payment_amounts[$x];
                    $data['paid_amount_in_gold'] = $total_balance_amounts_gold[$x] - $balance_amounts_gold[$x];

                    $this->admin_db->add_fixing_payments($data);

                    if($payment_method != 'Cheque'){

                        $this->admin_db->update_sale_bal_amount($sale_ids[$x], $balance_amounts_gold[$x]);

                        $customer_details = $this->admin_db->get_customer_by_id($customer_id);

                        if($balance_amounts_gold[$x] <= 0){

                            if($customer_details->status == 4 && $customer_details->customer_type == 'Walk-In'){
                                $this->admin_db->change_customer_status($customer_id, 1);
                            }

                            $this->admin_db->change_sale_status($sale_ids[$x], 1);
                        }else{

                            $this->admin_db->change_sale_status($sale_ids[$x], 2);
                        }

                        $debt_amount_gold = $customer_details->debt_amount_gold - $data['paid_amount_in_gold'];

                        $amounts['debt_amount_gold'] = $debt_amount_gold;
                        $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash;

                        $amounts['over_paid_gold'] = $customer_details->over_paid_gold;
                        $amounts['over_paid_cash'] = $customer_details->over_paid_cash;

                        $this->admin_db->update_customer_accounts($customer_id, $amounts);
                    }
                }

                $stock_details = $this->admin_db->get_stock_details();

                if($payment_method == 'Cash'){
                    $cash_in_hand = $stock_details->cash_in_hand;
                    $new_cash_in_hand = $cash_in_hand + $tot_payment_amount;

                    $this->admin_db->update_stock_details('cash_in_hand', $new_cash_in_hand);

                    $account['action_date'] = $data['date'];
                    $account['item_type'] = 'receipt amount';
                    $account['item_id'] = $added_payment['id'];
                    $account['action_type'] = 'Credited';
                    $account['amount'] = $tot_payment_amount;
                    $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                    $this->admin_db->add_cash_logs($account);

                }

                if($payment_method == 'Cheque'){
                    $cheque['bank_id'] = $data['cheq_bank'];
                    $cheque['payment_id'] = $added_payment['id'];
                    $cheque['customer_id'] = $customer_id;
                    $cheque['cheque_type'] = 'Sale';
                    $cheque['cheque_number'] = $data['cheq_cheque_number'];
                    $cheque['cheque_amount'] = $tot_payment_amount;
                    $cheque['deposit_date'] = $data['cheq_deposit_date'];

                    $this->admin_db->add_cheque_details($cheque);

                }

                if($payment_method == 'Gold'){
                    $tf_gold_in_hand = $stock_details->tf_gold_in_hand;
                    $new_tf_gold_in_hand = $tf_gold_in_hand + $tot_payment_amount;

                    $this->admin_db->update_stock_details('tf_gold_in_hand', $new_tf_gold_in_hand);

                    $account['item_type'] = 'receipt amount';
                    $account['item_id'] = $added_payment['id'];
                    $account['action_type'] = 'Credited';
                    $account['amount'] = $tot_payment_amount;
                    $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                    $this->admin_db->add_24k_gold_logs($account);

                }

                if($payment_method == 'Bank Deposit'){
                    $account_details = $this->admin_db->get_bank_account_by_id($bank_account_id);

                    $bank_balance = $account_details->bank_balance;
                    $new_bank_balance  = $bank_balance + $tot_payment_amount;

                    $this->admin_db->update_bank_balance($bank_account_id, $new_bank_balance);

                    $account['account_id'] = $bank_account_id;
                    $account['item_type'] = 'receipt amount';
                    $account['item_id'] = $added_payment['id'];
                    $account['action_type'] = 'Credited';
                    $account['amount'] = $tot_payment_amount;
                    $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                    $this->admin_db->add_bank_account_logs($account);

                }

                echo json_encode(array("message" => "Payments Made Successfully", "status" => "1", "customer_id" => $customer_id));

            }else{
                echo json_encode(array("message" => "Error Occured while making the payment", "status" => "0", "customer_id" => $customer_id));

            }
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }
    }

    public function bank_accounts()
    {
        $data['title'] = 'Bank Accounts';
        
        $data['active'] = "active";
        $data['inactive'] = "";
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/bank_accounts', $data);
        $this->load->view('dashboard/footer');
    }
    
    public function save_add_bank_account_details()
    {
        $data['account_type'] = $this->input->post('account_type');
        $data['bank_id'] = $this->input->post('bank_name');
        $data['account_name'] = $this->input->post('account_name');
        $data['account_number'] = $this->input->post('account_number');
        
        header('Content-Type: application/json');
              
        $up_user = $this->admin_db->save_add_bank_account_details($data);

        if($up_user == true){
            echo json_encode(array("message" => "Customer Added Successfully", "status" => "1"));

        }else{
            echo json_encode(array("message" => "An Error Occured while Adding Customer", "status" => "0"));

        }
    }

    public function change_bank_account_status()
    {
        $id = $this->input->get('id');
        $status = $this->input->get('status');
        
        $this->admin_db->change_bank_account_status($id, $status);
        
        // 1 - active, 2 - inactive
        if ($status == 2) {

            $data['success_msg'] = 'Bank Account Inactivated Successfully';
            $data['inactive'] = "active";
            $data['active'] = "";
            
        } else if ($status == 1) {

            $data['success_msg'] = 'Bank Account Activated Successfully';
            $data['active'] = "active";
            $data['inactive'] = "";
            
        }

        $data['title'] = 'Bank Accounts';
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/bank_accounts', $data);
        $this->load->view('dashboard/footer');

    }

    public function view_bank_account()
    {
        $id = $this->input->get('account_id');
        
        $data['account_details'] = $this->admin_db->get_account_details_by_id($id);
        
        $data['title'] = 'Bank Account Profile';
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/bank_account_profile', $data);
        $this->load->view('dashboard/footer');
    }
    
    public function save_edit_bank_account_details()
    {
        $id = $this->input->post('account_id');
        $data['account_type'] = $account_type = $this->input->post('account_type');
        $data['bank_id'] = $this->input->post('bank_name');
        $data['account_name'] = $this->input->post('account_name');
        $data['account_number'] = $this->input->post('account_number');
        $data['bank_balance'] = $bank_balance = $this->input->post('bank_balance');
        
        header('Content-Type: application/json');
        
        $account_details = $this->admin_db->get_account_details_by_id($id);
        
        if($account_details->bank_balance != $bank_balance){
            if($account_type == 'Dxb'){
                $account['account_id'] = $id;
                $account['item_type'] = 'bank_balance';
                $account['item_id'] = $id;
                $account['action_type'] = 'Credited';
                $account['amount'] = $bank_balance;
                $account['description'] = 'Bank Balance Changed to - Rs. '.$bank_balance;

                $this->admin_db->add_bank_account_logs($account);
                
            }elseif($account_type == 'Box'){
                $account['account_id'] = $id;
                $account['item_type'] = 'bank_balance';
                $account['item_id'] = $id;
                $account['action_type'] = 'Credited';
                $account['amount'] = $bank_balance;
                $account['description'] = 'Bank Balance Changed to - Rs. '.$bank_balance;

                $this->admin_db->add_box_bank_account_logs($account);
                
            }
            
        }

        
        $up_account = $this->admin_db->save_edit_bank_account_details($id, $data);

        if($up_account == true){
            echo json_encode(array("message" => "Bank Account Details Successfully Edited", "status" => "1", "account_id" => $id));

        }else{
            echo json_encode(array("message" => "An Error Occured while Editing Bank Account Details", "status" => "0", "account_id" => $id));

        }
    }

    public function get_monthly_collection_graph_data()
    {
        header('Content-Type: application/json');
        $data_array = array();
        
        $data_array = array();
        $end_date = date('Y-m-d', strtotime("+1 week"));
        $effectiveDate = date('Y-m-d', strtotime("-6 weeks", strtotime($end_date)));
        $i = 0;
        while ($effectiveDate < $end_date) {
            $unixtime = strtotime($effectiveDate);
            $v_month = date('M', $unixtime); //month in words
            $v_year = date('Y', $unixtime); //year
            $_month = date('m', $unixtime); //month
            $_date = date('d', $unixtime); //date
            $collection = $this->admin_db->get_collection_data_by_week($_date, $_month, $v_year);
            $effectiveDate = date("Y-m-d", strtotime("+1 week", strtotime($effectiveDate)));
            $j = 0;
            if ($collection == 0 || $collection == null) {
                $j++;
                $collection = 0;
            }
            $data_array[$i]['month'] = $_date.'/'.$_month;
            $data_array[$i]['total'] = $collection;
            $i++;
        }
        
        header('Content-Type: application/x-json; charset=utf-8');
        echo json_encode($data_array);
    }

    public function cheques()
    {
        $data['title'] = 'Cheques';
        
        $data['pending'] = "active";
        $data['deposited'] = "";
        $data['returned'] = "";
        $data['cancelled'] = "";
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/cheques', $data);
        $this->load->view('dashboard/footer');
    }

    public function view_cheque()
    {
        $id = $this->input->get('cheque_id');
        
        $data['title'] = 'View Cheque Details';
        
        $cheque_details = $this->admin_db->get_cheque_by_id($id);
        $data['cheque_details'] = $this->admin_db->get_cheque_details_by_id($id, $cheque_details->cheque_type);
        
        if($cheque_details->cheque_type == 'Sale'){
            $data['payment_details'] = $this->admin_db->get_payment_details_by_id($cheque_details->payment_id); 
            $data['sale_details'] = $this->admin_db->get_sales_by_payment_id($data['cheque_details']->payment_id, $data['cheque_details']->payment_type); 
        }elseif($cheque_details->cheque_type == 'Box Sale'){
            $data['payment_details'] = $this->admin_db->get_box_payment_details_by_id($cheque_details->payment_id); 
            $data['sale_details'] = $this->admin_db->get_box_sales_by_payment_id($data['cheque_details']->payment_id, $data['cheque_details']->payment_type); 
        }elseif($cheque_details->cheque_type == 'Other Income'){
            $data['payment_details'] = $this->admin_db->get_other_income_details_by_id($cheque_details->payment_id);
        }
        
        $data['customer_details'] = $this->admin_db->get_customer_by_id($data['cheque_details']->customer_id);
                
//        print_r($data['cheque_details']);exit;
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/view_cheque', $data);
        $this->load->view('dashboard/footer');
    }
    
    public function view_cheque_details_to_submit() {
        
        $id = $this->input->post('id');
        
        $data['cheque_details'] = $cheque_details = $this->admin_db->get_cheque_by_id($id);
        
        if($cheque_details->cheque_type == 'Sale'){
            $data['payment_details'] = $this->admin_db->get_payment_details_by_id($cheque_details->payment_id);  
        }elseif($cheque_details->cheque_type == 'Other Income'){
            $data['payment_details'] = $this->admin_db->get_other_income_details_by_id($cheque_details->payment_id);
        }
        
//        print_r($data['cheque_details']->id);exit;

        $this->load->view('dashboard/view_cheque_details', $data);
        
    }
    
    public function save_cheque_action()
    {
        $cheque_type = $this->input->post('cheque_type');
        $payment_id = $this->input->post('payment_id');
        $cheque_id = $this->input->post('cheque_id');
        $customer_id = $this->input->post('customer_id');
        $cheque_amount = $this->input->post('cheque_amount');
        $submit_action = $this->input->post('submit_action');
        $bank_account = $this->input->post('bank_account');
        $cheque_number = $this->input->post('cheque_number');
        $deposited_date = date("Y-m-d");
        
        header('Content-Type: application/json');
        
        try {
            $stock_details = $this->admin_db->get_stock_details();

            if($submit_action == 'Bank Deposited'){

                if($cheque_type == 'Sale'){

                    $sales_details = $this->admin_db->get_sales_by_payment_id($payment_id);

                    foreach($sales_details as $sales_detail){

                        if($sales_detail['payment_type'] != 'Fixing'){
                            $balance_total = $sales_detail['balance_amount'] - $sales_detail['paid_amount'];
                        }else{
                            $balance_total = $sales_detail['balance_amount'] - $sales_detail['paid_amount_in_gold'];
                        }

                        $this->admin_db->update_sale_bal_amount($sales_detail['sale_id'], $balance_total);

                        $customer_details = $this->admin_db->get_customer_by_id($customer_id);

                        if($balance_total <= 0){

                            if($customer_details->status == 4 && $customer_details->customer_type == 'Walk-In'){
                                $this->admin_db->change_customer_status($customer_id, 1);
                            }

                            $this->admin_db->change_sale_status($sales_detail['sale_id'], 1);
                        }else{

                            $this->admin_db->change_sale_status($sales_detail['sale_id'], 2);
                        }


                        if($sales_detail['payment_type'] != 'Fixing'){

                            $debt_amount_cash = $customer_details->debt_amount_cash - $sales_detail['paid_amount'];

                            $amounts['debt_amount_cash'] = $debt_amount_cash;
                            $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold;

                        }else{

                            $debt_amount_gold = $customer_details->debt_amount_gold - $sales_detail['paid_amount_in_gold'];

                            $amounts['debt_amount_gold'] = $debt_amount_gold;
                            $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash;

                        }

                        $over_paid_cash_amount = $cheque_amount - $sales_detail['paid_amount'];
                        $over_paid_cash = $customer_details->over_paid_cash + $over_paid_cash_amount;

                        $amounts['over_paid_cash'] = $over_paid_cash;
                        $amounts['over_paid_gold'] = $customer_details->over_paid_gold;

                        $this->admin_db->update_customer_accounts($customer_id, $amounts);
                    }

                }

                if($cheque_type == 'Box Sale'){

                    $sales_details = $this->admin_db->get_box_sales_by_payment_id($payment_id);

                    foreach($sales_details as $sales_detail){

                        if($sales_detail['payment_type'] != 'Fixing'){
                            $balance_total = $sales_detail['balance_amount'] - $sales_detail['paid_amount'];
                        }else{
                            $balance_total = $sales_detail['balance_amount'] - $sales_detail['paid_amount_in_gold'];
                        }

                        $this->admin_db->update_box_sale_bal_amount($sales_detail['box_sale_id'], $balance_total);

                        $customer_details = $this->admin_db->get_customer_by_id($customer_id);

                        if($balance_total <= 0){

                            if($customer_details->status == 4 && $customer_details->customer_type == 'Walk-In'){
                                $this->admin_db->change_customer_status($customer_id, 1);
                            }

                            $this->admin_db->change_box_sale_status($sales_detail['box_sale_id'], 1);
                        }else{

                            $this->admin_db->change_box_sale_status($sales_detail['box_sale_id'], 2);
                        }


                        if($sales_detail['payment_type'] != 'Fixing'){

                            $box_debt_amount_cash = $customer_details->box_debt_amount_cash - $sales_detail['paid_amount'];

                            $amounts['box_debt_amount_cash'] = $box_debt_amount_cash;
                            $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold;

                        }else{

                            $box_debt_amount_gold = $customer_details->box_debt_amount_gold - $sales_detail['paid_amount_in_gold'];

                            $amounts['box_debt_amount_gold'] = $box_debt_amount_gold;
                            $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash;

                        }

                        $box_over_paid_cash_amount = $cheque_amount - $sales_detail['paid_amount'];
                        $box_over_paid_cash = $customer_details->box_over_paid_cash + $box_over_paid_cash_amount;

                        $amounts['box_over_paid_cash'] = $box_over_paid_cash;
                        $amounts['box_over_paid_gold'] = $customer_details->box_over_paid_gold;

                        $this->admin_db->update_customer_box_accounts($customer_id, $amounts);
                    }

                }

                $account_details = $this->admin_db->get_bank_account_by_id($bank_account);

                $bank_balance = $account_details->bank_balance;
                $new_bank_balance  = $bank_balance + $cheque_amount;

                $this->admin_db->update_bank_balance($bank_account, $new_bank_balance);

                if($customer_id != null){
                    $customer_details = $this->admin_db->get_customer_by_id($customer_id);
                    $log_description = 'Cheque Deposited From '.$customer_details->customer_name.'. Cheque Number - '.$cheque_number;
                }else{
                    $log_description = 'Cheque Deposited. Cheque Number - '.$cheque_number;
                }

                $account['action_date'] = date('Y-m-d');
                $account['account_id'] = $bank_account;
                $account['item_type'] = 'cheque_deposited';
                $account['item_id'] = $cheque_id;
                $account['action_type'] = 'Credited';
                $account['amount'] = $cheque_amount;
                $account['description'] = $log_description;

                if($cheque_type == 'Box Sale'){
                    $this->admin_db->add_box_bank_account_logs($account);
                }else{
                    $this->admin_db->add_bank_account_logs($account);
                }

                if($cheque_type == 'Sale'){
                    $this->admin_db->change_payment_status($payment_id, 1);
                }elseif($cheque_type == 'Box Sale'){
                    $this->admin_db->change_box_payment_status($payment_id, 1);
                }elseif($cheque_type == 'Other Income'){
                    $this->admin_db->change_other_payment_status($payment_id, 1);
                }

                $this->admin_db->change_cheque_status($cheque_id, 'Deposited');

            }elseif($submit_action == 'Cashed'){

                if($cheque_type == 'Sale'){

                    $sales_details = $this->admin_db->get_sales_by_payment_id($payment_id);

                    foreach($sales_details as $sales_detail){

                        $balance_total = $sales_detail['balance_amount'] - $sales_detail['paid_amount'];

                        $this->admin_db->update_sale_bal_amount($sales_detail['sale_id'], $balance_total);

                        $customer_details = $this->admin_db->get_customer_by_id($customer_id);

                        if($balance_total <= 0){

                            if($customer_details->status == 4 && $customer_details->customer_type == 'Walk-In'){
                                $this->admin_db->change_customer_status($customer_id, 1);
                            }

                            $this->admin_db->change_sale_status($sales_detail['sale_id'], 1);
                        }else{

                            $this->admin_db->change_sale_status($sales_detail['sale_id'], 2);
                        }

                        if($sales_detail['payment_type'] != 'Fixing'){

                            $debt_amount_cash = $customer_details->debt_amount_cash - $sales_detail['paid_amount'];

                            $amounts['debt_amount_cash'] = $debt_amount_cash;
                            $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold;

                        }else{

                            $debt_amount_gold = $customer_details->debt_amount_gold - $sales_detail['paid_amount_in_gold'];

                            $amounts['debt_amount_gold'] = $debt_amount_gold;
                            $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash;

                        }

                        $over_paid_cash_amount = $cheque_amount - $sales_detail['paid_amount'];
                        $over_paid_cash = $customer_details->over_paid_cash + $over_paid_cash_amount;

                        $amounts['over_paid_cash'] = $over_paid_cash;
                        $amounts['over_paid_gold'] = $customer_details->over_paid_gold;

                        $this->admin_db->update_customer_accounts($customer_id, $amounts);
                    }

                    $cash_in_hand = $stock_details->cash_in_hand;
                    $new_cash_in_hand = $cash_in_hand + $cheque_amount;

                    $this->admin_db->update_stock_details('cash_in_hand', $new_cash_in_hand);

                }elseif($cheque_type == 'Box Sale'){

                    $sales_details = $this->admin_db->get_box_sales_by_payment_id($payment_id);

                    foreach($sales_details as $sales_detail){

                        $balance_total = $sales_detail['balance_amount'] - $sales_detail['paid_amount'];

                        $this->admin_db->update_box_sale_bal_amount($sales_detail['box_sale_id'], $balance_total);

                        $customer_details = $this->admin_db->get_customer_by_id($customer_id);

                        if($balance_total <= 0){

                            if($customer_details->status == 4 && $customer_details->customer_type == 'Walk-In'){
                                $this->admin_db->change_customer_status($customer_id, 1);
                            }

                            $this->admin_db->change_box_sale_status($sales_detail['box_sale_id'], 1);
                        }else{

                            $this->admin_db->change_box_sale_status($sales_detail['box_sale_id'], 2);
                        }

                        if($sales_detail['payment_type'] != 'Fixing'){

                            $box_debt_amount_cash = $customer_details->box_debt_amount_cash - $sales_detail['paid_amount'];

                            $amounts['box_debt_amount_cash'] = $box_debt_amount_cash;
                            $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold;

                        }else{

                            $box_debt_amount_gold = $customer_details->box_debt_amount_gold - $sales_detail['paid_amount_in_gold'];

                            $amounts['box_debt_amount_gold'] = $box_debt_amount_gold;
                            $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash;

                        }

                        $box_over_paid_cash_amount = $cheque_amount - $sales_detail['paid_amount'];
                        $box_over_paid_cash = $customer_details->box_over_paid_cash + $box_over_paid_cash_amount;

                        $amounts['box_over_paid_cash'] = $box_over_paid_cash;
                        $amounts['box_over_paid_gold'] = $customer_details->box_over_paid_gold;

                        $this->admin_db->update_customer_box_accounts($customer_id, $amounts);
                    }

                    $box_cash_in_hand = $stock_details->box_cash_in_hand;
                    $new_box_cash_in_hand = $box_cash_in_hand + $cheque_amount;

                    $this->admin_db->update_stock_details('box_cash_in_hand', $new_box_cash_in_hand);
                }

                if($cheque_type == 'Sale'){
                    $this->admin_db->change_payment_status($payment_id, 1);
                }elseif($cheque_type == 'Box Sale'){
                    $this->admin_db->change_box_payment_status($payment_id, 1);
                }elseif($cheque_type == 'Other Income'){
                    $this->admin_db->change_other_payment_status($payment_id, 1);
                }
                $this->admin_db->change_cheque_status($cheque_id, 'Deposited');

                if($customer_id != null){
                    $customer_details = $this->admin_db->get_customer_by_id($customer_id);
                    $log_description = 'Cheque Deposited From '.$customer_details->customer_name.'. Cheque Number - '.$cheque_number;
                }else{
                    $log_description = 'Cheque Deposited. Cheque Number - '.$cheque_number;
                }

                $account['action_date'] = $deposited_date;
                $account['item_type'] = 'cheque_cashed';
                $account['item_id'] = $cheque_id;
                $account['action_type'] = 'Credited';
                $account['amount'] = $cheque_amount;
                $account['description'] = $log_description;

                if($cheque_type == 'Box Sale'){
                    $this->admin_db->add_box_cash_logs($account);
                }else{
                    $this->admin_db->add_cash_logs($account);
                }


            }elseif($submit_action == 'Cheque Returned'){

                if($cheque_type == 'Sale'){
                    $this->admin_db->change_payment_status($payment_id, 3);
                }elseif($cheque_type == 'Box Sale'){
                    $this->admin_db->change_box_payment_status($payment_id, 3);
                }elseif($cheque_type == 'Other Income'){
                    $this->admin_db->change_other_payment_status($payment_id, 3);
                }
                $this->admin_db->change_cheque_status($cheque_id, 'Returned');

            }elseif($submit_action == 'Cheque Cancelled'){

                if($cheque_type == 'Sale'){
                    $this->admin_db->change_payment_status($payment_id, 4);
                }elseif($cheque_type == 'Box Sale'){
                    $this->admin_db->change_box_payment_status($payment_id, 4);
                }elseif($cheque_type == 'Other Income'){
                    $this->admin_db->change_other_payment_status($payment_id, 4);
                }
                $this->admin_db->change_cheque_status($cheque_id, 'Cancelled');

            }
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }
        
        echo json_encode(array("message" => "Cheque Submitted Made Successfully", "status" => "1"));
    }

    public function stock_items()
    {
        $data['title'] = 'Stock Items';
        
        $data['active'] = "active";
        $data['inactive'] = "";
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/stock_items', $data);
        $this->load->view('dashboard/footer');
    }
    
    public function save_add_stock_item_details()
    {
        $data['item_type'] = $this->input->post('item_type');
        $data['item_code'] = $this->input->post('item_code');
        $data['item_name'] = $this->input->post('item_name');
        $data['item_description'] = $this->input->post('item_description');
        $stock_item_category = $this->input->post('stock_item_category');
        
        header('Content-Type: application/json');
        
        if($stock_item_category == "Add New Category"){
            
            $category['category_name'] = $this->input->post('category_name');
            $category['description'] = $this->input->post('description');
            
            $added_category = $this->admin_db->save_add_stock_item_category_details($category);
            $data['category_id'] = $added_category['id'];
            
        }else{
            $data['category_id'] = $stock_item_category;
        }
              
        $up_user = $this->admin_db->save_add_stock_item_details($data);

        if($up_user == true){
            echo json_encode(array("message" => "Stock Item Added Successfully", "status" => "1"));

        }else{
            echo json_encode(array("message" => "An Error Occured while Adding Stock Item", "status" => "0"));

        }
    }

    public function change_stock_item_status()
    {
        $id = $this->input->get('id');
        $status = $this->input->get('status');
        
        $this->admin_db->change_stock_item_status($id, $status);
        
        // 1 - active, 2 - inactive, 3 - deleted
        if ($status == 2) {

            $data['success_msg'] = 'Stock Item Inactivated Successfully';
            $data['inactive'] = "active";
            $data['active'] = "";
            
        } else if ($status == 1) {

            $data['success_msg'] = 'Stock Item Activated Successfully';
            $data['active'] = "active";
            $data['inactive'] = "";
            
        } else if ($status == 3) {

            $data['success_msg'] = 'Stock Item Deleted Successfully';
            $data['active'] = "active";
            $data['inactive'] = "";
            
        }

        $data['title'] = 'Stock Items';
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/stock_items', $data);
        $this->load->view('dashboard/footer');

    }

    public function view_stock_item()
    {
        $id = $this->input->get('item_id');
        
        $data['item_details'] = $this->admin_db->get_item_details_by_id($id);
        
        $data['title'] = 'Stock Item Details';
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/stock_item_details', $data);
        $this->load->view('dashboard/footer');
    }
    
    public function save_edit_stock_item_details()
    {
        $id = $this->input->post('item_id');
        $data['item_type'] = $this->input->post('item_type');
        $data['item_code'] = $this->input->post('item_code');
        $data['item_name'] = $this->input->post('item_name');
        $data['item_description'] = $this->input->post('item_description');
        $stock_item_category = $this->input->post('stock_item_category');
        
        header('Content-Type: application/json');
        
        if($stock_item_category == "Add New Category"){
            
            $category['category_name'] = $this->input->post('category_name');
            $category['description'] = $this->input->post('description');
            
            $added_category = $this->admin_db->save_add_stock_item_category_details($category);
            $data['category_id'] = $added_category['id'];
            
        }else{
            $data['category_id'] = $stock_item_category;
        }
        
        $up_account = $this->admin_db->save_edit_stock_item_details($id, $data);

        if($up_account == true){
            echo json_encode(array("message" => "Stock Item Successfully Edited", "status" => "1", "item_id" => $id));

        }else{
            echo json_encode(array("message" => "An Error Occured while Editing Stock Item", "status" => "0", "item_id" => $id));

        }
    }

    public function rates()
    {
        $data['title'] = 'Rates';
        
        $data['rate_details'] = $this->admin_db->get_rate_details();
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/rates', $data);
        $this->load->view('dashboard/footer');
    }

    public function view_rate()
    {
        $data['title'] = 'Rate Details';
        $id = $this->input->get('rate_id');
        
        $data['rate_details'] = $this->admin_db->get_rate_detail_by_id($id);
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/view_rate', $data);
        $this->load->view('dashboard/footer');
    }
    
    public function save_change_rate_item()
    {
        $rate_id = $data['rate_id'] = $this->input->post('rate_id');
        $data['rate_amount'] = $this->input->post('current_rate');
        $description = $this->input->post('description');
        $other_description = $this->input->post('other_description');
        
        header('Content-Type: application/json');
        
        if($description == 'Other'){
            $data['description'] = $other_description;
            
        }else{
            $data['description'] = $description;
            
        }
        
        $user_type = $this->session->userdata('user_type_id');
        
        if($user_type != 1){
            $data['item_id'] = $rate_id;
            $data['item_type'] = '24K Rate Change';
            $data['amount'] = $data['rate_amount']; 
            $up_rate = $this->admin_db->add_approval_requests($data);
            
            $data['status'] = 'Request Sent';   
            $this->admin_db->save_add_rate_log($data);
            
        }else{
            $data['status'] = 'Approved';   
            $data['item_id'] = $rate_id;
            $data['item_type'] = '24K Rate Changed';
            $data['amount'] = $data['rate_amount']; 
            $this->admin_db->save_add_rate_log($data);
            $up_rate = $this->admin_db->update_current_rate($rate_id, $data); 
            
        }
        
        if($up_rate == true){
            echo json_encode(array("message" => "Rate Changed Successfully", "status" => "1", "user_type" => $user_type));

        }else{
            echo json_encode(array("message" => "An Error Occured while Changing Rate", "status" => "0", "user_type" => $user_type));

        }
    }
    
    public function save_add_previous_debts()
    {
        $data['customer_id'] = $customer_id = $this->input->post('customer_id');
        $invoice_date = $this->input->post('bill_date');
        $data['date'] = date("Y-m-d", strtotime($invoice_date));
        $data['sale_type'] = $sale_type = $this->input->post('sale_type');
        $sale_category = $this->input->post('sale_category');
        $data['total_amount'] = $total_amount =  $this->input->post('total_amount');
        $data['description'] = $this->input->post('description');
        $data['24k_rate'] = NULL;
        $data['sale_category'] = 'Old Debts';
        $data['invoice_number'] = NULL;
        
        header('Content-Type: application/json');
        $data['status'] = 3; // 3 - Pending Payment 
        
        try {
            if($sale_category == "Dxb"){
                $up_customer = $this->admin_db->add_sale($data);    

                $customer_details = $this->admin_db->get_customer_by_id($customer_id);

                $debt_amount_gold = $customer_details->debt_amount_gold + $total_amount;
                $debt_amount_cash = $customer_details->debt_amount_cash + $total_amount;

                if($sale_type == "Credit Sale"){
                    $amounts['debt_amount_cash'] = $debt_amount_cash;
                    $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold;
                }else if($sale_type == "Gold Sale"){
                    $amounts['debt_amount_gold'] = $debt_amount_gold;
                    $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash;
                }

                $amounts['over_paid_gold'] = $customer_details->over_paid_gold;
                $amounts['over_paid_cash'] = $customer_details->over_paid_cash;

                $up_customer = $this->admin_db->update_customer_accounts($customer_id, $amounts);

            }elseif($sale_category == "Box"){
                $this->admin_db->add_box_sale($data);    

                $customer_details = $this->admin_db->get_customer_by_id($customer_id);

                $box_debt_amount_gold = $customer_details->box_debt_amount_gold + $total_amount;
                $box_debt_amount_cash = $customer_details->box_debt_amount_cash + $total_amount;

                if($sale_type == "Credit Sale"){
                    $amounts['box_debt_amount_cash'] = $box_debt_amount_cash;
                    $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold;
                }else if($sale_type == "Gold Sale"){
                    $amounts['box_debt_amount_gold'] = $box_debt_amount_gold;
                    $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash;
                }

                $amounts['box_over_paid_gold'] = $customer_details->box_over_paid_gold;
                $amounts['box_over_paid_cash'] = $customer_details->box_over_paid_cash;

                $up_customer = $this->admin_db->update_customer_box_accounts($customer_id, $amounts);

            }
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }

        if($up_customer == true){
            echo json_encode(array("message" => "Previous Debts Added Successfully", "status" => "1"));

        }else{
            echo json_encode(array("message" => "An Error Occured while Adding Previous Debts", "status" => "0"));

        }
    }

    public function expense_categories()
    {
        $data['title'] = 'Expense Categories';
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/expense_categories', $data);
        $this->load->view('dashboard/footer');
    }
    
    public function save_add_expense_category_details()
    {
        $data['category_name'] = $this->input->post('category_name');
        $data['description'] = $this->input->post('description');
        
        header('Content-Type: application/json');
              
        $up_user = $this->admin_db->save_add_expense_category_details($data);

        if($up_user == true){
            echo json_encode(array("message" => "Expense Category Added Successfully", "status" => "1"));

        }else{
            echo json_encode(array("message" => "An Error Occured while Adding Expense Category", "status" => "0"));

        }
    }

    public function change_expense_category_status()
    {
        $id = $this->input->get('id');
        $status = $this->input->get('status');
        
        $this->admin_db->change_expense_category_status($id, $status);
        
        // 2 - deleted
        if ($status == 2) {

            $data['success_msg'] = 'Expense Category Deleted Successfully';
            
        }

        $data['title'] = 'Expense Categories';
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/expense_categories', $data);
        $this->load->view('dashboard/footer');

    }

    public function view_expense_category()
    {
        $id = $this->input->get('category_id');
        
        $data['category_details'] = $this->admin_db->get_expense_category_details_by_id($id);
        
        $data['title'] = 'Expense Category Details';
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/expense_category_details', $data);
        $this->load->view('dashboard/footer');
    }
    
    public function save_edit_expense_category_details()
    {
        $id = $this->input->post('category_id');
        $data['category_name'] = $this->input->post('category_name');
        $data['description'] = $this->input->post('description');
        
        header('Content-Type: application/json');
        
        $up_account = $this->admin_db->save_edit_expense_category_details($id, $data);

        if($up_account == true){
            echo json_encode(array("message" => "Expense Category Successfully Edited", "status" => "1", "category_id" => $id));

        }else{
            echo json_encode(array("message" => "An Error Occured while Editing Expense Category", "status" => "0", "category_id" => $id));

        }
    }

    public function expenses()
    {
        $data['title'] = 'Expenses';
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/expenses', $data);
        $this->load->view('dashboard/footer');
    }
    
    public function save_add_expense_details()
    {
        $expense_date = $this->input->post('expense_date');
        $data['date'] = date("Y-m-d", strtotime($expense_date));
        $expense_category = $this->input->post('expense_category');
        $payment_amount = $data['amount'] = $this->input->post('payment_amount');
        $payment_method = $data['payment_method'] = $this->input->post('payment_method');
        $data['description'] = $this->input->post('description');
        $user_type = $this->session->userdata('user_type_id');
        
        if($user_type != 1 && $payment_amount > 3000){
            $data['status'] = 'Pending';
        }else{
            $data['status'] = 'Approved';
            
        }
        
        $bank_id = NULL;
        
        if($payment_method == 'Cash'){
            $data['account_id'] = NULL;
            $data['cheque_number'] = NULL;
            $data['cheque_deposit_date'] = NULL;
            $data['third_party_bank_id'] = NULL;
            $data['third_party_account_number'] = NULL;
            
        }elseif($payment_method == 'Cheque'){
            $bank_account_id = $data['account_id'] = $this->input->post('cheq_bank_account');
            $cheque_number = $data['cheque_number'] = $this->input->post('cheq_cheque_number');
            $cheque_deposit_date = $this->input->post('cheq_deposit_date');
            $data['cheque_deposit_date'] = date("Y-m-d", strtotime($cheque_deposit_date));
            $data['third_party_bank_id'] = NULL;
            $data['third_party_account_number'] = NULL;
            
        }elseif($payment_method == 'Bank Transfer'){
            $bank_account_id = $data['account_id'] = $this->input->post('transfer_bank_account');
            $cheque_number = $data['cheque_number'] = NULL;
            $data['cheque_deposit_date'] = NULL;
            $bank_id = $data['third_party_bank_id'] = $this->input->post('bank_bank_name');
            $data['third_party_account_number'] = $this->input->post('bank_account_number');
            
        }elseif($payment_method == 'Bank Deposit'){
            $data['account_id'] = NULL;
            $data['cheque_number'] = NULL;
            $data['cheque_deposit_date'] = NULL;
            $bank_id = $data['third_party_bank_id'] = $this->input->post('bank_bank_name');
            $data['third_party_account_number'] = $this->input->post('bank_account_number');
            
        }
        
        header('Content-Type: application/json');
        
        if($expense_category == "Add New Category"){
            
            $category['category_name'] = $this->input->post('category_name');
            $category['description'] = $this->input->post('description');
            
            $added_category = $this->admin_db->save_add_expense_category_details($category);
            $data['category_id'] = $added_category['id'];
            
        }else{
            $data['category_id'] = $expense_category;
        }
        
        try {    
            $added_expense = $this->admin_db->add_expense_details($data);
            $expense_category_details = $this->admin_db->get_expense_category_details_by_id($data['category_id']);

            if($bank_id){
                $bank_details = $this->admin_db->get_bank_by_id($bank_id);
            }

            if($added_expense['status'] == 1){

                if($user_type == 1 || $payment_amount < 3000){

                    $data['payment_id'] = $added_expense['id'];
                    $stock_details = $this->admin_db->get_stock_details();

                    if($payment_method == 'Cash'){
                        $cash_in_hand = $stock_details->cash_in_hand;
                        $new_cash_in_hand = $cash_in_hand - $payment_amount;

                        $this->admin_db->update_stock_details('cash_in_hand', $new_cash_in_hand);

                        $account['action_date'] = $data['date'];
                        $account['item_type'] = 'expense';
                        $account['item_id'] = $added_expense['id'];
                        $account['action_type'] = 'Debited';
                        $account['amount'] = $payment_amount;
                        $account['description'] = 'Expense For '.$expense_category_details->category_name;

                        $this->admin_db->add_cash_logs($account);

                    }

                    if($payment_method == 'Cheque'){
                        $account_details = $this->admin_db->get_bank_account_by_id($bank_account_id);

                        $bank_balance = $account_details->bank_balance;
                        $new_bank_balance  = $bank_balance - $payment_amount;

                        $this->admin_db->update_bank_balance($bank_account_id, $new_bank_balance);

                        $account['account_id'] = $bank_account_id;
                        $account['item_type'] = 'expense';
                        $account['item_id'] = $added_expense['id'];
                        $account['action_type'] = 'Debited';
                        $account['amount'] = $payment_amount;
                        $account['description'] = 'Cheque Issued, Cheque Number - '.$cheque_number;

                        $this->admin_db->add_bank_account_logs($account);

                    }

                    if($payment_method == 'Bank Deposit'){
                        $cash_in_hand = $stock_details->cash_in_hand;
                        $new_cash_in_hand = $cash_in_hand - $payment_amount;

                        $this->admin_db->update_stock_details('cash_in_hand', $new_cash_in_hand);

                        $account['action_date'] = $data['date'];
                        $account['item_type'] = 'expense';
                        $account['item_id'] = $added_expense['id'];
                        $account['action_type'] = 'Debited';
                        $account['amount'] = $payment_amount;
                        $account['description'] = 'Bank Deposited To - '.$bank_details->bank_name.', Bank A/C No. - '.$data['third_party_account_number'];

                        $this->admin_db->add_cash_logs($account);

                    }

                    if($payment_method == 'Bank Transfer'){
                        $account_details = $this->admin_db->get_bank_account_by_id($bank_account_id);

                        $bank_balance = $account_details->bank_balance;
                        $new_bank_balance  = $bank_balance - $payment_amount;

                        $this->admin_db->update_bank_balance($bank_account_id, $new_bank_balance);

                        $account['account_id'] = $bank_account_id;
                        $account['item_type'] = 'expense';
                        $account['item_id'] = $added_expense['id'];
                        $account['action_type'] = 'Debited';
                        $account['amount'] = $payment_amount;
                        $account['description'] = 'Bank Tranfered To - '.$bank_details->bank_name.', Bank A/C No. - '.$data['third_party_account_number'];

                        $this->admin_db->add_bank_account_logs($account);

                    }

                    echo json_encode(array("message" => "Expense Added Successfully", "status" => "1", 'approval' => false));

                }else{

                    $expense['item_id'] = $added_expense['id'];
                    $expense['item_type'] = 'Expense';
                    $expense['amount'] = 'Rs. '.number_format($payment_amount,2,'.',',');
                    $expense['description'] = $data['description'];
                    $this->admin_db->add_approval_requests($expense);

                    echo json_encode(array("message" => "Expense Request Sent Successfully", "status" => "1", 'approval' => true));

                }

            }else{
                echo json_encode(array("message" => "An Error Occured while Adding Expense", "status" => "0"));

            }
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }
    }

    public function view_expense()
    {
        $id = $this->input->get('expense_id');
        
        $data['expense_details'] = $this->admin_db->get_expense_details_by_id($id);
        if($data['expense_details']->expense_status == 'Pending'){
            $data['approval_details'] = $this->admin_db->get_approval_by_item_type_id('Expense', $id);
        }
        
//        print_r($data['expense_details']->status);exit;
        
        $data['title'] = 'View Expense Details';
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/expense_details', $data);
        $this->load->view('dashboard/footer');
    }

    public function creditors()
    {
        $data['title'] = 'Creditors';
        
        $data['active'] = "active";
        $data['inactive'] = "";
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/creditors', $data);
        $this->load->view('dashboard/footer');
    }

    public function change_creditor_status()
    {
        $id = $this->input->get('id');
        $status = $this->input->get('status');
        
        $this->admin_db->change_creditor_status($id, $status);
        
        // 1 - active, 2 - inactive, 3 - deleted
        if ($status == 2) {

            $data['success_msg'] = 'Creditor Inactivated Successfully';
            $data['inactive'] = "active";
            $data['active'] = "";
            
        } else if ($status == 1) {

            $data['success_msg'] = 'Creditor Activated Successfully';
            $data['active'] = "active";
            $data['inactive'] = "";
            
        } else if ($status == 3) {

            $data['success_msg'] = 'Creditor Deleted Successfully';
            $data['active'] = "active";
            $data['inactive'] = "";
        }

        $data['title'] = 'Creditors';
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/creditors', $data);
        $this->load->view('dashboard/footer');

    }
    
    public function save_add_creditor_details()
    {
        $data['creditor_type'] = $this->input->post('creditor_type');
        $data['creditor_name'] = $this->input->post('creditor_name');
        $data['contact_number'] = $this->input->post('contact_num');
        
        header('Content-Type: application/json');
              
        $up_user = $this->admin_db->save_add_creditor_details($data);

        if($up_user == true){
            echo json_encode(array("message" => "Creditor Added Successfully", "status" => "1"));

        }else{
            echo json_encode(array("message" => "An Error Occured while Adding Creditor", "status" => "0"));

        }
    }

    public function view_creditor()
    {
        $id = $this->input->get('creditor_id');
        
        $data['creditor_details'] = $this->admin_db->get_creditor_by_id($id);
//        $data['tot_credit_sale_details'] = $this->admin_db->get_summery_debt_details_by_cus_id($id, null, 'Credit Sale');
//        $data['tot_gold_sale_details'] = $this->admin_db->get_summery_debt_details_by_cus_id($id, null, 'Gold Sale');
        
        $data['title'] = 'Creditor Profile';
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/creditor_profile', $data);
        $this->load->view('dashboard/footer');
    }
    
    public function save_edit_creditor_details()
    {
        $id = $this->input->post('creditor_id');
        $data['creditor_type'] = $this->input->post('creditor_type');
        $data['creditor_name'] = $this->input->post('creditor_name');
        $data['contact_number'] = $this->input->post('contact_num');
        
        header('Content-Type: application/json');
        
        $up_user = $this->admin_db->save_edit_creditor_details($id, $data);

        if($up_user['status'] == 1){
            echo json_encode(array("message" => "Creditor Details Successfully Edited", "status" => "1"));

        }else{
            echo json_encode(array("message" => "An Error Occured while Editing Creditor Details", "status" => "0"));

        }
    }

    public function approvals()
    {
        $data['title'] = 'Approvals';
        
        $data['pending'] = "active";
        $data['accepted'] = "";
        $data['rejected'] = "";
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/approvals', $data);
        $this->load->view('dashboard/footer');
    }

    public function change_approval_status()
    {
        $id = $this->input->get('id');
        $status = $this->input->get('status');
        $type = $this->input->get('type');
        
        $this->admin_db->change_approval_status($id, $status);
        
        $approval_details = $this->admin_db->get_approval_by_id($id);
        
        try {
            // Approved, Rejected
            if ($status == 'Approved') {

                $data['success_msg'] = 'Approval Approved Successfully';
                $data['pending'] = "";
                $data['accepted'] = "active";
                $data['rejected'] = "";

                if($type == '24K Rate Change'){
                    $data['rate_id'] = $rate_id = $approval_details->item_id;
                    $data['rate_amount'] = $data['amount'] = $approval_details->amount; 
                    $this->admin_db->update_current_rate($rate_id, $data);

                    $data['status'] = 'Approved'; 
                    $data['description'] = $approval_details->reason;        
                    $this->admin_db->save_add_rate_log($data);

                } else if($type == 'Expense'){

                    $this->admin_db->change_expense_status($approval_details->item_id, 'Approved');

                    $expense_details = $this->admin_db->get_expense_details_by_id($approval_details->item_id);
                    $expense_category_details = $this->admin_db->get_expense_category_details_by_id($expense_details->category_id);

                    if($expense_details->third_party_bank_id){
                        $bank_details = $this->admin_db->get_bank_by_id($expense_details->third_party_bank_id);
                    }

                    $data['payment_id'] = $approval_details->item_id;
                    $stock_details = $this->admin_db->get_stock_details();

                    if($expense_details->payment_method == 'Cash'){
                        $cash_in_hand = $stock_details->cash_in_hand;
                        $new_cash_in_hand = $cash_in_hand - $expense_details->amount;

                        $this->admin_db->update_stock_details('cash_in_hand', $new_cash_in_hand);

                        $account['action_date'] = date('Y-m-d');
                        $account['item_type'] = 'expense';
                        $account['item_id'] = $approval_details->item_id;
                        $account['action_type'] = 'Debited';
                        $account['amount'] = $expense_details->amount;
                        $account['description'] = 'Expense For '.$expense_category_details->category_name;

                        $this->admin_db->add_cash_logs($account);

                    }

                    if($expense_details->payment_method == 'Cheque'){
                        $account_details = $this->admin_db->get_bank_account_by_id($expense_details->account_id);

                        $bank_balance = $account_details->bank_balance;
                        $new_bank_balance  = $bank_balance - $expense_details->amount;

                        $this->admin_db->update_bank_balance($expense_details->account_id, $new_bank_balance);

                        $account['account_id'] = $expense_details->account_id;
                        $account['item_type'] = 'expense';
                        $account['item_id'] = $approval_details->item_id;
                        $account['action_type'] = 'Debited';
                        $account['amount'] = $expense_details->amount;
                        $account['description'] = 'Cheque Issued, Cheque Number - '.$expense_details->cheque_number;

                        $this->admin_db->add_bank_account_logs($account);

                    }

                    if($expense_details->payment_method == 'Bank Deposit'){
                        $cash_in_hand = $stock_details->cash_in_hand;
                        $new_cash_in_hand = $cash_in_hand - $expense_details->amount;

                        $this->admin_db->update_stock_details('cash_in_hand', $new_cash_in_hand);

                        $account['action_date'] = date('Y-m-d');
                        $account['item_type'] = 'expense';
                        $account['item_id'] = $approval_details->item_id;
                        $account['action_type'] = 'Debited';
                        $account['amount'] = $expense_details->amount;
                        $account['description'] = 'Bank Deposited To - '.$bank_details->bank_name.', Bank A/C No. - '.$expense_details->third_party_bank_id;

                        $this->admin_db->add_cash_logs($account);

                    }

                    if($expense_details->payment_method == 'Bank Transfer'){
                        $account_details = $this->admin_db->get_bank_account_by_id($expense_details->third_party_bank_id);

                        $bank_balance = $account_details->bank_balance;
                        $new_bank_balance  = $bank_balance - $expense_details->amount;

                        $this->admin_db->update_bank_balance($expense_details->third_party_bank_id, $new_bank_balance);

                        $account['account_id'] = $expense_details->third_party_bank_id;
                        $account['item_type'] = 'expense';
                        $account['item_id'] = $approval_details->item_id;
                        $account['action_type'] = 'Debited';
                        $account['amount'] = $expense_details->amount;
                        $account['description'] = 'Bank Tranfered To - '.$bank_details->bank_name.', Bank A/C No. - '.$data['third_party_account_number'];

                        $this->admin_db->add_bank_account_logs($account);

                    }
                } else if($type == 'Dxb Sale'){

                    $this->admin_db->change_sale_status($approval_details->item_id, 3);

                    $sale_details = $this->admin_db->get_sale_details_by_id($approval_details->item_id);

                    $customer_details = $this->admin_db->get_customer_by_id($sale_details->customer_id);

                    $customer_name = $customer_details->customer_name;
                    $customer_number = $customer_details->contact_number;
                    if($customer_details->send_sms == 1){
                        $send_msg = true;
                    }else{
                        $send_msg = false;
                    }

                    if($customer_number != '' && $send_msg){
                        $customer_number = preg_replace('/^0/','94',$customer_number); 

                        if($sale_details->sale_type == "Credit Sale"){
                            $total_sum = 'Rs. '.number_format($sale_details->bill_amount,2,'.',',');
                        }else if($sale_details->sale_type == "Gold Sale"){
                            $total_sum = number_format($sale_details->bill_amount,2,'.',',').' g';
                        }

                        $text = 'Hi '.$customer_name.'!<br>Thank you doing business of '.$total_sum.'<br>Ref. No : '.$sale_details->invoice_num.'<br>Bill Date : '.$sale_details->date.'<br><br>AVA Jewellers';

                        $user = "94777979679";
                        $password = "1739";
                        $text = urlencode($text);
                        $to = $customer_number;

                        $baseurl ="http://www.textit.biz/sendmsg";
                        $url = "$baseurl/?id=$user&pw=$password&to=$to&text=$text";
                        $ret = get_web_page($url);
                    }

                    if($customer_details->customer_type == 'Walk-In'){
                        $this->admin_db->change_customer_status($sale_details->customer_id, 4);
                    }

                    if($sale_details->sale_type == "Credit Sale"){
                        $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash + $sale_details->bill_amount;
                        $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold;
                    }else if($sale_details->sale_type == "Gold Sale"){
                        $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold + $sale_details->bill_amount;
                        $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash;
                    }

                    $amounts['over_paid_gold'] = $customer_details->over_paid_gold;
                    $amounts['over_paid_cash'] = $customer_details->over_paid_cash;

                    $this->admin_db->update_customer_accounts($sale_details->customer_id, $amounts);

                    $sale_items = $this->admin_db->get_sale_items_by_sale_id($sale_details->id);

                    $total_sale_grams = 0;

                    foreach($sale_items as $sale_item){

                        $total_sale_grams += $sale_item['sales_grams'];

                    }

                    $stock_details = $this->admin_db->get_stock_details();

                    $tt_gold_in_hand = $stock_details->tt_gold_in_hand;
                    $new_tt_gold_in_hand = $tt_gold_in_hand - $total_sale_grams;

                    $this->admin_db->update_stock_details('tt_gold_in_hand', $new_tt_gold_in_hand);

                    $account['item_type'] = 'sale';
                    $account['item_id'] = $sale_details->id;
                    $account['action_type'] = 'Debited';
                    $account['amount'] = $total_sale_grams;
                    $account['description'] = 'Sold To ' .$customer_details->customer_name;

                    $this->admin_db->add_22k_gold_logs($account);
                    
                    $payment_items = $this->admin_db->get_payment_items_by_sale_id($approval_details->item_id);
                    
                    if($payment_items){
                        foreach($payment_items as $payment_item){
                            
                            $customer_details = $this->admin_db->get_customer_by_id($sale_details->customer_id);
                            
                            if($sale_details->balance_amount < 0){
                                if($customer_details->status == 4 && $customer_details->customer_type == 'Walk-In'){
                                    $this->admin_db->change_customer_status($sale_details->customer_id, 1);
                                }

                                $this->admin_db->change_sale_status($sale_details->id, 1);
                            }else{

                                $this->admin_db->change_sale_status($sale_details->id, 2);
                            }
                            
                            $amounts = array();
                            if($payment_item['payment_method'] == "Gold"){

                                if($sale_details->balance_amount < 0){

                                    $new_over_paid_gold = $customer_details->over_paid_gold + abs($sale_details->balance_amount);
                                    $amounts['over_paid_gold'] = $new_over_paid_gold;

                                }else{

                                    $amounts['over_paid_gold'] = $customer_details->over_paid_gold;

                                }
                                

                                $amounts['over_paid_cash'] = $customer_details->over_paid_cash;
                                $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold - $payment_item['paid_amount'];
                                $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash;

                            }elseif($payment_item['payment_method'] == "Over Paid Gold"){

                                $new_over_paid_gold = $customer_details->over_paid_gold - $payment_item['paid_amount'];
                                $amounts['over_paid_gold'] = $new_over_paid_gold;

                                if($sale_details->balance_amount < 0){

                                    $over_paid_gold = $customer_details->over_paid_gold - $payment_item['paid_amount'];
                                    $new_over_paid_gold = $over_paid_gold + ($payment_item['paid_amount'] - $sale_details->balance_amount);

                                    $amounts['over_paid_gold'] = $new_over_paid_gold;

                                }

                                $amounts['over_paid_cash'] = $customer_details->over_paid_cash;
                                $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold - $payment_item['paid_amount'];
                                $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash;

                            }elseif($payment_item['payment_method'] == "Over Paid Cash"){

                                $new_over_paid_cash = $customer_details->over_paid_cash - $payment_item['paid_amount'];
                                $amounts['over_paid_cash'] = $new_over_paid_cash;

                                if($sale_details->balance_amount < 0){

                                    $over_paid_cash = $customer_details->over_paid_cash - $payment_item['paid_amount'];
                                    $new_over_paid_cash = $over_paid_cash + ($payment_item['paid_amount'] - $sale_details->balance_amount);

                                    $amounts['over_paid_cash'] = $new_over_paid_cash;

                                }

                                $amounts['over_paid_gold'] = $customer_details->over_paid_gold;
                                $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold;
                                $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash - $payment_item['paid_amount'];

                            }else{

                                if($sale_details->balance_amount < 0){

                                    $new_over_paid_cash = $customer_details->over_paid_cash + abs($sale_details->balance_amount);
                                    $amounts['over_paid_cash'] = $new_over_paid_cash;

                                }else{

                                    $amounts['over_paid_cash'] = $customer_details->over_paid_cash;

                                }

                                $amounts['over_paid_gold'] = $customer_details->over_paid_gold;
                                $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold;
                                $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash - $payment_item['paid_amount'];

                            }
                              
                            $this->admin_db->update_customer_accounts($sale_details->customer_id, $amounts);
                               
                            $stock_details = $this->admin_db->get_stock_details();

                            if($payment_item['payment_method'] == 'Cash'){
                                $cash_in_hand = $stock_details->cash_in_hand;
                                $new_cash_in_hand = $cash_in_hand + $payment_item['paid_amount'];

                                $this->admin_db->update_stock_details('cash_in_hand', $new_cash_in_hand);

                                $account['action_date'] = $data['date'];
                                $account['item_type'] = 'receipt amount';
                                $account['item_id'] = $payment_item['payment_id'];
                                $account['action_type'] = 'Credited';
                                $account['amount'] = $payment_item['paid_amount'];
                                $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                                $this->admin_db->add_cash_logs($account);

                            }

                            if($payment_item['payment_method'] == 'Cheque'){
                                $cheque['bank_id'] = $data['cheq_bank'];
                                $cheque['payment_id'] = $payment_item['payment_id'];
                                $cheque['customer_id'] = $sale_details->customer_id;
                                $cheque['cheque_type'] = 'Sale';
                                $cheque['cheque_number'] = $data['cheq_cheque_number'];
                                $cheque['cheque_amount'] = $payment_item['paid_amount'];
                                $cheque['deposit_date'] = $data['cheq_deposit_date'];

                                $this->admin_db->add_cheque_details($cheque);

                            }

                            if($payment_item['payment_method'] == 'Gold'){
                                $tf_gold_in_hand = $stock_details->tf_gold_in_hand;
                                $new_tf_gold_in_hand = $tf_gold_in_hand + $payment_item['paid_amount'];

                                $this->admin_db->update_stock_details('tf_gold_in_hand', $new_tf_gold_in_hand);

                                $account['item_type'] = 'receipt amount';
                                $account['item_id'] = $payment_item['payment_id'];
                                $account['action_type'] = 'Credited';
                                $account['amount'] = $payment_item['paid_amount'];
                                $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                                $this->admin_db->add_24k_gold_logs($account);

                            }

                            if($payment_item['payment_method'] == 'Bank Deposit'){
                                $account_details = $this->admin_db->get_bank_account_by_id($payment_item['account_id']);

                                $bank_balance = $account_details->bank_balance;
                                $new_bank_balance  = $bank_balance + $payment_item['paid_amount'];

                                $this->admin_db->update_bank_balance($payment_item['account_id'], $new_bank_balance);

                                $account['account_id'] = $payment_item['account_id'];
                                $account['item_type'] = 'receipt amount';
                                $account['item_id'] = $payment_item['payment_id'];
                                $account['action_type'] = 'Credited';
                                $account['amount'] = $payment_item['paid_amount'];
                                $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                                $this->admin_db->add_bank_account_logs($account);

                            }
                        }
                    }

                } else if($type == 'Box Sale'){

                    $this->admin_db->change_box_sale_status($approval_details->item_id, 3);

                    $sale_details = $this->admin_db->get_box_sale_details_by_id($approval_details->item_id);

                    $customer_details = $this->admin_db->get_customer_by_id($sale_details->customer_id);

                    $customer_name = $customer_details->customer_name;
                    $customer_number = $customer_details->contact_number;
                    if($customer_details->send_sms == 1){
                        $send_msg = true;
                    }else{
                        $send_msg = false;
                    }

                    if($customer_number != '' && $send_msg){
                        $customer_number = preg_replace('/^0/','94',$customer_number); 

                        if($sale_details->sale_type == "Credit Sale"){
                            $total_sum = 'Rs. '.number_format($sale_details->bill_amount,2,'.',',');
                        }else if($sale_details->sale_type == "Gold Sale"){
                            $total_sum = number_format($sale_details->bill_amount,2,'.',',').' g';
                        }

                        $text = 'Hi '.$customer_name.'!<br>Thank you doing business of '.$total_sum.'<br>Ref. No : '.$sale_details->invoice_num.'<br>Bill Date : '.$sale_details->date.'<br><br>AVA Jewellers';

                        $user = "94777979679";
                        $password = "1739";
                        $text = urlencode($text);
                        $to = $customer_number;

                        $baseurl ="http://www.textit.biz/sendmsg";
                        $url = "$baseurl/?id=$user&pw=$password&to=$to&text=$text";
                        $ret = get_web_page($url);
                    }

                    if($customer_details->customer_type == 'Walk-In'){
                        $this->admin_db->change_customer_status($sale_details->customer_id, 4);
                    }

                    if($sale_details->sale_type == "Credit Sale"){
                        $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash + $sale_details->bill_amount;
                        $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold;
                    }else if($sale_details->sale_type == "Gold Sale"){
                        $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold + $sale_details->bill_amount;
                        $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash;
                    }

                    $amounts['box_over_paid_gold'] = $customer_details->box_over_paid_gold;
                    $amounts['box_over_paid_cash'] = $customer_details->box_over_paid_cash;

                    $this->admin_db->update_customer_box_accounts($sale_details->customer_id, $amounts);

                    $sale_items = $this->admin_db->get_box_sale_items_by_box_sale_id($sale_details->id);

                    $total_sale_grams = 0;

                    foreach($sale_items as $sale_item){

                        $total_sale_grams += $sale_item['sales_grams'];

                    }

                    $stock_details = $this->admin_db->get_stock_details();

                    $box_tt_gold_in_hand = $stock_details->box_tt_gold_in_hand;
                    $new_box_tt_gold_in_hand = $box_tt_gold_in_hand - $total_sale_grams;

                    $this->admin_db->update_stock_details('box_tt_gold_in_hand', $new_box_tt_gold_in_hand);

                    $account['item_type'] = 'sale';
                    $account['item_id'] = $sale_details->id;
                    $account['action_type'] = 'Debited';
                    $account['amount'] = $total_sale_grams;
                    $account['description'] = 'Sold To ' .$customer_details->customer_name;

                    $this->admin_db->add_box_22k_gold_logs($account);
                    
                    $payment_items = $this->admin_db->get_box_payment_items_by_sale_id($approval_details->item_id);
                    
                    
                    
                    if($payment_items){
                        foreach($payment_items as $payment_item){
                            
                            $customer_details = $this->admin_db->get_customer_by_id($sale_details->customer_id);
                            
                            if($sale_details->balance_amount < 0){
                                if($customer_details->status == 4 && $customer_details->customer_type == 'Walk-In'){
                                    $this->admin_db->change_customer_status($sale_details->customer_id, 1);
                                }

                                $this->admin_db->change_box_sale_status($sale_details->id, 1);
                            }else{

                                $this->admin_db->change_box_sale_status($sale_details->id, 2);
                            }
                            
                            $amounts = array();
                            if($payment_item['payment_method'] == "Gold"){

                                if($sale_details->balance_amount < 0){

                                    $new_over_paid_gold = $customer_details->box_over_paid_gold + abs($sale_details->balance_amount);
                                    $amounts['box_over_paid_gold'] = $new_over_paid_gold;

                                }else{

                                    $amounts['box_over_paid_gold'] = $customer_details->box_over_paid_gold;

                                }
                                

                                $amounts['box_over_paid_cash'] = $customer_details->box_over_paid_cash;
                                $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold - $payment_item['paid_amount'];
                                $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash;

                            }elseif($payment_item['payment_method'] == "Over Paid Gold"){

                                $new_over_paid_gold = $customer_details->box_over_paid_gold - $payment_item['paid_amount'];
                                $amounts['box_over_paid_gold'] = $new_over_paid_gold;

                                if($sale_details->balance_amount < 0){

                                    $over_paid_gold = $customer_details->box_over_paid_gold - $payment_item['paid_amount'];
                                    $new_over_paid_gold = $over_paid_gold + ($payment_item['paid_amount'] - $sale_details->balance_amount);

                                    $amounts['box_over_paid_gold'] = $new_over_paid_gold;

                                }

                                $amounts['box_over_paid_cash'] = $customer_details->box_over_paid_cash;
                                $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold - $payment_item['paid_amount'];
                                $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash;

                            }elseif($payment_item['payment_method'] == "Over Paid Cash"){

                                $new_over_paid_cash = $customer_details->box_over_paid_cash - $payment_item['paid_amount'];
                                $amounts['box_over_paid_cash'] = $new_over_paid_cash;

                                if($sale_details->balance_amount < 0){

                                    $over_paid_cash = $customer_details->box_over_paid_cash - $payment_item['paid_amount'];
                                    $new_over_paid_cash = $over_paid_cash + ($payment_item['paid_amount'] - $sale_details->balance_amount);

                                    $amounts['box_over_paid_cash'] = $new_over_paid_cash;

                                }

                                $amounts['box_over_paid_gold'] = $customer_details->box_over_paid_gold;
                                $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold;
                                $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash - $payment_item['paid_amount'];

                            }else{

                                if($sale_details->balance_amount < 0){

                                    $new_over_paid_cash = $customer_details->box_over_paid_cash + abs($sale_details->balance_amount);
                                    $amounts['box_over_paid_cash'] = $new_over_paid_cash;

                                }else{

                                    $amounts['box_over_paid_cash'] = $customer_details->box_over_paid_cash;

                                }

                                $amounts['box_over_paid_gold'] = $customer_details->box_over_paid_gold;
                                $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold;
                                $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash - $payment_item['paid_amount'];

                            }
                              
                            $this->admin_db->update_customer_box_accounts($sale_details->customer_id, $amounts);
                               
                            $stock_details = $this->admin_db->get_stock_details();

                            if($payment_item['payment_method'] == 'Cash'){
                                $cash_in_hand = $stock_details->box_cash_in_hand;
                                $new_cash_in_hand = $cash_in_hand + $payment_item['paid_amount'];

                                $this->admin_db->update_stock_details('box_cash_in_hand', $new_cash_in_hand);

                                $account['action_date'] = $payment_item['date'];
                                $account['item_type'] = 'receipt amount';
                                $account['item_id'] = $payment_item['box_payment_id'];
                                $account['action_type'] = 'Credited';
                                $account['amount'] = $payment_item['paid_amount'];
                                $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                                $this->admin_db->add_box_cash_logs($account);

                            }

                            if($payment_item['payment_method'] == 'Cheque'){
                                $cheque['bank_id'] = $data['cheq_bank'];
                                $cheque['payment_id'] = $payment_item['box_payment_id'];
                                $cheque['customer_id'] = $sale_details->customer_id;
                                $cheque['cheque_type'] = 'Box Sale';
                                $cheque['cheque_number'] = $data['cheq_cheque_number'];
                                $cheque['cheque_amount'] = $payment_item['paid_amount'];
                                $cheque['deposit_date'] = $data['cheq_deposit_date'];

                                $this->admin_db->add_cheque_details($cheque);

                            }

                            if($payment_item['payment_method'] == 'Gold'){
                                $box_tf_gold_in_hand = $stock_details->box_tf_gold_in_hand;
                                $new_box_tf_gold_in_hand = $box_tf_gold_in_hand + $payment_item['paid_amount'];

                                $this->admin_db->update_stock_details('box_tf_gold_in_hand', $new_box_tf_gold_in_hand);

                                $account['item_type'] = 'receipt amount';
                                $account['item_id'] = $payment_item['box_payment_id'];
                                $account['action_type'] = 'Credited';
                                $account['amount'] = $payment_item['paid_amount'];
                                $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                                $this->admin_db->add_box_24k_gold_logs($account);

                            }

                            if($payment_item['payment_method'] == 'Bank Deposit'){
                                $account_details = $this->admin_db->get_bank_account_by_id($payment_item['account_id']);

                                $bank_balance = $account_details->bank_balance;
                                $new_bank_balance  = $bank_balance + $payment_item['paid_amount'];

                                $this->admin_db->update_bank_balance($payment_item['account_id'], $new_bank_balance);

                                $account['account_id'] = $payment_item['account_id'];
                                $account['item_type'] = 'receipt amount';
                                $account['item_id'] = $payment_item['box_payment_id'];
                                $account['action_type'] = 'Credited';
                                $account['amount'] = $payment_item['paid_amount'];
                                $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                                $this->admin_db->add_box_bank_account_logs($account);

                            }
                        }
                    }

                } else if ($type == 'UNA Purchase') {

                    $this->admin_db->change_una_status($approval_details->item_id, 3);

                    $una_details = $this->admin_db->get_una_details_by_id($approval_details->item_id);

                    $creditor_details = $this->admin_db->get_creditor_by_id($una_details->creditor_id);

                    $amounts['una_amount'] = $creditor_details->una_amount + $una_details->lkr_amount;
                    $amounts['una_bal_amount'] = $creditor_details->una_bal_amount + $una_details->lkr_amount;
                    $amounts['credit_amount'] = $creditor_details->amount;
                    $amounts['credit_bal_amount'] = $creditor_details->bal_amount;

                    $this->admin_db->update_creditor_amounts($una_details->creditor_id, $amounts);

                    $data['creditor_id'] = $una_details->creditor_id;
                    $data['item_type'] = 'UNA Purchase';
                    $data['item_id'] = $approval_details->item_id;
                    $data['amount'] = $una_details->lkr_amount;
                    $data['description'] = NULL;

                    $this->admin_db->add_creditor_accounts($data);

                } else if($type == '24K Sale'){

                    $this->admin_db->change_24k_sale_status($approval_details->item_id, 3);

                    $sale_details = $this->admin_db->get_24k_sale_details_by_id($approval_details->item_id);

                    $customer_details = $this->admin_db->get_24k_customer_by_id($sale_details->customer_id);

                    $customer_name = $customer_details->customer_name;
                    $customer_number = $customer_details->contact_number;
                    if($customer_details->send_sms == 1){
                        $send_msg = true;
                    }else{
                        $send_msg = false;
                    }

                    if($customer_number != '' && $send_msg){
                        $customer_number = preg_replace('/^0/','94',$customer_number); 

                        $total_sum = 'Rs. '.number_format($sale_details->bill_amount,2,'.',',');

                        $text = 'Hi '.$customer_name.'!<br>Thank you doing business of '.$total_sum.'<br>Ref. No : '.$sale_details->invoice_num.'<br>Bill Date : '.$sale_details->date.'<br><br>AVA Jewellers';

                        $user = "94777979679";
                        $password = "1739";
                        $text = urlencode($text);
                        $to = $customer_number;

                        $baseurl ="http://www.textit.biz/sendmsg";
                        $url = "$baseurl/?id=$user&pw=$password&to=$to&text=$text";
                        $ret = get_web_page($url);
                    }

                    if($sale_details->sale_type == '24K DXB Sale'){

                        $tot_amount_gold = $customer_details->dxb_gold_tot_amount + $sale_details->gold_amount;
                        $tot_amount_cash = $customer_details->dxb_cash_tot_amount + $sale_details->bill_amount;
                        $balance_amount = $customer_details->dxb_balance_amount + $sale_details->bill_amount;

                        $amounts['dxb_gold_tot_amount'] = $tot_amount_gold;
                        $amounts['dxb_cash_tot_amount'] = $tot_amount_cash;
                        $amounts['dxb_paid_amount'] = $customer_details->dxb_paid_amount;

                        $amounts['dxb_balance_amount'] = $balance_amount;

                        $this->admin_db->update_24k_customer_dxb_accounts($sale_details->customer_id, $amounts);

                    }elseif($sale_details->sale_type == '24K BOX Sale'){

                        $tot_amount_gold = $customer_details->box_gold_tot_amount + $sale_details->gold_amount;
                        $tot_amount_cash = $customer_details->box_cash_tot_amount + $sale_details->bill_amount;
                        $balance_amount = $customer_details->box_balance_amount + $sale_details->bill_amount;

                        $amounts['box_gold_tot_amount'] = $tot_amount_gold;
                        $amounts['box_cash_tot_amount'] = $tot_amount_cash;
                        $amounts['box_paid_amount'] = $customer_details->box_paid_amount;

                        $amounts['box_balance_amount'] = $balance_amount;

                        $this->admin_db->update_24k_customer_box_accounts($sale_details->customer_id, $amounts);

                    }

                    $sale_items = $this->admin_db->get_24k_sale_items_by_sale_id($sale_details->id);

                    $total_sale_grams = 0;

                    foreach($sale_items as $sale_item){

                        $total_sale_grams += $sale_item['sales_grams'];

                    }

                    $stock_details = $this->admin_db->get_stock_details();

                    $tf_gold_in_hand = $stock_details->tf_gold_in_hand;
                    $new_tf_gold_in_hand = $tf_gold_in_hand - $total_sale_grams;

                    $this->admin_db->update_stock_details('tf_gold_in_hand', $new_tf_gold_in_hand);

                    $account['item_type'] = 'sale';
                    $account['item_id'] = $sale_details->id;
                    $account['action_type'] = 'Debited';
                    $account['amount'] = $total_sale_grams;
                    $account['description'] = 'Sold To ' .$customer_details->customer_name;

                    $this->admin_db->add_24k_gold_logs($account);
                    
                    $payment_items = $this->admin_db->get_24k_payment_items_by_sale_id($approval_details->item_id);
                    
                    if($payment_items){
                        foreach($payment_items as $payment_item){
                            
                            $customer_details = $this->admin_db->get_24k_customer_by_id($sale_details->customer_id);
                            
                            if($payment_item['payment_method'] != 'Cheque'){
                                if($sale_details->balance_amount < 0){

                                    $amounts['balance_amount'] = 0.00;
                                    $amounts['paid_amount'] = $payment_item['paid_amount'];

                                    $this->admin_db->update_24k_sale_bal_amount($sale_details->id, $amounts);
                                }else{

                                    $amounts['balance_amount'] = $sale_details->balance_amount;
                                    $amounts['paid_amount'] = $payment_item['paid_amount'];

                                    $this->admin_db->update_24k_sale_bal_amount($sale_details->id, $amounts);

                                }
                            }

                            if($sale_details->balance_amount <= 0){ 

                                $this->admin_db->change_24k_sale_status($sale_details->id, 1);
                            }else{

                                $this->admin_db->change_24k_sale_status($sale_details->id, 2);
                            }
                            
                            if($payment_item['payment_method'] == "Over Paid Cash"){

                                $new_over_paid_cash = $customer_details->over_paid_cash - $payment_item['paid_amount'];
                                $amounts['over_paid_cash'] = $new_over_paid_cash;

                                if($sale_details->balance_amount < 0){

                                    $over_paid_cash = $customer_details->over_paid_cash - $payment_item['paid_amount'];
                                    $new_over_paid_cash = $over_paid_cash + ($payment_item['paid_amount'] - $sale_details->balance_amount);

                                    $amounts['over_paid_cash'] = $new_over_paid_cash;

                                }

                            }else{

                                if($sale_details->balance_amount < 0){

                                    $new_over_paid_cash = $customer_details->over_paid_cash + abs($sale_details->balance_amount);
                                    $amounts['over_paid_cash'] = $new_over_paid_cash;

                                }else{

                                    $amounts['over_paid_cash'] = $customer_details->over_paid_cash;

                                }

                            }

                            if($sale_details->sale_type == '24K DXB Sale'){
                                
                                $amounts['dxb_gold_tot_amount'] = $customer_details->dxb_gold_tot_amount;
                                $amounts['dxb_cash_tot_amount'] = $customer_details->dxb_cash_tot_amount;
                                $amounts['dxb_paid_amount'] = $customer_details->dxb_paid_amount + $payment_item['paid_amount'];

                                $amounts['dxb_balance_amount'] = $customer_details->dxb_balance_amount - $payment_item['paid_amount'];

                                $this->admin_db->update_24k_customer_dxb_accounts($sale_details->customer_id, $amounts);

                            }elseif($sale_details->sale_type == '24K BOX Sale'){

                                $amounts['box_gold_tot_amount'] = $customer_details->box_gold_tot_amount;
                                $amounts['box_cash_tot_amount'] = $customer_details->box_cash_tot_amount;
                                $amounts['box_paid_amount'] = $customer_details->box_paid_amount + $payment_item['paid_amount'];

                                $amounts['box_balance_amount'] = $customer_details->box_balance_amount - $payment_item['paid_amount'];

                                $this->admin_db->update_24k_customer_box_accounts($sale_details->customer_id, $amounts);

                            }
                            
                            $stock_details = $this->admin_db->get_stock_details();

                            if($payment_item['payment_method'] == 'Cash'){
                                $cash_in_hand = $stock_details->cash_in_hand;
                                $new_cash_in_hand = $cash_in_hand + $payment_item['paid_amount'];

                                $this->admin_db->update_stock_details('cash_in_hand', $new_cash_in_hand);

                                $account['action_date'] = $payment_item['date'];
                                $account['item_type'] = 'receipt amount';
                                $account['item_id'] = $payment_item['payment_id'];
                                $account['action_type'] = 'Credited';
                                $account['amount'] = $payment_item['paid_amount'];
                                $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                                $this->admin_db->add_cash_logs($account);

                            }

                            if($payment_item['payment_method'] == 'Cheque'){
                                $cheque['bank_id'] = $data['cheq_bank'];
                                $cheque['payment_id'] = $payment_item['payment_id'];
                                $cheque['customer_id'] = $sale_details->customer_id;
                                $cheque['cheque_type'] = '24K Sale';
                                $cheque['cheque_number'] = $data['cheq_cheque_number'];
                                $cheque['cheque_amount'] = $payment_item['paid_amount'];
                                $cheque['deposit_date'] = $data['cheq_deposit_date'];

                                $this->admin_db->add_cheque_details($cheque);

                            }

                            if($payment_item['payment_method'] == 'Bank Deposit'){
                                $account_details = $this->admin_db->get_bank_account_by_id($payment_item['account_id']);

                                $bank_balance = $account_details->bank_balance;
                                $new_bank_balance  = $bank_balance + $payment_item['paid_amount'];

                                $this->admin_db->update_bank_balance($payment_item['account_id'], $new_bank_balance);

                                $account['account_id'] = $payment_item['account_id'];
                                $account['item_type'] = 'receipt amount';
                                $account['item_id'] = $payment_item['payment_id'];
                                $account['action_type'] = 'Credited';
                                $account['amount'] = $payment_item['paid_amount'];
                                $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                                $this->admin_db->add_bank_account_logs($account);

                            }
                        }
                    }

                } else if($type == 'Return Dxb Sale'){

                    $this->admin_db->change_return_sale_status($approval_details->item_id, 1);
//                    
                    $return_sale_details = $this->admin_db->get_returned_sale_details_by_id($approval_details->item_id);
                    $sale_details = $this->admin_db->get_sale_details_by_id($return_sale_details->sale_id);
                    $customer_details = $this->admin_db->get_customer_by_id($return_sale_details->customer_id);
                    
                    $return_sale_items = $this->admin_db->get_returned_sale_items_for_approvals($approval_details->item_id);
//
                    $sale_amounts['balance_amount'] = $sale_details->balance_amount - $return_sale_details->amount;
                    $sale_amounts['return_sale_amount'] = $sale_details->return_sale_amount + $return_sale_details->amount;

                    if($sale_amounts['balance_amount'] <= 0){

                        if($customer_details->status == 4 && $customer_details->customer_type == 'Walk-In'){
                            $this->admin_db->change_customer_status($return_sale_details->customer_id, 1);
                        }

                        $this->admin_db->change_sale_status($return_sale_details->sale_id, 1);
                    }else{

                        $this->admin_db->change_sale_status($return_sale_details->sale_id, 2);
                    }

                    $this->admin_db->update_return_sale_amounts($return_sale_details->sale_id, $sale_amounts);
                    
                    

                    if($return_sale_details->sale_type == "Credit Sale"){

                        if($customer_details->debt_amount_cash == '' || $customer_details->debt_amount_cash == 0.00){
                            $amounts['over_paid_cash'] = $customer_details->over_paid_cash + $return_sale_details->amount;
                            $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash;
                        }else{
                            $amounts['over_paid_cash'] = $customer_details->over_paid_cash;
                            $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash - $return_sale_details->amount;
                        }

                        $amounts['over_paid_gold'] = $customer_details->over_paid_gold;
                        $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold;

                    }else if($return_sale_details->sale_type == "Gold Sale"){

                        if($customer_details->debt_amount_gold == '' || $customer_details->debt_amount_gold == 0.00){
                            $amounts['over_paid_gold'] = $customer_details->over_paid_gold + $return_sale_details->amount;
                            $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold;
                        }else{
                            $amounts['over_paid_gold'] = $customer_details->over_paid_gold;
                            $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold - $return_sale_details->amount;
                        }

                        $amounts['over_paid_cash'] = $customer_details->over_paid_cash;
                        $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash;
                    }

                    $this->admin_db->update_customer_accounts($return_sale_details->customer_id, $amounts);
                    
                    $total_sale_grams = 0;
                    
                    foreach($return_sale_items as $return_sale_item){
                        $sales_grams = $return_sale_item['sales_grams'];
                        $actual_grams = $return_sale_item['actual_grams'];
                        
                        $total_sale_grams += $sales_grams;

                        $actual_grams_after_ret = $actual_grams - $sales_grams;

                        $this->admin_db->update_sale_item_actual_grams($return_sale_item['item_id'], $actual_grams_after_ret); 

                    }

                    $stock_details = $this->admin_db->get_stock_details();

                    $tt_gold_in_hand = $stock_details->tt_gold_in_hand;
                    $new_tt_gold_in_hand = $tt_gold_in_hand + $total_sale_grams;

                    $this->admin_db->update_stock_details('tt_gold_in_hand', $new_tt_gold_in_hand);

                    $account['item_type'] = 'return sale';
                    $account['item_id'] = $approval_details->item_id;
                    $account['action_type'] = 'Credited';
                    $account['amount'] = $total_sale_grams;
                    $account['description'] = 'Returned Sale From '.$customer_details->customer_name;

                    $this->admin_db->add_22k_gold_logs($account);

                    
                }

            } else if ($status == 'Rejected') {

                $data['success_msg'] = 'Approval Rejected Successfully';
                $data['pending'] = "";
                $data['accepted'] = "";
                $data['rejected'] = "active";

                if($type == '24K Rate Change'){
                    $data['rate_id'] = $approval_details->item_id;
                    $data['amount'] = $approval_details->amount; 

                    $data['status'] = 'Rejected'; 
                    $data['description'] = $approval_details->reason;        
                    $this->admin_db->save_add_rate_log($data);

                }else if($type == 'Expense'){

                    $this->admin_db->change_expense_status($approval_details->item_id, 'Rejected');

                } else if($type == 'Dxb Sale'){

                    $this->admin_db->change_sale_status($approval_details->item_id, 5);

                } else if($type == 'Box Sale'){

                    $this->admin_db->change_box_sale_status($approval_details->item_id, 5);

                } else if($type == 'UNA Purchase'){

                    $this->admin_db->change_una_status($approval_details->item_id, 5);

                } else if($type == '24K Sale'){

                    $this->admin_db->change_24k_sale_status($approval_details->item_id, 5);

                } else if($type == 'Return Dxb Sale'){

                    $this->admin_db->change_return_sale_status($approval_details->item_id, 3);

                }

            } 
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }

        $data['title'] = 'Approvals';
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/approvals', $data);
        $this->load->view('dashboard/footer');

    }

    public function change_this_approval_status()
    {
        $id = $this->input->get('id');
        $status = $this->input->get('status');
        $type = $this->input->get('type');
        
        $this->admin_db->change_approval_status($id, $status);
        
        $approval_details = $this->admin_db->get_approval_by_id($id);
        
        try {
        // Approved, Rejected
            if ($status == 'Approved') {

                $data['success_msg'] = 'Approval Approved Successfully';
                $data['pending'] = "";
                $data['accepted'] = "active";
                $data['rejected'] = "";

                if($type == '24K Rate Change'){
                    $data['rate_id'] = $rate_id = $approval_details->item_id;
                    $data['rate_amount'] = $data['amount'] = $approval_details->amount; 
                    $this->admin_db->update_current_rate($rate_id, $data);

                    $data['status'] = 'Approved'; 
                    $data['description'] = $approval_details->reason;        
                    $this->admin_db->save_add_rate_log($data);

                } else if($type == 'Expense'){

                    $this->admin_db->change_expense_status($approval_details->item_id, 'Approved');

                    $expense_details = $this->admin_db->get_expense_details_by_id($approval_details->item_id);
                    $expense_category_details = $this->admin_db->get_expense_category_details_by_id($expense_details->category_id);

                    if($expense_details->third_party_bank_id){
                        $bank_details = $this->admin_db->get_bank_by_id($expense_details->third_party_bank_id);
                    }

                    $data['payment_id'] = $approval_details->item_id;
                    $stock_details = $this->admin_db->get_stock_details();

                    if($expense_details->payment_method == 'Cash'){
                        $cash_in_hand = $stock_details->cash_in_hand;
                        $new_cash_in_hand = $cash_in_hand - $expense_details->amount;

                        $this->admin_db->update_stock_details('cash_in_hand', $new_cash_in_hand);

                        $account['action_date'] = date('Y-m-d');
                        $account['item_type'] = 'expense';
                        $account['item_id'] = $approval_details->item_id;
                        $account['action_type'] = 'Debited';
                        $account['amount'] = $expense_details->amount;
                        $account['description'] = 'Expense For '.$expense_category_details->category_name;

                        $this->admin_db->add_cash_logs($account);

                    }

                    if($expense_details->payment_method == 'Cheque'){
                        $account_details = $this->admin_db->get_bank_account_by_id($expense_details->account_id);

                        $bank_balance = $account_details->bank_balance;
                        $new_bank_balance  = $bank_balance - $expense_details->amount;

                        $this->admin_db->update_bank_balance($expense_details->account_id, $new_bank_balance);

                        $account['account_id'] = $expense_details->account_id;
                        $account['item_type'] = 'expense';
                        $account['item_id'] = $approval_details->item_id;
                        $account['action_type'] = 'Debited';
                        $account['amount'] = $expense_details->amount;
                        $account['description'] = 'Cheque Issued, Cheque Number - '.$expense_details->cheque_number;

                        $this->admin_db->add_bank_account_logs($account);

                    }

                    if($expense_details->payment_method == 'Bank Deposit'){
                        $cash_in_hand = $stock_details->cash_in_hand;
                        $new_cash_in_hand = $cash_in_hand - $expense_details->amount;

                        $this->admin_db->update_stock_details('cash_in_hand', $new_cash_in_hand);

                        $account['action_date'] = date('Y-m-d');
                        $account['item_type'] = 'expense';
                        $account['item_id'] = $approval_details->item_id;
                        $account['action_type'] = 'Debited';
                        $account['amount'] = $expense_details->amount;
                        $account['description'] = 'Bank Deposited To - '.$bank_details->bank_name.', Bank A/C No. - '.$expense_details->third_party_bank_id;

                        $this->admin_db->add_cash_logs($account);

                    }

                    if($expense_details->payment_method == 'Bank Transfer'){
                        $account_details = $this->admin_db->get_bank_account_by_id($expense_details->third_party_bank_id);

                        $bank_balance = $account_details->bank_balance;
                        $new_bank_balance  = $bank_balance - $expense_details->amount;

                        $this->admin_db->update_bank_balance($expense_details->third_party_bank_id, $new_bank_balance);

                        $account['account_id'] = $expense_details->third_party_bank_id;
                        $account['item_type'] = 'expense';
                        $account['item_id'] = $approval_details->item_id;
                        $account['action_type'] = 'Debited';
                        $account['amount'] = $expense_details->amount;
                        $account['description'] = 'Bank Tranfered To - '.$bank_details->bank_name.', Bank A/C No. - '.$data['third_party_account_number'];

                        $this->admin_db->add_bank_account_logs($account);

                    }
                } else if($type == 'Dxb Sale'){

                    $this->admin_db->change_sale_status($approval_details->item_id, 3);

                    $sale_details = $this->admin_db->get_sale_details_by_id($approval_details->item_id);

                    $customer_details = $this->admin_db->get_customer_by_id($sale_details->customer_id);

                    $customer_name = $customer_details->customer_name;
                    $customer_number = $customer_details->contact_number;
                    if($customer_details->send_sms == 1){
                        $send_msg = true;
                    }else{
                        $send_msg = false;
                    }

                    if($customer_number != '' && $send_msg){
                        $customer_number = preg_replace('/^0/','94',$customer_number); 

                        if($sale_details->sale_type == "Credit Sale"){
                            $total_sum = 'Rs. '.number_format($sale_details->bill_amount,2,'.',',');
                        }else if($sale_details->sale_type == "Gold Sale"){
                            $total_sum = number_format($sale_details->bill_amount,2,'.',',').' g';
                        }

                        $text = 'Hi '.$customer_name.'!<br>Thank you doing business of '.$total_sum.'<br>Ref. No : '.$sale_details->invoice_num.'<br>Bill Date : '.$sale_details->date.'<br><br>AVA Jewellers';

                        $user = "94777979679";
                        $password = "1739";
                        $text = urlencode($text);
                        $to = $customer_number;

                        $baseurl ="http://www.textit.biz/sendmsg";
                        $url = "$baseurl/?id=$user&pw=$password&to=$to&text=$text";
                        $ret = get_web_page($url);
                    }

                    if($customer_details->customer_type == 'Walk-In'){
                        $this->admin_db->change_customer_status($sale_details->customer_id, 4);
                    }

                    if($sale_details->sale_type == "Credit Sale"){
                        $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash + $sale_details->bill_amount;
                        $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold;
                    }else if($sale_details->sale_type == "Gold Sale"){
                        $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold + $sale_details->bill_amount;
                        $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash;
                    }

                    $amounts['over_paid_gold'] = $customer_details->over_paid_gold;
                    $amounts['over_paid_cash'] = $customer_details->over_paid_cash;

                    $this->admin_db->update_customer_accounts($sale_details->customer_id, $amounts);

                    $sale_items = $this->admin_db->get_sale_items_by_sale_id($sale_details->id);

                    $total_sale_grams = 0;

                    foreach($sale_items as $sale_item){

                        $total_sale_grams += $sale_item['sales_grams'];

                    }

                    $stock_details = $this->admin_db->get_stock_details();

                    $tt_gold_in_hand = $stock_details->tt_gold_in_hand;
                    $new_tt_gold_in_hand = $tt_gold_in_hand - $total_sale_grams;

                    $this->admin_db->update_stock_details('tt_gold_in_hand', $new_tt_gold_in_hand);

                    $account['item_type'] = 'sale';
                    $account['item_id'] = $sale_details->id;
                    $account['action_type'] = 'Debited';
                    $account['amount'] = $total_sale_grams;
                    $account['description'] = 'Sold To ' .$customer_details->customer_name;

                    $this->admin_db->add_22k_gold_logs($account);
                    
                    $payment_items = $this->admin_db->get_payment_items_by_sale_id($approval_details->item_id);
                    
                    if($payment_items){
                        foreach($payment_items as $payment_item){
                            
                            $customer_details = $this->admin_db->get_customer_by_id($sale_details->customer_id);
                            
                            if($sale_details->balance_amount < 0){
                                if($customer_details->status == 4 && $customer_details->customer_type == 'Walk-In'){
                                    $this->admin_db->change_customer_status($sale_details->customer_id, 1);
                                }

                                $this->admin_db->change_sale_status($sale_details->id, 1);
                            }else{

                                $this->admin_db->change_sale_status($sale_details->id, 2);
                            }
                            
                            $amounts = array();
                            if($payment_item['payment_method'] == "Gold"){

                                if($sale_details->balance_amount < 0){

                                    $new_over_paid_gold = $customer_details->over_paid_gold + abs($sale_details->balance_amount);
                                    $amounts['over_paid_gold'] = $new_over_paid_gold;

                                }else{

                                    $amounts['over_paid_gold'] = $customer_details->over_paid_gold;

                                }
                                

                                $amounts['over_paid_cash'] = $customer_details->over_paid_cash;
                                $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold - $payment_item['paid_amount'];
                                $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash;

                            }elseif($payment_item['payment_method'] == "Over Paid Gold"){

                                $new_over_paid_gold = $customer_details->over_paid_gold - $payment_item['paid_amount'];
                                $amounts['over_paid_gold'] = $new_over_paid_gold;

                                if($sale_details->balance_amount < 0){

                                    $over_paid_gold = $customer_details->over_paid_gold - $payment_item['paid_amount'];
                                    $new_over_paid_gold = $over_paid_gold + ($payment_item['paid_amount'] - $sale_details->balance_amount);

                                    $amounts['over_paid_gold'] = $new_over_paid_gold;

                                }

                                $amounts['over_paid_cash'] = $customer_details->over_paid_cash;
                                $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold - $payment_item['paid_amount'];
                                $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash;

                            }elseif($payment_item['payment_method'] == "Over Paid Cash"){

                                $new_over_paid_cash = $customer_details->over_paid_cash - $payment_item['paid_amount'];
                                $amounts['over_paid_cash'] = $new_over_paid_cash;

                                if($sale_details->balance_amount < 0){

                                    $over_paid_cash = $customer_details->over_paid_cash - $payment_item['paid_amount'];
                                    $new_over_paid_cash = $over_paid_cash + ($payment_item['paid_amount'] - $sale_details->balance_amount);

                                    $amounts['over_paid_cash'] = $new_over_paid_cash;

                                }

                                $amounts['over_paid_gold'] = $customer_details->over_paid_gold;
                                $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold;
                                $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash - $payment_item['paid_amount'];

                            }else{

                                if($sale_details->balance_amount < 0){

                                    $new_over_paid_cash = $customer_details->over_paid_cash + abs($sale_details->balance_amount);
                                    $amounts['over_paid_cash'] = $new_over_paid_cash;

                                }else{

                                    $amounts['over_paid_cash'] = $customer_details->over_paid_cash;

                                }

                                $amounts['over_paid_gold'] = $customer_details->over_paid_gold;
                                $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold;
                                $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash - $payment_item['paid_amount'];

                            }
                              
                            $this->admin_db->update_customer_accounts($sale_details->customer_id, $amounts);
                               
                            $stock_details = $this->admin_db->get_stock_details();

                            if($payment_item['payment_method'] == 'Cash'){
                                $cash_in_hand = $stock_details->cash_in_hand;
                                $new_cash_in_hand = $cash_in_hand + $payment_item['paid_amount'];

                                $this->admin_db->update_stock_details('cash_in_hand', $new_cash_in_hand);

                                $account['action_date'] = $payment_item['date'];
                                $account['item_type'] = 'receipt amount';
                                $account['item_id'] = $payment_item['payment_id'];
                                $account['action_type'] = 'Credited';
                                $account['amount'] = $payment_item['paid_amount'];
                                $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                                $this->admin_db->add_cash_logs($account);

                            }

                            if($payment_item['payment_method'] == 'Cheque'){
                                $cheque['bank_id'] = $payment_item['cheq_bank'];
                                $cheque['payment_id'] = $payment_item['payment_id'];
                                $cheque['customer_id'] = $sale_details->customer_id;
                                $cheque['cheque_type'] = 'Sale';
                                $cheque['cheque_number'] = $data['cheq_cheque_number'];
                                $cheque['cheque_amount'] = $payment_item['paid_amount'];
                                $cheque['deposit_date'] = $data['cheq_deposit_date'];

                                $this->admin_db->add_cheque_details($cheque);

                            }

                            if($payment_item['payment_method'] == 'Gold'){
                                $tf_gold_in_hand = $stock_details->tf_gold_in_hand;
                                $new_tf_gold_in_hand = $tf_gold_in_hand + $payment_item['paid_amount'];

                                $this->admin_db->update_stock_details('tf_gold_in_hand', $new_tf_gold_in_hand);

                                $account['item_type'] = 'receipt amount';
                                $account['item_id'] = $payment_item['payment_id'];
                                $account['action_type'] = 'Credited';
                                $account['amount'] = $payment_item['paid_amount'];
                                $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                                $this->admin_db->add_24k_gold_logs($account);

                            }

                            if($payment_item['payment_method'] == 'Bank Deposit'){
                                $account_details = $this->admin_db->get_bank_account_by_id($payment_item['account_id']);

                                $bank_balance = $account_details->bank_balance;
                                $new_bank_balance  = $bank_balance + $payment_item['paid_amount'];

                                $this->admin_db->update_bank_balance($payment_item['account_id'], $new_bank_balance);

                                $account['account_id'] = $payment_item['account_id'];
                                $account['item_type'] = 'receipt amount';
                                $account['item_id'] = $payment_item['payment_id'];
                                $account['action_type'] = 'Credited';
                                $account['amount'] = $payment_item['paid_amount'];
                                $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                                $this->admin_db->add_bank_account_logs($account);

                            }
                        }
                    }

                } else if($type == 'Box Sale'){

                    $this->admin_db->change_box_sale_status($approval_details->item_id, 3);

                    $sale_details = $this->admin_db->get_box_sale_details_by_id($approval_details->item_id);
                    
                    $customer_details = $this->admin_db->get_customer_by_id($sale_details->customer_id);

                    $customer_name = $customer_details->customer_name;
                    $customer_number = $customer_details->contact_number;
                    if($customer_details->send_sms == 1){
                        $send_msg = true;
                    }else{
                        $send_msg = false;
                    }

                    if($customer_number != '' && $send_msg){
                        $customer_number = preg_replace('/^0/','94',$customer_number); 

                        if($sale_details->sale_type == "Credit Sale"){
                            $total_sum = 'Rs. '.number_format($sale_details->bill_amount,2,'.',',');
                        }else if($sale_details->sale_type == "Gold Sale"){
                            $total_sum = number_format($sale_details->bill_amount,2,'.',',').' g';
                        }

                        $text = 'Hi '.$customer_name.'!<br>Thank you doing business of '.$total_sum.'<br>Ref. No : '.$sale_details->invoice_num.'<br>Bill Date : '.$sale_details->date.'<br><br>AVA Jewellers';

                        $user = "94777979679";
                        $password = "1739";
                        $text = urlencode($text);
                        $to = $customer_number;

                        $baseurl ="http://www.textit.biz/sendmsg";
                        $url = "$baseurl/?id=$user&pw=$password&to=$to&text=$text";
                        $ret = get_web_page($url);
                    }

                    if($customer_details->customer_type == 'Walk-In'){
                        $this->admin_db->change_customer_status($sale_details->customer_id, 4);
                    }

                    if($sale_details->sale_type == "Credit Sale"){
                        $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash + $sale_details->bill_amount;
                        $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold;
                    }else if($sale_details->sale_type == "Gold Sale"){
                        $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold + $sale_details->bill_amount;
                        $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash;
                    }

                    $amounts['box_over_paid_gold'] = $customer_details->box_over_paid_gold;
                    $amounts['box_over_paid_cash'] = $customer_details->box_over_paid_cash;

                    $this->admin_db->update_customer_box_accounts($sale_details->customer_id, $amounts);

                    $sale_items = $this->admin_db->get_box_sale_items_by_box_sale_id($sale_details->id);

                    $total_sale_grams = 0;

                    foreach($sale_items as $sale_item){

                        $total_sale_grams += $sale_item['sales_grams'];

                    }

                    $stock_details = $this->admin_db->get_stock_details();

                    $box_tt_gold_in_hand = $stock_details->box_tt_gold_in_hand;
                    $new_box_tt_gold_in_hand = $box_tt_gold_in_hand - $total_sale_grams;

                    $this->admin_db->update_stock_details('box_tt_gold_in_hand', $new_box_tt_gold_in_hand);

                    $account['item_type'] = 'sale';
                    $account['item_id'] = $sale_details->id;
                    $account['action_type'] = 'Debited';
                    $account['amount'] = $total_sale_grams;
                    $account['description'] = 'Sold To ' .$customer_details->customer_name;

                    $this->admin_db->add_box_22k_gold_logs($account);
                    
                    $payment_items = $this->admin_db->get_box_payment_items_by_sale_id($approval_details->item_id);
                    
                    if($payment_items){
                        foreach($payment_items as $payment_item){
                            
                            $customer_details = $this->admin_db->get_customer_by_id($sale_details->customer_id);
                            
                            if($sale_details->balance_amount < 0){
                                if($customer_details->status == 4 && $customer_details->customer_type == 'Walk-In'){
                                    $this->admin_db->change_customer_status($sale_details->customer_id, 1);
                                }

                                $this->admin_db->change_box_sale_status($sale_details->id, 1);
                            }else{

                                $this->admin_db->change_box_sale_status($sale_details->id, 2);
                            }
                            
                            $amounts = array();
                            if($payment_item['payment_method'] == "Gold"){

                                if($sale_details->balance_amount < 0){

                                    $new_over_paid_gold = $customer_details->box_over_paid_gold + abs($sale_details->balance_amount);
                                    $amounts['box_over_paid_gold'] = $new_over_paid_gold;

                                }else{

                                    $amounts['box_over_paid_gold'] = $customer_details->box_over_paid_gold;

                                }
                                

                                $amounts['box_over_paid_cash'] = $customer_details->box_over_paid_cash;
                                $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold - $payment_item['paid_amount'];
                                $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash;

                            }elseif($payment_item['payment_method'] == "Over Paid Gold"){

                                $new_over_paid_gold = $customer_details->box_over_paid_gold - $payment_item['paid_amount'];
                                $amounts['box_over_paid_gold'] = $new_over_paid_gold;

                                if($sale_details->balance_amount < 0){

                                    $over_paid_gold = $customer_details->box_over_paid_gold - $payment_item['paid_amount'];
                                    $new_over_paid_gold = $over_paid_gold + ($payment_item['paid_amount'] - $sale_details->balance_amount);

                                    $amounts['over_paid_gold'] = $new_over_paid_gold;

                                }

                                $amounts['box_over_paid_cash'] = $customer_details->box_over_paid_cash;
                                $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold - $payment_item['paid_amount'];
                                $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash;

                            }elseif($payment_item['payment_method'] == "Over Paid Cash"){

                                $new_over_paid_cash = $customer_details->box_over_paid_cash - $payment_item['paid_amount'];
                                $amounts['box_over_paid_cash'] = $new_over_paid_cash;

                                if($sale_details->balance_amount < 0){

                                    $over_paid_cash = $customer_details->box_over_paid_cash - $payment_item['paid_amount'];
                                    $new_over_paid_cash = $over_paid_cash + ($payment_item['paid_amount'] - $sale_details->balance_amount);

                                    $amounts['box_over_paid_cash'] = $new_over_paid_cash;

                                }

                                $amounts['box_over_paid_gold'] = $customer_details->box_over_paid_gold;
                                $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold;
                                $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash - $payment_item['paid_amount'];

                            }else{

                                if($sale_details->balance_amount < 0){

                                    $new_over_paid_cash = $customer_details->box_over_paid_cash + abs($sale_details->balance_amount);
                                    $amounts['box_over_paid_cash'] = $new_over_paid_cash;

                                }else{

                                    $amounts['box_over_paid_cash'] = $customer_details->box_over_paid_cash;

                                }

                                $amounts['box_over_paid_gold'] = $customer_details->box_over_paid_gold;
                                $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold;
                                $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash - $payment_item['paid_amount'];

                            }
                              
                            $this->admin_db->update_customer_box_accounts($sale_details->customer_id, $amounts);
                               
                            $stock_details = $this->admin_db->get_stock_details();

                            if($payment_item['payment_method'] == 'Cash'){
                                $cash_in_hand = $stock_details->box_cash_in_hand;
                                $new_cash_in_hand = $cash_in_hand + $payment_item['paid_amount'];

                                $this->admin_db->update_stock_details('box_cash_in_hand', $new_cash_in_hand);

                                $account['action_date'] = $payment_item['date'];
                                $account['item_type'] = 'receipt amount';
                                $account['item_id'] = $payment_item['box_payment_id'];
                                $account['action_type'] = 'Credited';
                                $account['amount'] = $payment_item['paid_amount'];
                                $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                                $this->admin_db->add_box_cash_logs($account);

                            }

                            if($payment_item['payment_method'] == 'Cheque'){
                                $cheque['bank_id'] = $data['cheq_bank'];
                                $cheque['payment_id'] = $payment_item['box_payment_id'];
                                $cheque['customer_id'] = $sale_details->customer_id;
                                $cheque['cheque_type'] = 'Box Sale';
                                $cheque['cheque_number'] = $data['cheq_cheque_number'];
                                $cheque['cheque_amount'] = $payment_item['paid_amount'];
                                $cheque['deposit_date'] = $data['cheq_deposit_date'];

                                $this->admin_db->add_cheque_details($cheque);

                            }

                            if($payment_item['payment_method'] == 'Gold'){
                                $box_tf_gold_in_hand = $stock_details->box_tf_gold_in_hand;
                                $new_box_tf_gold_in_hand = $box_tf_gold_in_hand + $payment_item['paid_amount'];

                                $this->admin_db->update_stock_details('box_tf_gold_in_hand', $new_box_tf_gold_in_hand);

                                $account['item_type'] = 'receipt amount';
                                $account['item_id'] = $payment_item['box_payment_id'];
                                $account['action_type'] = 'Credited';
                                $account['amount'] = $payment_item['paid_amount'];
                                $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                                $this->admin_db->add_box_24k_gold_logs($account);

                            }

                            if($payment_item['payment_method'] == 'Bank Deposit'){
                                $account_details = $this->admin_db->get_bank_account_by_id($payment_item['account_id']);

                                $bank_balance = $account_details->bank_balance;
                                $new_bank_balance  = $bank_balance + $payment_item['paid_amount'];

                                $this->admin_db->update_bank_balance($payment_item['account_id'], $new_bank_balance);

                                $account['account_id'] = $payment_item['account_id'];
                                $account['item_type'] = 'receipt amount';
                                $account['item_id'] = $payment_item['box_payment_id'];
                                $account['action_type'] = 'Credited';
                                $account['amount'] = $payment_item['paid_amount'];
                                $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                                $this->admin_db->add_box_bank_account_logs($account);

                            }
                        }
                    }

                } else if ($type == 'UNA Purchase') {

                    $this->admin_db->change_una_status($approval_details->item_id, 3);

                    $una_details = $this->admin_db->get_una_details_by_id($approval_details->item_id);

                    $creditor_details = $this->admin_db->get_creditor_by_id($una_details->creditor_id);

                    $amounts['una_amount'] = $creditor_details->una_amount + $una_details->lkr_amount;
                    $amounts['una_bal_amount'] = $creditor_details->una_bal_amount + $una_details->lkr_amount;
                    $amounts['credit_amount'] = $creditor_details->amount;
                    $amounts['credit_bal_amount'] = $creditor_details->bal_amount;

                    $this->admin_db->update_creditor_amounts($una_details->creditor_id, $amounts);

                    $data['creditor_id'] = $una_details->creditor_id;
                    $data['item_type'] = 'UNA Purchase';
                    $data['item_id'] = $approval_details->item_id;
                    $data['amount'] = $una_details->lkr_amount;
                    $data['description'] = NULL;

                    $this->admin_db->add_creditor_accounts($data);

                } else if($type == '24K Sale'){

                    $this->admin_db->change_24k_sale_status($approval_details->item_id, 3);

                    $sale_details = $this->admin_db->get_24k_sale_details_by_id($approval_details->item_id);

                    $customer_details = $this->admin_db->get_24k_customer_by_id($sale_details->customer_id);

                    $customer_name = $customer_details->customer_name;
                    $customer_number = $customer_details->contact_number;
                    if($customer_details->send_sms == 1){
                        $send_msg = true;
                    }else{
                        $send_msg = false;
                    }

                    if($customer_number != '' && $send_msg){
                        $customer_number = preg_replace('/^0/','94',$customer_number); 

                        $total_sum = 'Rs. '.number_format($sale_details->bill_amount,2,'.',',');

                        $text = 'Hi '.$customer_name.'!<br>Thank you doing business of '.$total_sum.'<br>Ref. No : '.$sale_details->invoice_num.'<br>Bill Date : '.$sale_details->date.'<br><br>AVA Jewellers';

                        $user = "94777979679";
                        $password = "1739";
                        $text = urlencode($text);
                        $to = $customer_number;

                        $baseurl ="http://www.textit.biz/sendmsg";
                        $url = "$baseurl/?id=$user&pw=$password&to=$to&text=$text";
                        $ret = get_web_page($url);
                    }

                    if($sale_details->sale_type == '24K DXB Sale'){

                        $tot_amount_gold = $customer_details->dxb_gold_tot_amount + $sale_details->gold_amount;
                        $tot_amount_cash = $customer_details->dxb_cash_tot_amount + $sale_details->bill_amount;
                        $balance_amount = $customer_details->dxb_balance_amount + $sale_details->bill_amount;

                        $amounts['dxb_gold_tot_amount'] = $tot_amount_gold;
                        $amounts['dxb_cash_tot_amount'] = $tot_amount_cash;
                        $amounts['dxb_paid_amount'] = $customer_details->dxb_paid_amount;

                        $amounts['dxb_balance_amount'] = $balance_amount;

                        $this->admin_db->update_24k_customer_dxb_accounts($sale_details->customer_id, $amounts);

                    }elseif($sale_details->sale_type == '24K BOX Sale'){

                        $tot_amount_gold = $customer_details->box_gold_tot_amount + $sale_details->gold_amount;
                        $tot_amount_cash = $customer_details->box_cash_tot_amount + $sale_details->bill_amount;
                        $balance_amount = $customer_details->box_balance_amount + $sale_details->bill_amount;

                        $amounts['box_gold_tot_amount'] = $tot_amount_gold;
                        $amounts['box_cash_tot_amount'] = $tot_amount_cash;
                        $amounts['box_paid_amount'] = $customer_details->box_paid_amount;

                        $amounts['box_balance_amount'] = $balance_amount;

                        $this->admin_db->update_24k_customer_box_accounts($sale_details->customer_id, $amounts);

                    }

                    $sale_items = $this->admin_db->get_24k_sale_items_by_sale_id($sale_details->id);

                    $total_sale_grams = 0;

                    foreach($sale_items as $sale_item){

                        $total_sale_grams += $sale_item['sales_grams'];

                    }

                    $stock_details = $this->admin_db->get_stock_details();

                    $tf_gold_in_hand = $stock_details->tf_gold_in_hand;
                    $new_tf_gold_in_hand = $tf_gold_in_hand - $total_sale_grams;

                    $this->admin_db->update_stock_details('tf_gold_in_hand', $new_tf_gold_in_hand);

                    $account['item_type'] = 'sale';
                    $account['item_id'] = $sale_details->id;
                    $account['action_type'] = 'Debited';
                    $account['amount'] = $total_sale_grams;
                    $account['description'] = 'Sold To ' .$customer_details->customer_name;

                    $this->admin_db->add_24k_gold_logs($account);
                    
                    $payment_items = $this->admin_db->get_24k_payment_items_by_sale_id($approval_details->item_id);
                    
                    if($payment_items){
                        foreach($payment_items as $payment_item){
                            
                            $customer_details = $this->admin_db->get_24k_customer_by_id($sale_details->customer_id);
                            
                            if($payment_item['payment_method'] != 'Cheque'){
                                if($sale_details->balance_amount < 0){

                                    $amounts['balance_amount'] = 0.00;
                                    $amounts['paid_amount'] = $payment_item['paid_amount'];

                                    $this->admin_db->update_24k_sale_bal_amount($sale_details->id, $amounts);
                                }else{

                                    $amounts['balance_amount'] = $sale_details->balance_amount;
                                    $amounts['paid_amount'] = $payment_item['paid_amount'];

                                    $this->admin_db->update_24k_sale_bal_amount($sale_details->id, $amounts);

                                }
                            }

                            if($sale_details->balance_amount <= 0){ 

                                $this->admin_db->change_24k_sale_status($sale_details->id, 1);
                            }else{

                                $this->admin_db->change_24k_sale_status($sale_details->id, 2);
                            }
                            
                            if($payment_item['payment_method'] == "Over Paid Cash"){

                                $new_over_paid_cash = $customer_details->over_paid_cash - $payment_item['paid_amount'];
                                $amounts['over_paid_cash'] = $new_over_paid_cash;

                                if($sale_details->balance_amount < 0){

                                    $over_paid_cash = $customer_details->over_paid_cash - $payment_item['paid_amount'];
                                    $new_over_paid_cash = $over_paid_cash + ($payment_item['paid_amount'] - $sale_details->balance_amount);

                                    $amounts['over_paid_cash'] = $new_over_paid_cash;

                                }

                            }else{

                                if($sale_details->balance_amount < 0){

                                    $new_over_paid_cash = $customer_details->over_paid_cash + abs($sale_details->balance_amount);
                                    $amounts['over_paid_cash'] = $new_over_paid_cash;

                                }else{

                                    $amounts['over_paid_cash'] = $customer_details->over_paid_cash;

                                }

                            }

                            if($sale_details->sale_type == '24K DXB Sale'){
                                
                                $amounts['dxb_gold_tot_amount'] = $customer_details->dxb_gold_tot_amount;
                                $amounts['dxb_cash_tot_amount'] = $customer_details->dxb_cash_tot_amount;
                                $amounts['dxb_paid_amount'] = $customer_details->dxb_paid_amount + $payment_item['paid_amount'];

                                $amounts['dxb_balance_amount'] = $customer_details->dxb_balance_amount - $payment_item['paid_amount'];

                                $this->admin_db->update_24k_customer_dxb_accounts($sale_details->customer_id, $amounts);

                            }elseif($sale_details->sale_type == '24K BOX Sale'){

                                $amounts['box_gold_tot_amount'] = $customer_details->box_gold_tot_amount;
                                $amounts['box_cash_tot_amount'] = $customer_details->box_cash_tot_amount;
                                $amounts['box_paid_amount'] = $customer_details->box_paid_amount + $payment_item['paid_amount'];

                                $amounts['box_balance_amount'] = $customer_details->box_balance_amount - $payment_item['paid_amount'];

                                $this->admin_db->update_24k_customer_box_accounts($sale_details->customer_id, $amounts);

                            }
                            
                            $stock_details = $this->admin_db->get_stock_details();

                            if($payment_item['payment_method'] == 'Cash'){
                                $cash_in_hand = $stock_details->cash_in_hand;
                                $new_cash_in_hand = $cash_in_hand + $payment_item['paid_amount'];

                                $this->admin_db->update_stock_details('cash_in_hand', $new_cash_in_hand);

                                $account['action_date'] = $payment_item['date'];
                                $account['item_type'] = 'receipt amount';
                                $account['item_id'] = $payment_item['payment_id'];
                                $account['action_type'] = 'Credited';
                                $account['amount'] = $payment_item['paid_amount'];
                                $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                                $this->admin_db->add_cash_logs($account);

                            }

                            if($payment_item['payment_method'] == 'Cheque'){
                                $cheque['bank_id'] = $data['cheq_bank'];
                                $cheque['payment_id'] = $payment_item['payment_id'];
                                $cheque['customer_id'] = $sale_details->customer_id;
                                $cheque['cheque_type'] = '24K Sale';
                                $cheque['cheque_number'] = $data['cheq_cheque_number'];
                                $cheque['cheque_amount'] = $payment_item['paid_amount'];
                                $cheque['deposit_date'] = $data['cheq_deposit_date'];

                                $this->admin_db->add_cheque_details($cheque);

                            }

                            if($payment_item['payment_method'] == 'Bank Deposit'){
                                $account_details = $this->admin_db->get_bank_account_by_id($payment_item['account_id']);

                                $bank_balance = $account_details->bank_balance;
                                $new_bank_balance  = $bank_balance + $payment_item['paid_amount'];

                                $this->admin_db->update_bank_balance($payment_item['account_id'], $new_bank_balance);

                                $account['account_id'] = $payment_item['account_id'];
                                $account['item_type'] = 'receipt amount';
                                $account['item_id'] = $payment_item['payment_id'];
                                $account['action_type'] = 'Credited';
                                $account['amount'] = $payment_item['paid_amount'];
                                $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                                $this->admin_db->add_bank_account_logs($account);

                            }
                        }
                    }

                } else if($type == 'Return Dxb Sale'){

                    $this->admin_db->change_return_sale_status($approval_details->item_id, 1);
//                    
                    $return_sale_details = $this->admin_db->get_returned_sale_details_by_id($approval_details->item_id);
                    $sale_details = $this->admin_db->get_sale_details_by_id($return_sale_details->sale_id);
                    $customer_details = $this->admin_db->get_customer_by_id($return_sale_details->customer_id);
                    
                    $return_sale_items = $this->admin_db->get_returned_sale_items_for_approvals($approval_details->item_id);
//
                    $sale_amounts['balance_amount'] = $sale_details->balance_amount - $return_sale_details->amount;
                    $sale_amounts['return_sale_amount'] = $sale_details->return_sale_amount + $return_sale_details->amount;

                    if($sale_amounts['balance_amount'] <= 0){

                        if($customer_details->status == 4 && $customer_details->customer_type == 'Walk-In'){
                            $this->admin_db->change_customer_status($return_sale_details->customer_id, 1);
                        }

                        $this->admin_db->change_sale_status($return_sale_details->sale_id, 1);
                    }else{

                        $this->admin_db->change_sale_status($return_sale_details->sale_id, 2);
                    }

                    $this->admin_db->update_return_sale_amounts($return_sale_details->sale_id, $sale_amounts);
                    
                    

                    if($return_sale_details->sale_type == "Credit Sale"){

                        if($customer_details->debt_amount_cash == '' || $customer_details->debt_amount_cash == 0.00){
                            $amounts['over_paid_cash'] = $customer_details->over_paid_cash + $return_sale_details->amount;
                            $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash;
                        }else{
                            $amounts['over_paid_cash'] = $customer_details->over_paid_cash;
                            $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash - $return_sale_details->amount;
                        }

                        $amounts['over_paid_gold'] = $customer_details->over_paid_gold;
                        $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold;

                    }else if($return_sale_details->sale_type == "Gold Sale"){

                        if($customer_details->debt_amount_gold == '' || $customer_details->debt_amount_gold == 0.00){
                            $amounts['over_paid_gold'] = $customer_details->over_paid_gold + $return_sale_details->amount;
                            $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold;
                        }else{
                            $amounts['over_paid_gold'] = $customer_details->over_paid_gold;
                            $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold - $return_sale_details->amount;
                        }

                        $amounts['over_paid_cash'] = $customer_details->over_paid_cash;
                        $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash;
                    }

                    $this->admin_db->update_customer_accounts($return_sale_details->customer_id, $amounts);
                    
                    $total_sale_grams = 0;
                    
                    foreach($return_sale_items as $return_sale_item){
                        $sales_grams = $return_sale_item['sales_grams'];
                        $actual_grams = $return_sale_item['actual_grams'];
                        
                        $total_sale_grams += $sales_grams;

                        $actual_grams_after_ret = $actual_grams - $sales_grams;

                        $this->admin_db->update_sale_item_actual_grams($return_sale_item['item_id'], $actual_grams_after_ret); 

                    }

                    $stock_details = $this->admin_db->get_stock_details();

                    $tt_gold_in_hand = $stock_details->tt_gold_in_hand;
                    $new_tt_gold_in_hand = $tt_gold_in_hand + $total_sale_grams;

                    $this->admin_db->update_stock_details('tt_gold_in_hand', $new_tt_gold_in_hand);

                    $account['item_type'] = 'return sale';
                    $account['item_id'] = $approval_details->item_id;
                    $account['action_type'] = 'Credited';
                    $account['amount'] = $total_sale_grams;
                    $account['description'] = 'Returned Sale From '.$customer_details->customer_name;

                    $this->admin_db->add_22k_gold_logs($account);

                    
                }

                $data['pending'] = "";
                $data['accepted'] = "active";
                $data['rejected'] = "";

            } else if ($status == 'Rejected') {

                $data['success_msg'] = 'Approval Rejected Successfully';
                $data['pending'] = "";
                $data['accepted'] = "";
                $data['rejected'] = "active";

                if($type == '24K Rate Change'){
                    $data['rate_id'] = $approval_details->item_id;
                    $data['amount'] = $approval_details->amount; 

                    $data['status'] = 'Rejected'; 
                    $data['description'] = $approval_details->reason;        
                    $this->admin_db->save_add_rate_log($data);

                }else if($type == 'Expense'){

                    $this->admin_db->change_expense_status($approval_details->item_id, 'Rejected');

                } else if($type == 'Dxb Sale'){

                    $this->admin_db->change_sale_status($approval_details->item_id, 5);

                } else if($type == 'Box Sale'){

                    $this->admin_db->change_box_sale_status($approval_details->item_id, 5);

                } else if($type == 'UNA Purchase'){

                    $this->admin_db->change_una_status($approval_details->item_id, 5);

                } else if($type == '24K Sale'){

                    $this->admin_db->change_24k_sale_status($approval_details->item_id, 5);

                } else if($type == 'Return Dxb Sale'){

                    $this->admin_db->change_return_sale_status($approval_details->item_id, 3);

                }

            }
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        } 
        
        $data['title'] = 'Approvals';
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/approvals', $data);
        $this->load->view('dashboard/footer');

    }

    public function get_pending_approvals_count()
    {
        $user_type = $this->session->userdata('user_type_id');
        
        header('Content-Type: application/json');
        $approval_count = $this->admin_db->get_pending_approvals_count($user_type);
        
        echo json_encode($approval_count);
    }
    

    public function una()
    {
        $data['title'] = 'UNA';
        
        $data['all_una'] = "active";
        $data['pending_una'] = "";
        $data['completed_una'] = "";
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/una', $data);
        $this->load->view('dashboard/footer');
    }

    public function add_una()
    {
        $data['title'] = 'Purchase UNA';
//        $data['k_rate'] = $this->admin_db->get_rate_detail_by_id(1)->item_rate;
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/add_una', $data);
        $this->load->view('dashboard/footer');
    }

    public function ajax_get_creditor_details()
    {
        $id = $this->input->post('creditor_id');
        header('Content-Type: application/json');
        
        $creditor_details = $this->admin_db->get_creditor_by_id($id);
        
        $result = array(
            "contact_number" => $creditor_details->contact_number,
            "tel_number" => $creditor_details->tel_number, 
            "creditor_status" => $creditor_details->status,
            "creditor_type" => $creditor_details->creditor_type,
            "tot_amount" => $creditor_details->amount,
            "bal_amount" => $creditor_details->bal_amount,
            "paid_amount" => $creditor_details->paid_amount,
            "una_tot_amount" => $creditor_details->una_amount,
            "una_bal_amount" => $creditor_details->una_bal_amount,
            "una_paid_amount" => $creditor_details->una_paid_amount,
            
        );
        
        echo json_encode($result);
    }

    public function save_add_una()
    {
        $invoice_date = $this->input->post('invoice_date');
        $data['una_amount'] = $this->input->post('una_amount');
        $data['una_rate'] = $this->input->post('una_rate');
        $data['lkr_amount'] = $this->input->post('lkr_amount');
        $data['recipient'] = $this->input->post('recipient');
        $select_creditor = $this->input->post('select_creditor');
        $data['remarks'] = $this->input->post('remarks');
        
        $user_type = $this->session->userdata('user_type_id');
        
        $data['date'] = date("Y-m-d", strtotime($invoice_date));
        
        header('Content-Type: application/json');
        
        try {
            if($select_creditor == "Add New Creditor"){
                $creditor['creditor_name'] = $this->input->post('creditor_name');
                $creditor['contact_number'] = $this->input->post('contact_num');
                $creditor['tel_number'] = $this->input->post('tel_number');
                $creditor['creditor_type'] = $this->input->post('creditor_type');
                $creditor['amount'] = 0.00;

                if($user_type == 1){
                    $creditor['una_amount'] = $data['lkr_amount'];
                }else{
                    $creditor['una_amount'] = 0.00;
                }

                $added_creditor = $this->admin_db->add_creditor_details_sale($creditor);

                $data['creditor_id'] = $added_creditor['id'];

            }else{
                $data['creditor_id'] = $select_creditor;
                if($user_type == 1){

                    $creditor_details = $this->admin_db->get_creditor_by_id($select_creditor);

                    $amounts['una_amount'] = $creditor_details->una_amount + $data['lkr_amount'];
                    $amounts['una_bal_amount'] = $creditor_details->una_bal_amount + $data['lkr_amount'];
                    $amounts['credit_amount'] = $creditor_details->amount;
                    $amounts['credit_bal_amount'] = $creditor_details->bal_amount;

                    $this->admin_db->update_creditor_amounts($select_creditor, $amounts);
                }
            }

            if($user_type == 1){
                $data['status'] = 3; // 3 - Pending Payment  
                $added_una = $this->admin_db->add_una($data);

                $data['item_type'] = 'UNA Purchase';
                $data['item_id'] = $added_una['id'];
                $data['amount'] = $data['lkr_amount'];
                $data['description'] = NULL;

                $this->admin_db->add_creditor_accounts($data);

            }else{
                $data['status'] = 4; // 4 - Requested 
                $added_una = $this->admin_db->add_una($data);

                $data['item_id'] = $added_una['id'];
                $data['item_type'] = 'UNA Purchase';
                $data['amount'] = 'Rs. '.number_format($data['lkr_amount'],2,'.',','); 
                $data['description'] = NULL;
                $this->admin_db->add_approval_requests($data);

            }

            if($added_una['status'] == 1){
                echo json_encode(array("message" => "UNA Added Successfully", "status" => "1"));

            }
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }
    }

    public function view_una()
    {
        $id = $this->input->get('una_id');
        
        $data['una_details'] = $una_details = $this->admin_db->get_una_by_id($id);
        $data['creditor_details'] = $this->admin_db->get_creditor_by_id($una_details->creditor_id);
        
        
        $data['stock_details'] = $this->admin_db->get_stock_details();
        $data['bank_accounts'] = $this->admin_db->get_bank_accounts();
        $data['settlement_creditors'] = $this->admin_db->get_creditors_to_settle_una();
        
        if($data['una_details']->status == 4){
            $data['approval_details'] = $this->admin_db->get_approval_by_item_type_id('UNA Purchase', $id);
        }
        
//        print_r($data['settlement_creditors']);exit;
        
        $data['title'] = 'View UNA Details';
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/view_una', $data);
        $this->load->view('dashboard/footer');
    }

    public function save_edit_una()
    {
        $id = $this->input->post('una_id');
        $invoice_date = $this->input->post('invoice_date');
        $data['una_amount'] = $this->input->post('una_amount');
        $data['una_rate'] = $this->input->post('una_rate');
        $data['lkr_amount'] = $this->input->post('lkr_amount');
        $prev_lkr_amount = $this->input->post('lkr_amount');
        $data['recipient'] = $this->input->post('recipient');
        $select_creditor = $this->input->post('select_creditor');
        $prev_creditor_id = $this->input->post('prev_creditor_id');
        
        $data['date'] = date("Y-m-d", strtotime($invoice_date));
        
        header('Content-Type: application/json');
        
        try {
            if($select_creditor == "Add New Creditor"){
                $creditor['creditor_name'] = $this->input->post('creditor_name');
                $creditor['contact_number'] = $this->input->post('contact_num');
                $creditor['tel_number'] = $this->input->post('tel_number');
                $creditor['creditor_type'] = $this->input->post('creditor_type');
                $creditor['amount'] = 0.00;
                $creditor['una_amount'] = $data['lkr_amount'];

                $added_creditor = $this->admin_db->add_creditor_details_sale($creditor);

                $data['creditor_id'] = $added_creditor['id'];

                $prev_creditor_details = $this->admin_db->get_creditor_by_id($prev_creditor_id);

                $amounts['una_amount'] = $prev_creditor_details->una_amount - $prev_lkr_amount;
                $amounts['una_bal_amount'] = $prev_creditor_details->una_bal_amount - $prev_lkr_amount;
                $amounts['credit_amount'] = $prev_creditor_details->amount;
                $amounts['credit_bal_amount'] = $prev_creditor_details->bal_amount;

                $this->admin_db->update_creditor_amounts($prev_creditor_id, $amounts);

            }else{
                $data['creditor_id'] = $select_creditor;

                $creditor_details = $this->admin_db->get_creditor_by_id($prev_creditor_id);

                $prev_una_amount = ($creditor_details->una_amount - $prev_lkr_amount);
                $prev_una_bal_amount = ($creditor_details->una_bal_amount - $prev_lkr_amount);

                if($prev_una_amount < 0){
                    $prev_una_amount = 0;
                }
                if($prev_una_bal_amount < 0){
                    $prev_una_bal_amount = 0;
                }

                $amounts['una_amount'] = $prev_una_amount + $data['lkr_amount'];
                $amounts['una_bal_amount'] = $prev_una_bal_amount + $data['lkr_amount'];
                $amounts['credit_amount'] = $creditor_details->amount;
                $amounts['credit_bal_amount'] = $creditor_details->bal_amount;

                $this->admin_db->update_creditor_amounts($select_creditor, $amounts);

                if($prev_creditor_id != $select_creditor){

                    $prev_creditor_details = $this->admin_db->get_creditor_by_id($prev_creditor_id);

                    $amounts['una_amount'] = $prev_creditor_details->una_amount - $prev_lkr_amount;
                    $amounts['una_bal_amount'] = $prev_creditor_details->una_bal_amount - $prev_lkr_amount;
                    $amounts['credit_amount'] = $prev_creditor_details->amount;
                    $amounts['credit_bal_amount'] = $prev_creditor_details->bal_amount;

                    $this->admin_db->update_creditor_amounts($prev_creditor_id, $amounts);

                }
            }


            $una_details = $this->admin_db->get_una_by_id($id);

            $prev_bal_amount = ($una_details->bal_amount - $prev_lkr_amount);

            if($prev_bal_amount < 0){
                $prev_bal_amount = 0;
            }

            $data['bal_amount'] = $prev_bal_amount + $data['lkr_amount'];
            $data['amount'] = $data['lkr_amount'];

            $up_una = $this->admin_db->save_edit_una_details($id, $data);

            $credit_account_details = $this->admin_db->get_creditor_accounts_by_item_id('UNA Purchase', $id);



            $this->admin_db->update_creditor_una_account($credit_account_details->id, $data['lkr_amount']);

            if($up_una['status'] == 1){
                echo json_encode(array("message" => "UNA Details Successfully Edited", "status" => "1", "una_id" => $id));

            }else{
                echo json_encode(array("message" => "An Error Occured while Editing UNA Details", "status" => "0", "una_id" => $id));

            }
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }
    }

    public function una_settlements()
    {
        $data['title'] = 'UNA Settlements';
        
//        $data['all_una'] = "active";
//        $data['pending_una'] = "";
//        $data['completed_una'] = "";
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/una_settlements', $data);
        $this->load->view('dashboard/footer');
    }
    
    public function save_add_previous_credits()
    {
        $data['creditor_id'] = $creditor_id = $this->input->post('creditor_id');
        $date = $this->input->post('bill_date');
        $data['date'] = date("Y-m-d", strtotime($date));
        $data['description'] = $this->input->post('description');
        $credit_type = $this->input->post('credit_type');
        $data['amount'] = $this->input->post('total_amount');
        
        header('Content-Type: application/json');
        
        try {
            $creditor_details = $this->admin_db->get_creditor_by_id($creditor_id);

            if($credit_type == 'Normal Credit'){
                $amounts['credit_amount'] = $creditor_details->amount + $data['amount'];
                $amounts['credit_bal_amount'] = $creditor_details->bal_amount + $data['amount'];
                $amounts['una_amount'] = $creditor_details->una_amount;
                $amounts['una_bal_amount'] = $creditor_details->una_bal_amount;

                $data['item_type'] = 'Previous Credits';
                $data['item_id'] = NULL;

            }else if($credit_type == 'UNA Credit'){
                $amounts['una_amount'] = $creditor_details->una_amount + $data['amount'];
                $amounts['una_bal_amount'] = $creditor_details->una_bal_amount + $data['amount'];
                $amounts['credit_amount'] = $creditor_details->amount;
                $amounts['credit_bal_amount'] = $creditor_details->bal_amount;

                $data['amount'] = $this->input->post('lkr_amount');

                $una['date'] = date("Y-m-d", strtotime($date));
                $una['una_amount'] = $this->input->post('una_amount');
                $una['una_rate'] = $this->input->post('una_rate');
                $una['lkr_amount'] = $this->input->post('lkr_amount');
                $una['recipient'] = $this->input->post('recipient');
                $una['creditor_id'] = $creditor_id;

                $added_una = $this->admin_db->add_una($una);

                $data['item_type'] = 'Previous Credits - UNA Purchase';
                $data['item_id'] = $added_una['id'];

                $amounts['item_id'] = $creditor_details->una_amount + $data['amount'];

            }

            $up_credit = $this->admin_db->add_creditor_accounts($data);  

            $this->admin_db->update_creditor_amounts($creditor_id, $amounts);

            if($up_credit == true){
                echo json_encode(array("message" => "Previous Credit Added Successfully", "status" => "1"));

            }else{
                echo json_encode(array("message" => "An Error Occured while Adding Previous Credit", "status" => "0"));

            }
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }
    }

    public function save_add_una_admin_remarks()
    {
        $una_id = $this->input->post('una_id');
        $data['admin_remarks'] = $this->input->post('admin_remarks');
        
        header('Content-Type: application/json');
        
        try {
            $updated_una = $this->admin_db->update_admin_remarks($una_id, $data);

            if($updated_una == true){
                echo json_encode(array("message" => "UNA Updated Successfully", "status" => "1", "una_id" => $una_id));

            }
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }
    }

    public function creditor_settlements()
    {
        $data['title'] = 'Settle Creditor';
        $data['k_rate'] = $this->admin_db->get_rate_detail_by_id(1)->item_rate;
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/settle_creditor', $data);
        $this->load->view('dashboard/footer');
    }
    
    public function save_settle_creditor()
    {
        $credit_date = $this->input->post('credit_date');
        $data['date'] = date("Y-m-d", strtotime($credit_date));
        $creditor_id = $data['creditor_id'] = $this->input->post('select_creditor');
        
        $total_credit_amount = $this->input->post('txt_cre_tot_amount');
        $total_paid_amount = $this->input->post('txt_cre_paid_amount');
        $total_balance_amount = $this->input->post('txt_cre_bal_amount');
        
        $payment_amount = $data['amount'] = $this->input->post('payment_amount');
        $payment_method = $data['payment_method'] = $this->input->post('payment_method');
        $bank_id = NULL;
        $data['status'] = 'Completed';
        $data['una_payment_id'] = null;
        
        if($payment_method == 'Cash'){
            $data['account_id'] = NULL;
            $data['cheque_number'] = NULL;
            $data['cheque_deposit_date'] = NULL;
            $data['third_party_bank_id'] = NULL;
            $data['third_party_account_number'] = NULL;
            
        }elseif($payment_method == 'Cheque'){
            $bank_account_id = $data['account_id'] = $this->input->post('cheq_bank_account');
            $cheque_number = $data['cheque_number'] = $this->input->post('cheq_cheque_number');
            $cheque_deposit_date = $this->input->post('cheq_deposit_date');
            $data['cheque_deposit_date'] = date("Y-m-d", strtotime($cheque_deposit_date));
            $data['third_party_bank_id'] = NULL;
            $data['third_party_account_number'] = NULL;
            
        }elseif($payment_method == 'Bank Transfer'){
            $bank_account_id = $data['account_id'] = $this->input->post('transfer_bank_account');
            $cheque_number = $data['cheque_number'] = NULL;
            $data['cheque_deposit_date'] = NULL;
            $bank_id = $data['third_party_bank_id'] = $this->input->post('bank_bank_name');
            $data['third_party_account_number'] = $this->input->post('bank_account_number');
            
        }elseif($payment_method == 'Bank Deposit'){
            $data['account_id'] = NULL;
            $data['cheque_number'] = NULL;
            $data['cheque_deposit_date'] = NULL;
            $bank_id = $data['third_party_bank_id'] = $this->input->post('bank_bank_name');
            $data['third_party_account_number'] = $this->input->post('bank_account_number');
            
        }
        
        header('Content-Type: application/json');
        
        try {
            $added_payment = $this->admin_db->add_creditor_payments($data);

            if($bank_id){
                $bank_details = $this->admin_db->get_bank_by_id($bank_id);
            }

            if($added_payment['status'] == 1){

                $payment_id = $added_payment['id'];
                $stock_details = $this->admin_db->get_stock_details();

                $creditor_details = $this->admin_db->get_creditor_by_id($creditor_id);

                $amounts['paid_amount'] = $creditor_details->paid_amount + $payment_amount;
                $amounts['bal_amount'] = $creditor_details->bal_amount - $payment_amount;
                $amounts['una_paid_amount'] = $creditor_details->una_paid_amount;
                $amounts['una_bal_amount'] = $creditor_details->una_bal_amount;

                $this->admin_db->update_creditor_payment_amounts($creditor_id, $amounts);

                if($payment_method == 'Cash'){
                    $cash_in_hand = $stock_details->cash_in_hand;
                    $new_cash_in_hand = $cash_in_hand - $payment_amount;

                    $this->admin_db->update_stock_details('cash_in_hand', $new_cash_in_hand);

                    $account['action_date'] = $data['date'];
                    $account['item_type'] = 'creditor_payment';
                    $account['item_id'] = $payment_id;
                    $account['action_type'] = 'Debited';
                    $account['amount'] = $payment_amount;
                    $account['description'] = 'Paid Credit For '.$creditor_details->creditor_name;

                    $this->admin_db->add_cash_logs($account);

                }

                if($payment_method == 'Cheque'){
                    $account_details = $this->admin_db->get_bank_account_by_id($bank_account_id);

                    $bank_balance = $account_details->bank_balance;
                    $new_bank_balance  = $bank_balance - $payment_amount;

                    $this->admin_db->update_bank_balance($bank_account_id, $new_bank_balance);

                    $account['account_id'] = $bank_account_id;
                    $account['item_type'] = 'creditor_payment';
                    $account['item_id'] = $payment_id;
                    $account['action_type'] = 'Debited';
                    $account['amount'] = $payment_amount;
                    $account['description'] = 'Cheque Issued, Cheque Number - '.$cheque_number;

                    $this->admin_db->add_bank_account_logs($account);

                }

                if($payment_method == 'Bank Deposit'){
                    $cash_in_hand = $stock_details->cash_in_hand;
                    $new_cash_in_hand = $cash_in_hand - $payment_amount;

                    $this->admin_db->update_stock_details('cash_in_hand', $new_cash_in_hand);

                    $account['action_date'] = $data['date'];
                    $account['item_type'] = 'creditor_payment';
                    $account['item_id'] = $payment_id;
                    $account['action_type'] = 'Debited';
                    $account['amount'] = $payment_amount;
                    $account['description'] = 'Bank Deposited To - '.$bank_details->bank_name.', Bank A/C No. - '.$data['third_party_account_number'];

                    $this->admin_db->add_cash_logs($account);

                }

                if($payment_method == 'Bank Transfer'){
                    $account_details = $this->admin_db->get_bank_account_by_id($bank_account_id);

                    $bank_balance = $account_details->bank_balance;
                    $new_bank_balance  = $bank_balance - $payment_amount;

                    $this->admin_db->update_bank_balance($bank_account_id, $new_bank_balance);

                    $account['account_id'] = $bank_account_id;
                    $account['item_type'] = 'creditor_payment';
                    $account['item_id'] = $payment_id;
                    $account['action_type'] = 'Debited';
                    $account['amount'] = $payment_amount;
                    $account['description'] = 'Bank Tranfered To - '.$bank_details->bank_name.', Bank A/C No. - '.$data['third_party_account_number'];

                    $this->admin_db->add_bank_account_logs($account);

                }

                echo json_encode(array("message" => "Expense Added Successfully", "status" => "1", "amount" => $payment_amount));

            }else{
                echo json_encode(array("message" => "An Error Occured while Adding Expense", "status" => "0", "amount" => $payment_amount));

            }
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }
    }

    public function una_creditor_settlements()
    {
        $data['title'] = 'Settle UNA Creditor';
        $data['k_rate'] = $this->admin_db->get_rate_detail_by_id(1)->item_rate;
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/settle_una_creditor', $data);
        $this->load->view('dashboard/footer');
    }

    public function ajax_get_una_to_settle()
    {
        $id = $this->input->post('creditor_id');
        
        $data['stock_details'] = $this->admin_db->get_stock_details();
        $data['bank_accounts'] = $this->admin_db->get_dxb_bank_accounts();
        $data['settlement_creditors'] = $this->admin_db->get_creditors_to_settle_una();
        $data['una_purchases'] = $this->admin_db->get_pending_una_by_creditor_id($id);

        $this->load->view('dashboard/view_una_details', $data);
        
    }
    
    public function save_una_settle_creditor() 
    {      
        $data['creditor_id'] = $creditor_id = $this->input->post('select_creditor');
        $invoice_date = $this->input->post('invoice_date');
        $data['date'] = date("Y-m-d", strtotime($invoice_date));
        
        $data['amount'] = $una_settle_amount = $this->input->post('una_settle_amount');
        
        $cash_payment = $this->input->post('cash_payment');
        
        $k_rate = $this->input->post('txt_24k_rate');
        $gold_cash_payment = $this->input->post('gold_cash_payment');
        $gold_cash_amount = $this->input->post('txt_gold_cash_amount');
        $bal_gold_in_hand = $this->input->post('txt_gold_available_balance');
        
        $bank_account_ids = $this->input->post('bank_account_id');
        $bank_payment = $this->input->post('bank_payment');
        $bal_cash_at_bank = $this->input->post('txt_bank_available_balance');
        
        $settlement_creditor_ids = $this->input->post('settlement_creditor_id');
        $creditor_payment = $this->input->post('creditor_payment');
        
        $data['status'] = 'Completed';
        
        header('Content-Type: application/json');
        
        try {
            $una_ids = $this->input->post('una_ids');
            $una_payment_amount = $this->input->post('una_payment_amount');

            for ($y = 0; $y < count($una_ids); $y++) {

                $data['una_id'] = $una_ids[$y];

                $added_payment = $this->admin_db->add_una_payments($data);

                // Update UNA Balance
                $una_details = $this->admin_db->get_una_by_id($una_ids[$y]);

                $una['paid_amount'] = $una_details->paid_amount + $una_payment_amount[$y];
                $una['bal_amount'] = $bal_amount = $una_details->bal_amount - $una_payment_amount[$y];

                $this->admin_db->update_una_payment_amounts($una_ids[$y], $una);

                if($bal_amount == 0){

                    $this->admin_db->change_una_status($una_ids[$y], 1);
                }else{

                    $this->admin_db->change_una_status($una_ids[$y], 2);
                }


                $payment_items['una_payment_id'] = $payment_id = $added_payment['id'];

                if($cash_payment != ''){
                    $payment_items['item_type'] = 'Cash in hand';
                    $payment_items['item_id'] = NULL;
                    $payment_items['amount'] = $cash_payment;
                    $payment_items['description'] = '';
                    $this->admin_db->add_una_payment_items($payment_items);

                }

                if($gold_cash_payment != ''){
                    $payment_items['item_type'] = 'Gold';
                    $payment_items['item_id'] = NULL;
                    $payment_items['amount'] = $gold_cash_payment;
                    $payment_items['description'] = $gold_cash_amount.' g x Rs.'.$k_rate.'/8 = Rs.'.$gold_cash_payment;
                    $this->admin_db->add_una_payment_items($payment_items);
                }

                for ($x = 0; $x < count($bank_account_ids); $x++) {
                    if($bank_payment[$x] != ''){
                        $payment_items['item_type'] = 'Cash at bank';
                        $payment_items['item_id'] = $bank_account_ids[$x];
                        $payment_items['amount'] = $bank_payment[$x];
                        $payment_items['description'] = '';
                        $this->admin_db->add_una_payment_items($payment_items);

                    }
                }

                for ($x = 0; $x < count($settlement_creditor_ids); $x++) {
                    if($creditor_payment[$x] != ''){
                        $payment_items['item_type'] = 'Creditor';
                        $payment_items['item_id'] = $settlement_creditor_ids[$x];
                        $payment_items['amount'] = $creditor_payment[$x];
                        $payment_items['description'] = NULL;
                        $this->admin_db->add_una_payment_items($payment_items);
                    }
                }

            }

            $stock_details = $this->admin_db->get_stock_details();

            $creditor_payments['date'] = $data['date'];
            $creditor_payments['creditor_id'] = $creditor_id;
            $creditor_payments['payment_method'] = 'UNA Settlement';
            $creditor_payments['una_payment_id'] = $payment_id;
            $creditor_payments['account_id'] = NULL;
            $creditor_payments['cheque_number'] = NULL;
            $creditor_payments['cheque_deposit_date'] = NULL;
            $creditor_payments['third_party_bank_id'] = NULL;
            $creditor_payments['third_party_account_number'] = NULL;
            $creditor_payments['amount'] = $una_settle_amount;
            $creditor_payments['status'] = 'Completed';

            $this->admin_db->add_creditor_payments($creditor_payments);

            // Update UNA Creditor Balance
            $creditor_details = $this->admin_db->get_creditor_by_id($creditor_id);

            $amounts['una_paid_amount'] = $creditor_details->una_paid_amount + $una_settle_amount;
            $amounts['una_bal_amount'] = $creditor_details->una_bal_amount - $una_settle_amount;
            $amounts['paid_amount'] = $creditor_details->paid_amount;
            $amounts['bal_amount'] = $creditor_details->bal_amount;

            $this->admin_db->update_creditor_payment_amounts($creditor_id, $amounts);

            if($cash_payment != ''){
                $cash_in_hand = $stock_details->cash_in_hand;
                $new_cash_in_hand = $cash_in_hand - $cash_payment;

                $this->admin_db->update_stock_details('cash_in_hand', $new_cash_in_hand);

                $cash['action_date'] = $data['date'];
                $cash['item_type'] = 'una_payment';
                $cash['item_id'] = $payment_id;
                $cash['action_type'] = 'Debited';
                $cash['amount'] = $cash_payment;
                $cash['description'] = 'UNA Settlement For '.$creditor_details->creditor_name;

                $this->admin_db->add_cash_logs($cash);
            }

            if($gold_cash_payment != ''){
                $this->admin_db->update_stock_details('tf_gold_in_hand', $bal_gold_in_hand);

                $gold['item_type'] = 'una_payment';
                $gold['item_id'] = $payment_id;
                $gold['action_type'] = 'Debited';
                $gold['amount'] = $gold_cash_amount;
                $gold['description'] = 'UNA Settlement For '.$creditor_details->creditor_name;

                $this->admin_db->add_24k_gold_logs($gold);
            }

            for ($x = 0; $x < count($bank_account_ids); $x++) {

                if($bank_payment[$x] != ''){

                    $this->admin_db->update_bank_balance($bank_account_ids[$x], $bal_cash_at_bank[$x]);

                    $bank['account_id'] = $bank_account_ids[$x];
                    $bank['item_type'] = 'una_payment';
                    $bank['item_id'] = $payment_id;
                    $bank['action_type'] = 'Debited';
                    $bank['amount'] = $bank_payment[$x];
                    $bank['description'] = 'UNA Settlement For '.$creditor_details->creditor_name;

                    $this->admin_db->add_bank_account_logs($bank);

                }
            }

            for ($x = 0; $x < count($settlement_creditor_ids); $x++) {

                if($creditor_payment[$x] != ''){

                    $creditor_details = $this->admin_db->get_creditor_by_id($settlement_creditor_ids[$x]);

                    $account['creditor_id'] = $settlement_creditor_ids[$x];
                    $account['amount'] = $creditor_payment[$x];

                    $creditor_accounts['date'] = $data['date'];
                    $creditor_accounts['creditor_id'] = $settlement_creditor_ids[$x];
                    $creditor_accounts['item_type'] = 'UNA Settlement';
                    $creditor_accounts['item_id'] = NULL;
                    $creditor_accounts['amount'] = $creditor_payment[$x];
                    $creditor_accounts['description'] = NULL;

                    $this->admin_db->add_creditor_accounts($creditor_accounts);

                    $amounts['credit_amount'] = $creditor_details->amount + $creditor_payment[$x];
                    $amounts['credit_bal_amount'] = $creditor_details->bal_amount + $creditor_payment[$x];
                    $amounts['una_amount'] = $creditor_details->una_amount;
                    $amounts['una_bal_amount'] = $creditor_details->una_bal_amount;

                    $this->admin_db->update_creditor_amounts($settlement_creditor_ids[$x], $amounts);

                }
            }
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }

        echo json_encode(array("message" => "UNA Settlement Added Successfully", "status" => "1", "creditor_id" => $creditor_id));
           
    }
    
    public function view_creditor_account() {
        $id = $this->input->post('id');
        $data['credit_account_details'] = $this->admin_db->get_creditor_accounts_by_id($id);

        $this->load->view('dashboard/view_creditor_account', $data);
        
    }
    
    public function view_creditor_payment() {
        $id = $this->input->post('id');
        $data['payment_account_details'] = $this->admin_db->get_creditor_payments_by_id($id);

        $this->load->view('dashboard/view_creditor_payment', $data);
        
    }
    
    public function save_settle_una() {
        
        $data['una_id'] = $una_id = $this->input->post('una_id');
        $data['creditor_id'] = $creditor_id = $this->input->post('creditor_id');
        $invoice_date = $this->input->post('invoice_date');
        $data['date'] = date("Y-m-d", strtotime($invoice_date));
        
        $una_settle_bal_amount = $this->input->post('una_settle_bal_amount');
        $data['amount'] = $una_settle_amount = $this->input->post('una_settle_amount');
        
        $cash_payment = $this->input->post('cash_payment');
        $bal_cash_in_hand = $this->input->post('txt_cash_available_balance');
        
        $k_rate = $this->input->post('txt_24k_rate');
        $gold_cash_payment = $this->input->post('gold_cash_payment');
        $gold_cash_amount = $this->input->post('txt_gold_cash_amount');
        $bal_gold_in_hand = $this->input->post('txt_gold_available_balance');
        
        $bank_account_ids = $this->input->post('bank_account_id');
        $bank_payment = $this->input->post('bank_payment');
        $bal_cash_at_bank = $this->input->post('txt_bank_available_balance');
        
        $settlement_creditor_ids = $this->input->post('settlement_creditor_id');
        $creditor_payment = $this->input->post('creditor_payment');
        
        try {
            $data['status'] = 'Completed';
            $added_payment = $this->admin_db->add_una_payments($data);

            header('Content-Type: application/json');

            if($added_payment['status'] == 1){

                $payment_items['una_payment_id'] = $payment_id = $added_payment['id'];

                // Update UNA Balance
                $una_details = $this->admin_db->get_una_by_id($una_id);

                $una['paid_amount'] = $una_details->paid_amount + $una_settle_amount;
                $una['bal_amount'] = $bal_amount = $una_details->bal_amount - $una_settle_amount;

                $this->admin_db->update_una_payment_amounts($una_id, $una);

                if($bal_amount == 0){

                    $this->admin_db->change_una_status($una_id, 1);
                }else{

                    $this->admin_db->change_una_status($una_id, 2);
                }

                $stock_details = $this->admin_db->get_stock_details();

                // Update UNA Creditor Balance
                $creditor_details = $this->admin_db->get_creditor_by_id($creditor_id);

                $amounts['una_paid_amount'] = $creditor_details->paid_amount + $una_settle_amount;
                $amounts['una_bal_amount'] = $creditor_details->bal_amount - $una_settle_amount;
                $amounts['paid_amount'] = $creditor_details->paid_amount;
                $amounts['bal_amount'] = $creditor_details->bal_amount;

                $creditor_payments['date'] = $data['date'];
                $creditor_payments['creditor_id'] = $creditor_id;
                $creditor_payments['payment_method'] = 'UNA Settlement';
                $creditor_payments['una_payment_id'] = $payment_id;
                $creditor_payments['account_id'] = NULL;
                $creditor_payments['cheque_number'] = NULL;
                $creditor_payments['cheque_deposit_date'] = NULL;
                $creditor_payments['third_party_bank_id'] = NULL;
                $creditor_payments['third_party_account_number'] = NULL;
                $creditor_payments['amount'] = $una_settle_amount;
                $creditor_payments['status'] = 'Completed';

                $added_payment = $this->admin_db->add_creditor_payments($creditor_payments);

                $this->admin_db->update_creditor_payment_amounts($creditor_id, $amounts);

                if($cash_payment != ''){
                    $cash_in_hand = $stock_details->cash_in_hand;
                    $new_cash_in_hand = $cash_in_hand - $cash_payment;

                    $this->admin_db->update_stock_details('cash_in_hand', $new_cash_in_hand);

                    $cash['action_date'] = $data['date'];
                    $cash['item_type'] = 'una_payment';
                    $cash['item_id'] = $payment_id;
                    $cash['action_type'] = 'Debited';
                    $cash['amount'] = $cash_payment;
                    $cash['description'] = 'UNA Settlement For '.$creditor_details->creditor_name;

                    $this->admin_db->add_cash_logs($cash);

                    $payment_items['item_type'] = 'Cash in hand';
                    $payment_items['item_id'] = NULL;
                    $payment_items['amount'] = $cash_payment;
                    $payment_items['description'] = '';
                    $this->admin_db->add_una_payment_items($payment_items);
                }

                if($gold_cash_payment != ''){
                    $this->admin_db->update_stock_details('tf_gold_in_hand', $bal_gold_in_hand);

                    $gold['item_type'] = 'una_payment';
                    $gold['item_id'] = $payment_id;
                    $gold['action_type'] = 'Debited';
                    $gold['amount'] = $gold_cash_amount;
                    $gold['description'] = 'UNA Settlement For '.$creditor_details->creditor_name;

                    $this->admin_db->add_24k_gold_logs($gold);

                    $payment_items['item_type'] = 'Gold';
                    $payment_items['item_id'] = NULL;
                    $payment_items['amount'] = $gold_cash_payment;
                    $payment_items['description'] = $gold_cash_amount.' g x Rs.'.$k_rate.'/8 = Rs.'.$gold_cash_payment;
                    $this->admin_db->add_una_payment_items($payment_items);
                }

                for ($x = 0; $x < count($bank_account_ids); $x++) {

                    if($bank_payment[$x] != ''){

                        $this->admin_db->update_bank_balance($bank_account_ids[$x], $bal_cash_at_bank[$x]);

                        $bank['account_id'] = $bank_account_ids[$x];
                        $bank['item_type'] = 'una_payment';
                        $bank['item_id'] = $payment_id;
                        $bank['action_type'] = 'Debited';
                        $bank['amount'] = $bank_payment[$x];
                        $bank['description'] = 'UNA Settlement For '.$creditor_details->creditor_name;

                        $this->admin_db->add_bank_account_logs($bank);

                        $payment_items['item_type'] = 'Cash at bank';
                        $payment_items['item_id'] = $bank_account_ids[$x];
                        $payment_items['amount'] = $bank_payment[$x];
                        $payment_items['description'] = '';
                        $this->admin_db->add_una_payment_items($payment_items);

                    }
                }

                for ($x = 0; $x < count($settlement_creditor_ids); $x++) {

                    if($creditor_payment[$x] != ''){

                        $creditor_details = $this->admin_db->get_creditor_by_id($settlement_creditor_ids[$x]);

                        $account['creditor_id'] = $settlement_creditor_ids[$x];
                        $account['amount'] = $creditor_payment[$x];

                        $creditor_accounts['date'] = $data['date'];
                        $creditor_accounts['creditor_id'] = $settlement_creditor_ids[$x];
                        $creditor_accounts['item_type'] = 'UNA Settlement';
                        $creditor_accounts['item_id'] = $una_id;
                        $creditor_accounts['amount'] = $creditor_payment[$x];
                        $creditor_accounts['description'] = NULL;

                        $this->admin_db->add_creditor_accounts($creditor_accounts);

                        $amounts['credit_amount'] = $creditor_details->amount + $data['amount'];
                        $amounts['credit_bal_amount'] = $creditor_details->bal_amount + $data['amount'];
                        $amounts['una_amount'] = $creditor_details->una_amount;
                        $amounts['una_bal_amount'] = $creditor_details->una_bal_amount;

                        $this->admin_db->update_creditor_amounts($settlement_creditor_ids[$x], $amounts);

                        $payment_items['item_type'] = 'Creditor';
                        $payment_items['item_id'] = $settlement_creditor_ids[$x];
                        $payment_items['amount'] = $creditor_payment[$x];
                        $payment_items['description'] = NULL;
                        $this->admin_db->add_una_payment_items($payment_items);
                    }
                }

                echo json_encode(array("message" => "UNA Settlement Added Successfully", "status" => "1", "una_id" => $una_id));

            }else{
                echo json_encode(array("message" => "An Error Occured while Adding UNA Settlement", "status" => "0", "una_id" => $una_id));
            }    
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }    
        
    }

    public function view_una_payments()
    {
        $data['title'] = 'View UNA Payment Details';
        
        $una_payment_id = $this->input->get('una_payment_id');
        
        $data['una_payment_details'] = $this->admin_db->get_una_payments_by_id($una_payment_id);        
        $data['una_payment_items'] = $this->admin_db->get_una_payment_items_by_payment_id($una_payment_id);
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/view_una_payment', $data);
        $this->load->view('dashboard/footer');
    }

    public function view_payments()
    {
        $id = $this->input->get('payment_id');
        
        $data['title'] = 'View Payment Details';
        
        $data['payment_details'] = $this->admin_db->get_payment_details_by_id($id);  
        $data['payment_items'] = $this->admin_db->get_payment_items_by_payment_id($id);    
        
//        echo '<pre>'. print_r($data['payment_details'],1). '</pre>'; exit;
        
//        print_r($data['payment_items']);exit;
                
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/view_payment_details', $data);
        $this->load->view('dashboard/footer');
    }

    public function stock_balances()
    {
        $data['title'] = 'Stock Balances';
        
        $data['stock_details'] = $this->admin_db->get_stock_details();
        $data['last_cash_log'] = $this->admin_db->get_last_cash_log();
        $data['last_22k_gold_log'] = $this->admin_db->get_last_22k_gold_log();
        $data['last_24k_gold_log'] = $this->admin_db->get_last_24k_gold_log();
        
        $data['last_box_cash_log'] = $this->admin_db->get_last_box_cash_log();
        $data['last_box_22k_gold_log'] = $this->admin_db->get_last_box_22k_gold_log();
        $data['last_box_24k_gold_log'] = $this->admin_db->get_last_box_24k_gold_log();
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/stock_balances', $data);
        $this->load->view('dashboard/footer');
    }

    public function view_stock_balance()
    {
        $data['title'] = 'Stock Balance Details';
        $data['stock_name'] = $stock_name = $this->input->get('stock');
        
        $data['stock_details'] = $this->admin_db->get_stock_details();
        
        if($stock_name == 'DXB Cash'){
            $data['stock_log'] = $this->admin_db->get_last_cash_log();
        }elseif($stock_name == 'DXB 22K Gold'){
            $data['stock_log'] = $this->admin_db->get_last_22k_gold_log();
        }elseif($stock_name == 'DXB 24K Gold'){
            $data['stock_log'] = $this->admin_db->get_last_24k_gold_log();
        }elseif($stock_name == 'BOX Cash'){
            $data['stock_log'] = $this->admin_db->get_last_box_cash_log();
        }elseif($stock_name == 'BOX 22K Gold'){
            $data['stock_log'] = $this->admin_db->get_last_box_22k_gold_log();
        }elseif($stock_name == 'BOX 24K Gold'){
            $data['stock_log'] = $this->admin_db->get_last_box_24k_gold_log();
        }
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/view_stock_balance', $data);
        $this->load->view('dashboard/footer');
    }
    
    public function save_change_stock_balance()
    {
        $stock_name = $this->input->post('stock_name');
        $action_type = $this->input->post('credit_debit_balance');
        $stock_balance = $this->input->post('stock_balance');
        $description = $this->input->post('description');
        
        header('Content-Type: application/json');
            
        $stock_details = $this->admin_db->get_stock_details();
        
        try {
            if($stock_name == 'DXB Cash'){     

                $cash_in_hand = $stock_details->cash_in_hand;

                if($action_type == 'Credited'){
                    $new_cash_in_hand = $cash_in_hand - $stock_balance;
                }elseif($action_type == 'Debited'){
                    $new_cash_in_hand = $cash_in_hand + $stock_balance;
                }

                $up_balance = $this->admin_db->update_balance_stock('cash_in_hand', $new_cash_in_hand);

                $cash['action_date'] = date('Y-m-d');
                $cash['item_type'] = $stock_name.' Balance';
                $cash['item_id'] = 1;
                $cash['action_type'] = $action_type;
                $cash['amount'] = $stock_balance;
                $cash['description'] = 'Adjustment - '.$description;

                $this->admin_db->add_cash_logs($cash);

            }else if($stock_name == 'DXB 22K Gold'){

                $tt_gold_in_hand = $stock_details->tt_gold_in_hand;

                if($action_type == 'Credited'){
                    $new_tt_gold_in_hand = $tt_gold_in_hand - $stock_balance;
                }elseif($action_type == 'Debited'){
                    $new_tt_gold_in_hand = $tt_gold_in_hand + $stock_balance;
                }

                $up_balance = $this->admin_db->update_stock_details('tt_gold_in_hand', $new_tt_gold_in_hand);

                $account['item_type'] = $stock_name.' Balance';
                $account['item_id'] = 1;
                $account['action_type'] = $action_type;
                $account['amount'] = $stock_balance;
                $account['description'] = 'Adjustment - '.$description;

                $this->admin_db->add_22k_gold_logs($account);

            }else if($stock_name == 'DXB 24K Gold'){

                $tf_gold_in_hand = $stock_details->tf_gold_in_hand;

                if($action_type == 'Credited'){
                    $new_tf_gold_in_hand = $tf_gold_in_hand - $stock_balance;
                }elseif($action_type == 'Debited'){
                    $new_tf_gold_in_hand = $tf_gold_in_hand + $stock_balance;
                }

                $up_balance = $this->admin_db->update_stock_details('tf_gold_in_hand', $new_tf_gold_in_hand);

                $account['item_type'] = $stock_name.' Balance';
                $account['item_id'] = 1;
                $account['action_type'] = $action_type;
                $account['amount'] = $stock_balance;
                $account['description'] = 'Adjustment - '.$description;

                $this->admin_db->add_24k_gold_logs($account);

            }elseif($stock_name == 'BOX Cash'){     

                $box_cash_in_hand = $stock_details->box_cash_in_hand;

                if($action_type == 'Credited'){
                    $new_box_cash_in_hand = $box_cash_in_hand - $stock_balance;
                }elseif($action_type == 'Debited'){
                    $new_box_cash_in_hand = $box_cash_in_hand + $stock_balance;
                }

                $up_balance = $this->admin_db->update_balance_stock('box_cash_in_hand', $new_box_cash_in_hand);

                $cash['action_date'] = date('Y-m-d');
                $cash['item_type'] = $stock_name.' Balance';
                $cash['item_id'] = 1;
                $cash['action_type'] = $action_type;
                $cash['amount'] = $stock_balance;
                $cash['description'] = 'Adjustment - '.$description;

                $this->admin_db->add_box_cash_logs($cash);

            }else if($stock_name == 'BOX 22K Gold'){

                $box_tt_gold_in_hand = $stock_details->box_tt_gold_in_hand;

                if($action_type == 'Credited'){
                    $new_box_tt_gold_in_hand = $box_tt_gold_in_hand - $stock_balance;
                }elseif($action_type == 'Debited'){
                    $new_box_tt_gold_in_hand = $box_tt_gold_in_hand + $stock_balance;
                }

                $up_balance = $this->admin_db->update_stock_details('box_tt_gold_in_hand', $new_box_tt_gold_in_hand);

                $account['item_type'] = $stock_name.' Balance';
                $account['item_id'] = 1;
                $account['action_type'] = $action_type;
                $account['amount'] = $stock_balance;
                $account['description'] = 'Adjustment - '.$description;

                $this->admin_db->add_box_22k_gold_logs($account);

            }else if($stock_name == 'BOX 24K Gold'){

                $box_tf_gold_in_hand = $stock_details->box_tf_gold_in_hand;

                if($action_type == 'Credited'){
                    $new_box_tf_gold_in_hand = $box_tf_gold_in_hand - $stock_balance;
                }elseif($action_type == 'Debited'){
                    $new_box_tf_gold_in_hand = $box_tf_gold_in_hand + $stock_balance;
                }

                $up_balance = $this->admin_db->update_stock_details('tf_box_gold_in_hand', $new_box_tf_gold_in_hand);

                $account['item_type'] = $stock_name.' Balance';
                $account['item_id'] = 1;
                $account['action_type'] = $action_type;
                $account['amount'] = $stock_balance;
                $account['description'] = 'Adjustment - '.$description;

                $this->admin_db->add_box_24k_gold_logs($account);

            }  

            if($up_balance == true){
                echo json_encode(array("message" => "Stock Balance Changed Successfully", "status" => "1"));

            }else{
                echo json_encode(array("message" => "An Error Occured while Changing Rate", "status" => "0"));

            }
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }
    }

    public function daily_audits()
    {
        $data['title'] = 'Daily Audits';
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/daily_audits', $data);
        $this->load->view('dashboard/footer');
    }
    
    public function save_add_daily_audit_details()
    {
        $audit_date = $this->input->post('audit_date');
        $data['date'] = date("Y-m-d", strtotime($audit_date));
        $data['cash_balance'] = $this->input->post('cash_balance');
        $data['gold_balance'] = $this->input->post('gold_balance');
        $data['description'] = $this->input->post('description');
        
        header('Content-Type: application/json');
              
        $up_user = $this->admin_db->save_add_daily_audit_details($data);

        if($up_user == true){
            echo json_encode(array("message" => "Daily Audit Added Successfully", "status" => "1"));

        }else{
            echo json_encode(array("message" => "An Error Occured while Adding Daily Audit", "status" => "0"));

        }
    }

    public function change_daily_audit_status()
    {
        $id = $this->input->get('id');
        $status = $this->input->get('status');
        
        $this->admin_db->change_stock_item_status($id, $status);
        
        // 1 - active, 0 - deleted
        if ($status == 0) {
            echo json_encode(array("message" => "Stock Item Inactivated Successfully", "status" => "1"));
            
        }
    }

    public function view_daily_audit()
    {
        $id = $this->input->get('audit_id');
        
        $data['audit_details'] = $this->admin_db->get_audit_details_by_id($id);
        
        $data['title'] = 'Daily Audit Details';
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/daily_audit_details', $data);
        $this->load->view('dashboard/footer');
    }
    
    public function save_edit_daily_audit_details()
    {
        $id = $this->input->post('audit_id');
        $audit_date = $this->input->post('audit_date');
        $data['date'] = date("Y-m-d", strtotime($audit_date));
        $data['cash_balance'] = $this->input->post('cash_balance');
        $data['gold_balance'] = $this->input->post('gold_balance');
        $data['description'] = $this->input->post('description');
        
        header('Content-Type: application/json');
        
        $up_account = $this->admin_db->save_edit_daily_audit_details($id, $data);

        if($up_account == true){
            echo json_encode(array("message" => "Daily Audit Successfully Edited", "status" => "1", "audit_id" => $id));

        }else{
            echo json_encode(array("message" => "An Error Occured while Editing Daily Audit", "status" => "0", "audit_id" => $id));

        }
    }

    public function get_last_daily_audit()
    {
        $audit_details = $this->admin_db->get_last_daily_audit();
        header('Content-Type: application/x-json; charset=utf-8');
        
        if($audit_details){
            echo json_encode(date("d-m-Y", strtotime($audit_details->date)));
        }else{
            echo false;
        }
        
    }

    public function other_income()
    {
        $data['title'] = 'Other Income';
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/other_income', $data);
        $this->load->view('dashboard/footer');
    }
    
    public function save_add_other_income_details()
    {
        $income_date = $this->input->post('income_date');
        $data['date'] = date("Y-m-d", strtotime($income_date));
        $other_income = $this->input->post('other_income');
        
        if($other_income == 'Other'){
            $data['other_income'] = $this->input->post('txt_other_income');
            
        }else{
            $data['other_income'] = $other_income;
            
        }
        
        $select_customer = $this->input->post('select_customer');
        $data['payment_method'] = $payment_method = $this->input->post('payment_method');
        $data['description'] = $this->input->post('description');
        
        try {
            if($payment_method == 'Cash'){
                $data['cheq_bank'] = NULL;
                $data['cheq_cheque_number'] = NULL;
                $data['cheq_deposit_date'] = NULL;
                $data['deposit_bank_account'] = NULL;
                $data['status'] = 1;

            }else if($payment_method == 'Cheque'){
                $data['cheq_bank'] = $this->input->post('cheq_bank');
                $data['cheq_cheque_number'] = $this->input->post('cheq_cheque_number');
                $cheq_deposit_date = $this->input->post('cheq_deposit_date');
                $data['cheq_deposit_date'] = date("Y-m-d", strtotime($cheq_deposit_date));
                $data['deposit_bank_account'] = NULL;
                $data['status'] = 2;

            }else if($payment_method == 'Bank Deposit'){
                $data['deposit_bank_account'] = $bank_account_id = $this->input->post('deposit_bank_account');
                $data['cheq_bank'] = NULL;
                $data['cheq_cheque_number'] = NULL;
                $data['cheq_deposit_date'] = NULL;
                $data['status'] = 1;

            }

            $data['payment_amount'] = $payment_amount = $this->input->post('payment_amount');

            if($other_income != 'Other'){
                if($select_customer == "Add New Customer"){
                    $data['customer_name'] = $customer_name = $this->input->post('customer_name');
                    $data['contact_number'] = $customer_number = $this->input->post('contact_num');
                    $data['customer_type'] = $customer_type = $this->input->post('customer_type');
                    $data['tel_number'] = $this->input->post('tel_number');
                    $data['status'] = 1;
                    $data['debt_amount_gold'] = 0.000;
                    $data['debt_amount_cash'] = 0.00;
                    $data['over_paid_gold'] = 0.000;
                    $data['over_paid_cash'] = 0.00;
                    $data['box_debt_amount_gold'] = 0.000;
                    $data['box_debt_amount_cash'] = 0.00;
                    $data['box_over_paid_gold'] = 0.000;
                    $data['box_over_paid_cash'] = 0.00;

                    $added_customer = $this->admin_db->add_customer_details_sale($data);

                    $data['customer_id'] = $added_customer['id'];

                }else{
                    $data['customer_id'] = $select_customer;
                    $customer_details = $this->admin_db->get_customer_by_id($select_customer);
                    $customer_name = $customer_details->customer_name;

                }
                $log_description = 'Receipt Amount Received From '.$customer_name;
            }else{
                $data['customer_id'] = NULL;
                $log_description = 'Receipt Amount Received';
            }

            header('Content-Type: application/json');

            $added_other_income = $this->admin_db->add_other_income_details($data);

            if($added_other_income['status'] == 1){

                $stock_details = $this->admin_db->get_stock_details();

                if($payment_method == 'Cash'){
                    $cash_in_hand = $stock_details->cash_in_hand;
                    $new_cash_in_hand = $cash_in_hand + $payment_amount;

                    $this->admin_db->update_stock_details('cash_in_hand', $new_cash_in_hand);

                    $account['action_date'] = $data['date'];
                    $account['item_type'] = 'income';
                    $account['item_id'] = $added_other_income['id'];
                    $account['action_type'] = 'Credited';
                    $account['amount'] = $payment_amount;
                    $account['description'] = $log_description;

                    $this->admin_db->add_cash_logs($account);

                }

                if($payment_method == 'Cheque'){
                    $cheque['bank_id'] = $data['cheq_bank'];
                    $cheque['payment_id'] = $added_other_income['id'];
                    $cheque['customer_id'] = $data['customer_id'];
                    $cheque['cheque_type'] = 'Other Income';
                    $cheque['cheque_number'] = $data['cheq_cheque_number'];
                    $cheque['cheque_amount'] = $payment_amount;
                    $cheque['deposit_date'] = $data['cheq_deposit_date'];

                    $this->admin_db->add_cheque_details($cheque);

                }

                if($payment_method == 'Bank Deposit'){
                    $account_details = $this->admin_db->get_bank_account_by_id($bank_account_id);

                    $bank_balance = $account_details->bank_balance;
                    $new_bank_balance  = $bank_balance + $payment_amount;

                    $this->admin_db->update_bank_balance($bank_account_id, $new_bank_balance);

                    $account['account_id'] = $bank_account_id;
                    $account['item_type'] = 'other_income';
                    $account['item_id'] = $added_other_income['id'];
                    $account['action_type'] = 'Credited';
                    $account['amount'] = $payment_amount;
                    $account['description'] = $log_description;

                    $this->admin_db->add_bank_account_logs($account);

                }

                echo json_encode(array("message" => "Receipt Amount Added Successfully", "status" => "1"));
            }else{
                echo json_encode(array("message" => "An Error Occured while Adding Receipt Amount", "status" => "0"));

            }
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }
    }

    public function view_other_income()
    {
        $id = $this->input->get('other_income_id');
        
        $data['income_details'] = $this->admin_db->get_other_income_details_by_id($id);
        
        $data['title'] = 'View Other Income Details';
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/view_other_income', $data);
        $this->load->view('dashboard/footer');
    }

    public function box_sales()
    {
        $data['title'] = 'Box Sales';
        
        $data['all'] = "active";
        $data['pay_completed'] = "";
        $data['pay_incompleted'] = "";
        $data['pay_pending'] = "";
        
        $data['user_type'] = $this->session->userdata('user_type_id');
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/box_sales', $data);
        $this->load->view('dashboard/footer');
    }

    public function do_box_sales()
    {
        $data['title'] = 'Do Box Sales';
        $data['k_rate'] = $this->admin_db->get_rate_detail_by_id(1)->item_rate;
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/do_box_sales', $data);
        $this->load->view('dashboard/footer');
    }

    public function save_do_box_sale()
    {                
        $invoice_date = $this->input->post('invoice_date');
        $data['invoice_number'] = $this->input->post('invoice_number');
        $data['sale_type'] = $sale_type = $this->input->post('sale_type');
        $data['24k_rate'] = $rate = $this->input->post('24k_rate');
        $select_customer = $this->input->post('select_customer');
        $total_sum_credit = $this->input->post('debit_sum_txt_credit');
        $total_sum_gold = $this->input->post('debit_sum_txt_gold');
        $discount = $this->input->post('discount');
        
        $sale_data_credit = $this->input->post('sale_data_credit');
        $sale_data_gold = $this->input->post('sale_data_gold');
        
        $user_type = $this->session->userdata('user_type_id');
        
        $data['date'] = date("Y-m-d", strtotime($invoice_date));
        
        header('Content-Type: application/json');
        
        try {
            if($sale_type == "Credit Sale"){
                $data['total_amount'] = $total_sum_credit;
                $data['24k_rate'] = $rate;
            }else if($sale_type == "Gold Sale"){
                $data['total_amount'] = $total_sum_gold;
                $data['24k_rate'] = '';
            }

            if($select_customer == "Add New Customer"){
                $data['customer_name'] = $customer_name = $this->input->post('customer_name');
                $data['contact_number'] = $customer_number = $this->input->post('contact_num');
                $data['customer_type'] = $customer_type = $this->input->post('customer_type');
                $data['tel_number'] = $this->input->post('tel_number');

                if($customer_type == 'Walk-In'){
                    $data['status'] = 4;
                }else if($customer_type == 'Priority'){
                    $data['status'] = 1;
                }

                if($sale_type == "Credit Sale"){
                    if($user_type == 1){
                        $data['box_debt_amount_cash'] = $total_sum_credit;
                    }else{
                        $data['box_debt_amount_cash'] = 0.00;
                    }
                    $data['box_debt_amount_gold'] = 0.000;

                    $data['box_over_paid_gold'] = 0.000;
                    $data['box_over_paid_cash'] = 0.00;
                }else if($sale_type == "Gold Sale"){
                    if($user_type == 1){
                        $data['box_debt_amount_gold'] = $total_sum_gold;
                    }else{
                        $data['box_debt_amount_gold'] = 0.000;
                    }

                    $data['box_debt_amount_cash'] = 0.00;

                    $data['box_over_paid_gold'] = 0.000;
                    $data['box_over_paid_cash'] = 0.00;
                }

                $data['debt_amount_gold'] = 0.000;
                $data['debt_amount_cash'] = 0.00;
                $data['over_paid_gold'] = 0.000;
                $data['over_paid_cash'] = 0.00;

                $added_customer = $this->admin_db->add_customer_details_sale($data);

                $data['customer_id'] = $added_customer['id'];

            }else{
                $data['customer_id'] = $select_customer;

                if($user_type == 1){

                    $customer_details = $this->admin_db->get_customer_by_id($select_customer);

                    if($customer_details->customer_type == 'Walk-In'){
                        $this->admin_db->change_customer_status($select_customer, 4);
                    }

                    $debt_amount_gold = $customer_details->box_debt_amount_gold + $total_sum_gold;
                    $debt_amount_cash = $customer_details->box_debt_amount_cash + $total_sum_credit;

                    if($sale_type == "Credit Sale"){
                        $amounts['box_debt_amount_cash'] = $debt_amount_cash;
                        $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold;
                    }else if($sale_type == "Gold Sale"){
                        $amounts['box_debt_amount_gold'] = $debt_amount_gold;
                        $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash;
                    }

                    $amounts['box_over_paid_gold'] = $customer_details->box_over_paid_gold;
                    $amounts['box_over_paid_cash'] = $customer_details->box_over_paid_cash;

                    $this->admin_db->update_customer_box_accounts($select_customer, $amounts);

                }
            }

            $data['sale_category'] = 'Normal';
            $data['description'] = NULL;

            if($user_type != 1){

                $data['status'] = 4;   
                $added_sale = $this->admin_db->add_box_sale($data);

                if($sale_type == "Credit Sale"){
                    $amount = 'Rs. '.number_format($total_sum_credit,2,'.',',');
                }else if($sale_type == "Gold Sale"){
                    $amount = number_format($total_sum_gold,3,'.',',').' g';
                }

                $data['item_id'] = $added_sale['id'];
                $data['item_type'] = 'Box Sale';
                $data['amount'] = $amount;
                $data['description'] = NULL;
                $this->admin_db->add_approval_requests($data);

            }else{
                $data['status'] = 3;   
                $added_sale = $this->admin_db->add_box_sale($data);

                if($select_customer == "Add New Customer"){
                    $customer_name = $customer_name;
                    $customer_number = $customer_number;
                    $send_msg = 'true';
                }else{
                    $customer_details = $this->admin_db->get_customer_by_id($select_customer);
                    $customer_name = $customer_details->customer_name;
                    $customer_number = $customer_details->contact_number;
                    if($customer_details->send_sms == 1){
                        $send_msg = 'true';
                    }else{
                        $send_msg = 'false';
                    }
                }

                if($customer_number != '' && $send_msg == 'true'){
                    $customer_number = preg_replace('/^0/','94',$customer_number); 

    //            print_r($customer_number);exit;

                    if($sale_type == "Credit Sale"){
                        $total_sum = 'Rs. '.number_format($total_sum_credit,2,'.',',');
                    }else if($sale_type == "Gold Sale"){
                        $total_sum = number_format($total_sum_gold,3,'.',',').' g';
                    }

                    $text = 'Hi '.$customer_name.'!<br>Thank you doing business of '.$total_sum.'<br>Ref. No : '.$data['invoice_number'].'<br>Bill Date : '.$data['date'].'<br><br>AVA Jewellers';

                    $user = "94777979679";
                    $password = "1739";
                    $text = urlencode($text);
                    $to = $customer_number;

                    $baseurl ="http://www.textit.biz/sendmsg";
                    $url = "$baseurl/?id=$user&pw=$password&to=$to&text=$text";
                    $ret = get_web_page($url);
                }

            }

            $total_sale_grams = 0;

            if($sale_type == "Credit Sale"){
                for ($x = 0; $x < count($sale_data_credit['description']); $x++) {

                    $data1['sale_id'] = $added_sale['id'];
                    $data1['item_name'] = $sale_data_credit['item_name'][$x];
                    $data1['description'] = $sale_data_credit['description'][$x];
                    $data1['selling_percentage'] = $sale_data_credit['selling_percentage'][$x];
                    $data1['selling_rate'] = $sale_data_credit['selling_rate'][$x];
                    $data1['sales_grams'] = $sale_data_credit['sales_grams'][$x];
                    $data1['amount'] = $sale_data_credit['sub_total'][$x];

                    $total_sale_grams += $sale_data_credit['sales_grams'][$x];

                    $this->admin_db->add_box_sale_items($data1);

                }

            }else if($sale_type == "Gold Sale"){
                for ($x = 0; $x < count($sale_data_gold['selling_percentage']); $x++) {

                    $data1['sale_id'] = $added_sale['id'];
                    $data1['item_name'] = $sale_data_gold['item_name'][$x];
                    $data1['description'] = $sale_data_gold['description'][$x];
                    $data1['selling_percentage'] = $sale_data_gold['selling_percentage'][$x];
                    $data1['selling_rate'] = null;
                    $data1['sales_grams'] = $sale_data_gold['sales_grams'][$x];
                    $data1['amount'] = $sale_data_gold['sub_total'][$x];

                    $total_sale_grams += $sale_data_gold['sales_grams'][$x];

                    $this->admin_db->add_box_sale_items($data1);

                }
            }

            if($user_type == 1){

                $stock_details = $this->admin_db->get_stock_details();

                $box_tt_gold_in_hand = $stock_details->box_tt_gold_in_hand;
                $new_box_tt_gold_in_hand = $box_tt_gold_in_hand - $total_sale_grams;

                $this->admin_db->update_stock_details('box_tt_gold_in_hand', $new_box_tt_gold_in_hand);

                $customer_details = $this->admin_db->get_customer_by_id($data['customer_id']);

                $account['item_type'] = 'sale';
                $account['item_id'] = $added_sale['id'];
                $account['action_type'] = 'Debited';
                $account['amount'] = $total_sale_grams;
                $account['description'] = 'Sold To '.$customer_details->customer_name;

                $this->admin_db->add_box_22k_gold_logs($account);

                if($discount != ''){
                    $sale_details = $this->admin_db->get_sale_details_by_id($added_sale['id']);

                    $sale_amounts['discount_amount'] = $sale_details->discount_amount + $discount;
                    $sale_amounts['balance_amount'] = $sale_details->balance_amount - $discount;

                    $customer_details = $this->admin_db->get_customer_by_id($sale_details->customer_id);

                    if($sale_amounts['balance_amount'] <= 0){

                        if($customer_details->status == 4 && $customer_details->customer_type == 'Walk-In'){
                            $this->admin_db->change_customer_status($sale_details->customer_id, 1);
                        }

                        $this->admin_db->change_box_sale_status($added_sale['id'], 1);
                    }else{

                        $this->admin_db->change_box_sale_status($added_sale['id'], 2);
                    }

                    $this->admin_db->update_box_sale_discount_amount($added_sale['id'], $sale_amounts);

                    if($sale_details->sale_type == "Credit Sale"){

                        $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash - $discount;

                        $amounts['over_paid_cash'] = $customer_details->over_paid_cash;
                        $amounts['over_paid_gold'] = $customer_details->over_paid_gold;
                        $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold;

                    }else if($sale_details->sale_type == "Gold Sale"){

                        $amounts['debt_amount_gold'] = $customer_details->debt_amount_gold - $discount;

                        $amounts['over_paid_cash'] = $customer_details->over_paid_cash;
                        $amounts['over_paid_gold'] = $customer_details->over_paid_gold;
                        $amounts['debt_amount_cash'] = $customer_details->debt_amount_cash;
                    }

                    $this->admin_db->update_customer_box_accounts($sale_details->customer_id, $amounts);

                    $data['box_sale_id'] = $added_sale['id'];
                    $data['customer_id'] = $sale_details->customer_id;
                    $data['discount_amount'] = $discount;
                    $this->admin_db->add_box_sale_discount($data);
                }

            }
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }
        
        if($added_sale['status'] == 1){
            echo json_encode(array("message" => "Box Sale Added Successfully", "status" => "1"));
            
        }
    }

    public function view_box_sale()
    {
        $id = $this->input->get('box_sale_id');
        
        $data['title'] = 'View Box Sale Details';
        
        $data['sale_details'] = $this->admin_db->get_box_sale_details_by_id($id);
        $data['sale_items'] = $this->admin_db->get_box_sale_items_by_box_sale_id($id);    
        $data['payment_items'] = $this->admin_db->get_box_payment_items_by_box_sale_id($id);
        $data['fixing_items'] = $this->admin_db->get_box_fixing_details_by_box_sale_id($id);
        
        if($data['sale_details']->status == 4){
            $data['approval_details'] = $this->admin_db->get_approval_by_item_type_id('Box Sale', $id);
        }
        
//        echo '<pre>'. print_r($data['returned_sale_details'],1). '</pre>'; exit;
        
//        print_r($data['sale_details']);exit;
                
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/view_box_sale', $data);
        $this->load->view('dashboard/footer');
    }
    
    public function save_box_sale_discount()
    {     
        $data['sale_id'] = $sale_id = $this->input->post('sale_id');
        $data['customer_id'] = $customer_id = $this->input->post('customer_id');
        $discount_date = $this->input->post('discount_date');
        $data['date'] = date("Y-m-d", strtotime($discount_date));
        $data['discount_amount'] = $discount_amount = $this->input->post('discount_amount');
        $sale_type = $this->input->post('sale_type');
        
        $sale_details = $this->admin_db->get_box_sale_details_by_id($sale_id);
        
        $sale_amounts['discount_amount'] = $sale_details->discount_amount + $discount_amount;
        $sale_amounts['balance_amount'] = $sale_details->balance_amount - $discount_amount;
        
        $customer_details = $this->admin_db->get_customer_by_id($customer_id);

        try {
            if($sale_amounts['balance_amount'] <= 0){

                if($customer_details->status == 4 && $customer_details->customer_type == 'Walk-In'){
                    $this->admin_db->change_customer_status($customer_id, 1);
                }

                $this->admin_db->change_sale_status($sale_id, 1);
            }else{

                $this->admin_db->change_sale_status($sale_id, 2);
            }

            $this->admin_db->update_box_sale_discount_amount($sale_id, $sale_amounts);

            if($sale_type == "Credit Sale"){

                $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash - $discount_amount;

                $amounts['box_over_paid_cash'] = $customer_details->box_over_paid_cash;
                $amounts['box_over_paid_gold'] = $customer_details->box_over_paid_gold;
                $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold;

            }else if($sale_type == "Gold Sale"){

                $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold - $discount_amount;

                $amounts['box_over_paid_cash'] = $customer_details->box_over_paid_cash;
                $amounts['box_over_paid_gold'] = $customer_details->box_over_paid_gold;
                $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash;
            }

            $this->admin_db->update_customer_box_accounts($customer_id, $amounts);

            header('Content-Type: application/json');

            $this->admin_db->add_box_sale_discount($data);

            echo json_encode(array("message" => "Discount Added Successfully", "status" => "1", "sale_id" => $sale_id));
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }

    }

    public function delete_box_sale()
    {
        $id = $this->input->get('id');
        $status = $this->input->get('status');
        
        try {
            $status_updated = $this->admin_db->change_box_sale_status($id, $status);
            $status_updated = true;
            if($status_updated == true){

                // 6 - Deleted
                if ($status == 6) {

                    $data['success_msg'] = 'Sale Deleted Successfully';

                    $sale_items = $this->admin_db->get_box_sale_items_by_box_sale_id($id);

                    if ($sale_items) {

                        $total_sale_grams = 0;

                        foreach($sale_items as $sale_item){

                            $total_sale_grams += $sale_item['sales_grams'];

                        }

                        $stock_details = $this->admin_db->get_stock_details();

                        $box_tt_gold_in_hand = $stock_details->box_tt_gold_in_hand;
                        $new_box_tt_gold_in_hand = $box_tt_gold_in_hand + $total_sale_grams;

                        $this->admin_db->update_stock_details('box_tt_gold_in_hand', $new_box_tt_gold_in_hand);

                        $account['item_type'] = 'delete sale';
                        $account['item_id'] = $id;
                        $account['action_type'] = 'Credited';
                        $account['amount'] = $total_sale_grams;
                        $account['description'] = 'Sale Deleted. Sale No.'.$id;

                        $this->admin_db->add_box_22k_gold_logs($account);

                    }

                    $sale_details = $this->admin_db->get_box_sale_details_by_id($id);

                    $customer_details = $this->admin_db->get_customer_by_id($sale_details->customer_id);

                    $paid_amount = $sale_details->total_amount - $sale_details->balance_amount;

                    if($sale_details->sale_type == 'Credit Sale'){
                        if($paid_amount == 0){

                            $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash - $sale_details->balance_amount;
                            $amounts['box_over_paid_cash'] = $customer_details->box_over_paid_cash;
                            $amounts['box_over_paid_gold'] = $customer_details->box_over_paid_gold;
                            $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold;

                        }else{

                            $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash - $sale_details->balance_amount;
                            $amounts['box_over_paid_cash'] = $customer_details->box_over_paid_cash + $paid_amount;
                            $amounts['box_over_paid_gold'] = $customer_details->box_over_paid_gold;
                            $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold;

                        }
                    }elseif($sale_details->sale_type == 'Gold Sale'){
                        if($paid_amount == 0){

                            $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold - $sale_details->balance_amount;
                            $amounts['box_over_paid_gold'] = $customer_details->box_over_paid_gold;
                            $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash;
                            $amounts['box_over_paid_cash'] = $customer_details->box_over_paid_cash;

                        }else{

                            $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold - $sale_details->balance_amount;
                            $amounts['box_over_paid_gold'] = $customer_details->box_over_paid_gold + $paid_amount;
                            $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash;
                            $amounts['box_over_paid_cash'] = $customer_details->box_over_paid_cash;

                        }

                    }

                    $this->admin_db->update_customer_box_accounts($sale_details->customer_id, $amounts);

                }
            }

            redirect(base_url().'view_box_sale?box_sale_id='.$sale_details->id);
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }

    }

    public function print_box_sale()
    {
        $id = $this->input->get('sale_id');
        
        $data['title'] = 'View Box Sale Details';
        
        $data['sale_details'] = $this->admin_db->get_box_sale_details_by_id($id);
        $data['sale_items'] = $this->admin_db->get_box_sale_items_by_box_sale_id($id);    
        $data['payment_items'] = $this->admin_db->get_box_payment_items_by_box_sale_id($id);
        $data['fixing_items'] = $this->admin_db->get_box_fixing_details_by_box_sale_id($id);
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/print_box_sale', $data);
        $this->load->view('dashboard/footer');
    }

    public function save_make_normal_box_payment()
    {     
        
        $data['sale_id'] = $sale_id = $this->input->post('sale_id');
        $data['customer_id'] = $customer_id = $this->input->post('customer_id');
        $invoice_date = $this->input->post('invoice_date');
        $data['date'] = date("Y-m-d", strtotime($invoice_date));
        
        $data['payment_method'] = $payment_method = $this->input->post('payment_method');
        
        if($payment_method == 'Gold'){
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 1;
            
        }elseif($payment_method == 'Over Paid Gold'){
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 1;
            
        }elseif($payment_method == 'Over Paid Cash'){
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 1;
            
        }elseif($payment_method == 'Cash'){
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 1;
            
        }else if($payment_method == 'Cheque'){
            $data['cheq_bank'] = $this->input->post('cheq_bank');
            $data['cheq_cheque_number'] = $this->input->post('cheq_cheque_number');
            $cheq_deposit_date = $this->input->post('cheq_deposit_date');
            $data['cheq_deposit_date'] = date("Y-m-d", strtotime($cheq_deposit_date));
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 2;
            
        }else if($payment_method == 'Bank Deposit'){
            $data['deposit_bank_account'] = $bank_account_id = $this->input->post('deposit_bank_account');
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['status'] = 1;
            
        }
        
        try {
            $payment_total = $this->input->post('payment_total');
            $data['payment_amount'] = $payment_amount = $this->input->post('payment_amount');
            $data['payment_type'] = 'Normal';

            header('Content-Type: application/json');

            $added_payment = $this->admin_db->add_box_payment_details($data);

            $added_payment['status'] = 1;

            if($added_payment['status'] == 1){
                $data['payment_id'] = $added_payment['id'];
                $this->admin_db->add_box_payment_items($data);
                
                $sale_details = $this->admin_db->get_box_sale_by_id($sale_id);

                if($payment_method != 'Cheque'){

                    $balance_total = $payment_total - $payment_amount;

                    if($balance_total < 0){
                        $this->admin_db->update_box_sale_bal_amount($sale_id, 0);
                        $payment_amount = $payment_total;
                    }else{
                        $this->admin_db->update_box_sale_bal_amount($sale_id, $balance_total);

                    }

                    $customer_details = $this->admin_db->get_customer_by_id($customer_id);
                    
                    if($sale_details->status != 4){

                        if($balance_total <= 0){

                            if($customer_details->status == 4 && $customer_details->customer_type == 'Walk-In'){
                                $this->admin_db->change_customer_status($customer_id, 1);
                            }

                                $this->admin_db->change_box_sale_status($sale_id, 1);
                        }else{

                            $this->admin_db->change_box_sale_status($sale_id, 2);
                        }

                        if($payment_method == "Gold"){

                            if($balance_total < 0){

                                $new_box_over_paid_gold = $customer_details->box_over_paid_gold + abs($balance_total);
                                $amounts['box_over_paid_gold'] = $new_box_over_paid_gold;

                            }else{

                                $amounts['box_over_paid_gold'] = $customer_details->box_over_paid_gold;

                            }

                            $amounts['box_over_paid_cash'] = $customer_details->box_over_paid_cash;
                            $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold - $payment_amount;
                            $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash;

                        }elseif($payment_method == "Over Paid Gold"){

                            $new_box_over_paid_gold = $customer_details->box_over_paid_gold - $payment_amount;
                            $amounts['box_over_paid_gold'] = $new_box_over_paid_gold;

                            if($balance_total < 0){

                                $box_over_paid_gold = $customer_details->box_over_paid_gold - $payment_amount;
                                $new_box_over_paid_gold = $box_over_paid_gold + ($payment_amount - $payment_total);

                                $amounts['box_over_paid_gold'] = $new_box_over_paid_gold;

                            }

                            $amounts['box_over_paid_cash'] = $customer_details->box_over_paid_cash;
                            $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold - $payment_amount;
                            $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash;

                        }elseif($payment_method == "Over Paid Cash"){

                            $new_box_over_paid_cash = $customer_details->box_over_paid_cash - $payment_amount;
                            $amounts['box_over_paid_cash'] = $new_box_over_paid_cash;

                            if($balance_total < 0){

                                $box_over_paid_cash = $customer_details->box_over_paid_cash - $payment_amount;
                                $new_box_over_paid_cash = $box_over_paid_cash + ($payment_amount - $payment_total);

                                $amounts['box_over_paid_cash'] = $new_box_over_paid_cash;

                            }

                            $amounts['box_over_paid_gold'] = $customer_details->box_over_paid_gold;
                            $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold;
                            $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash - $payment_amount;

                        }else{

                            if($balance_total < 0){

                                $new_box_over_paid_cash = $customer_details->box_over_paid_cash + abs($balance_total);
                                $amounts['box_over_paid_cash'] = $new_box_over_paid_cash;

                            }else{

                                $amounts['box_over_paid_cash'] = $customer_details->box_over_paid_cash;

                            }

                            $amounts['box_over_paid_gold'] = $customer_details->box_over_paid_gold;
                            $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold;
                            $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash - $payment_amount;

                        }

                        $this->admin_db->update_customer_box_accounts($customer_id, $amounts);
                    }

                }
                
                if($sale_details->status != 4){

                    $stock_details = $this->admin_db->get_stock_details();

                    if($payment_method == 'Cash'){
                        $box_cash_in_hand = $stock_details->box_cash_in_hand;
                        $new_box_cash_in_hand = $box_cash_in_hand + $payment_amount;

                        $this->admin_db->update_stock_details('box_cash_in_hand', $new_box_cash_in_hand);

                        $account['action_date'] = $data['date'];
                        $account['item_type'] = 'receipt amount';
                        $account['item_id'] = $added_payment['id'];
                        $account['action_type'] = 'Credited';
                        $account['amount'] = $payment_amount;
                        $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                        $this->admin_db->add_box_cash_logs($account);

                    }

                    if($payment_method == 'Cheque'){
                        $cheque['bank_id'] = $data['cheq_bank'];
                        $cheque['payment_id'] = $added_payment['id'];
                        $cheque['customer_id'] = $customer_id;
                        $cheque['cheque_type'] = 'Box Sale';
                        $cheque['cheque_number'] = $data['cheq_cheque_number'];
                        $cheque['cheque_amount'] = $payment_amount;
                        $cheque['deposit_date'] = $data['cheq_deposit_date'];

                        $this->admin_db->add_cheque_details($cheque);

                    }

                    if($payment_method == 'Gold'){
                        $box_tf_gold_in_hand = $stock_details->box_tf_gold_in_hand;
                        $new_box_tf_gold_in_hand = $box_tf_gold_in_hand + $payment_amount;

                        $this->admin_db->update_stock_details('box_tf_gold_in_hand', $new_box_tf_gold_in_hand);

                        $account['item_type'] = 'receipt amount';
                        $account['item_id'] = $added_payment['id'];
                        $account['action_type'] = 'Credited';
                        $account['amount'] = $payment_amount;
                        $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                        $this->admin_db->add_box_24k_gold_logs($account);

                    }

                    if($payment_method == 'Bank Deposit'){
                        $account_details = $this->admin_db->get_bank_account_by_id($bank_account_id);

                        $bank_balance = $account_details->bank_balance;
                        $new_bank_balance  = $bank_balance + $payment_amount;

                        $this->admin_db->update_bank_balance($bank_account_id, $new_bank_balance);

                        $account['account_id'] = $bank_account_id;
                        $account['item_type'] = 'receipt amount';
                        $account['item_id'] = $added_payment['id'];
                        $account['action_type'] = 'Credited';
                        $account['amount'] = $payment_amount;
                        $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                        $this->admin_db->add_box_bank_account_logs($account);

                    }
                }

                echo json_encode(array("message" => "Payment Made Successfully", "status" => "1", "sale_id" => $sale_id));

            }else{
                echo json_encode(array("message" => "Error Occured while making the payment", "status" => "0", "sale_id" => $sale_id));

            }
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }
    }

    public function save_make_fixing_box_payment()
    {        
        $data['sale_id'] = $sale_id = $this->input->post('sale_id');
        $data['customer_id'] = $customer_id = $this->input->post('customer_id');
        $invoice_date = $this->input->post('invoice_date');
        $data['date'] = date("Y-m-d", strtotime($invoice_date));
        $data['invoice_number'] = $this->input->post('invoice_number');
        $data['24k_rate'] = $this->input->post('k_rate_fixing');
        $fixing_payment_amount = $this->input->post('fixing_payment_amount');
        $payment_total_in_grams = $this->input->post('payment_total_in_grams');
        $fixing_balance_total_in_grams = $this->input->post('fixing_balance_total_in_grams');
        
        $data['payment_method'] = $payment_method = $this->input->post('payment_method');
        
        if($payment_method == 'Gold'){
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 1;
            
        }elseif($payment_method == 'Cash'){
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 1;
            
        }else if($payment_method == 'Cheque'){
            $data['cheq_bank'] = $this->input->post('cheq_bank');
            $data['cheq_cheque_number'] = $this->input->post('cheq_cheque_number');
            $cheq_deposit_date = $this->input->post('cheq_deposit_date');
            $data['cheq_deposit_date'] = date("Y-m-d", strtotime($cheq_deposit_date));
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 2;
            
        }else if($payment_method == 'Bank Deposit'){
            $data['deposit_bank_account'] = $bank_account_id = $this->input->post('deposit_bank_account');
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['status'] = 1;
            
        }
        
        $data['payment_amount'] = $payment_amount = $this->input->post('fixing_payment_amount');
        $data['payment_type'] = 'Fixing';
        
        header('Content-Type: application/json');
        
        try {
            $added_payment = $this->admin_db->add_box_payment_details($data);

            if($added_payment['status'] == 1){
                $data['payment_id'] = $added_payment['id'];
                $added_payment_item = $this->admin_db->add_box_payment_items($data);
                $data['payment_item_id'] = $added_payment_item['id'];

                $data['paid_amount_in_cash'] = $fixing_payment_amount;
                $data['paid_amount_in_gold'] = $payment_total_in_grams - $fixing_balance_total_in_grams;

    //            print_r($data);exit;
                $this->admin_db->add_fixing_box_payments($data);

                if($payment_method != 'Cheque'){

                    $balance_total = $this->input->post('fixing_balance_total_in_grams');

                    $this->admin_db->update_box_sale_bal_amount($sale_id, $balance_total);

                    $customer_details = $this->admin_db->get_customer_by_id($customer_id);

                    if($balance_total <= 0){

                        if($customer_details->status == 4 && $customer_details->customer_type == 'Walk-In'){
                            $this->admin_db->change_customer_status($customer_id, 1);
                        }

                        $this->admin_db->change_sale_status($sale_id, 1);
                    }else{

                        $this->admin_db->change_sale_status($sale_id, 2);
                    }

                    $box_debt_amount_gold = $customer_details->box_debt_amount_gold - $data['paid_amount_in_gold'];

                    $amounts['box_debt_amount_gold'] = $box_debt_amount_gold;
                    $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash;

                    $amounts['box_over_paid_gold'] = $customer_details->box_over_paid_gold;
                    $amounts['box_over_paid_cash'] = $customer_details->box_over_paid_cash;

                    $this->admin_db->update_customer_box_accounts($customer_id, $amounts);

                }

                $stock_details = $this->admin_db->get_stock_details();

                if($payment_method == 'Cash'){
                    $box_cash_in_hand = $stock_details->box_cash_in_hand;
                    $new_box_cash_in_hand = $box_cash_in_hand + $payment_amount;

                    $this->admin_db->update_stock_details('box_cash_in_hand', $new_box_cash_in_hand);

                    $account['action_date'] = $data['date'];
                    $account['item_type'] = 'receipt amount';
                    $account['item_id'] = $added_payment['id'];
                    $account['action_type'] = 'Credited';
                    $account['amount'] = $payment_amount;
                    $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                    $this->admin_db->add_box_cash_logs($account);

                }

                if($payment_method == 'Cheque'){
                    $cheque['bank_id'] = $data['cheq_bank'];
                    $cheque['payment_id'] = $added_payment['id'];
                    $cheque['customer_id'] = $customer_id;
                    $cheque['cheque_type'] = 'Box Sale';
                    $cheque['cheque_number'] = $data['cheq_cheque_number'];
                    $cheque['cheque_amount'] = $payment_amount;
                    $cheque['deposit_date'] = $data['cheq_deposit_date'];

                    $this->admin_db->add_cheque_details($cheque);

                }

                if($payment_method == 'Gold'){
                    $box_tf_gold_in_hand = $stock_details->box_tf_gold_in_hand;
                    $new_box_tf_gold_in_hand = $box_tf_gold_in_hand + $payment_amount;

                    $this->admin_db->update_stock_details('box_tf_gold_in_hand', $new_box_tf_gold_in_hand);

                    $account['item_type'] = 'receipt amount';
                    $account['item_id'] = $added_payment['id'];
                    $account['action_type'] = 'Credited';
                    $account['amount'] = $payment_amount;
                    $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                    $this->admin_db->add_box_24k_gold_logs($account);

                }

                if($payment_method == 'Bank Deposit'){
                    $account_details = $this->admin_db->get_bank_account_by_id($bank_account_id);

                    $bank_balance = $account_details->bank_balance;
                    $new_bank_balance  = $bank_balance + $payment_amount;

                    $this->admin_db->update_bank_balance($bank_account_id, $new_bank_balance);

                    $account['account_id'] = $bank_account_id;
                    $account['item_type'] = 'receipt amount';
                    $account['item_id'] = $added_payment['id'];
                    $account['action_type'] = 'Credited';
                    $account['amount'] = $payment_amount;
                    $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                    $this->admin_db->add_box_bank_account_logs($account);

                }

                echo json_encode(array("message" => "Payment Made Successfully", "status" => "1", "sale_id" => $sale_id));

            }else{
                echo json_encode(array("message" => "Error Occured while making the payment", "status" => "0", "sale_id" => $sale_id));

            }
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }
    }
    
    public function save_return_box_sale()
    {                
        $data['sale_id'] = $sale_id = $this->input->post('sale_id');
        $data['customer_id'] = $customer_id = $this->input->post('customer_id');
        $invoice_date = $this->input->post('return_date');
        $data['date'] = date("Y-m-d", strtotime($invoice_date));
        $data['sale_type'] = $sale_type = $this->input->post('sale_type');
        $data['description'] = $this->input->post('description');
        
        $sale_item_ids = $this->input->post('item_id_ret_sale');
        
        $item_amount = $this->input->post('txt_ret_sale_item_amount');
        $item_name = $this->input->post('item_name_ret_sale');
        $item_description = $this->input->post('item_description_ret_sale');
        $selling_percentage = $this->input->post('selling_percentage_ret_sale');
        $selling_rate = $this->input->post('selling_rate_ret_sale');
        $sales_grams = $this->input->post('sales_grams_ret_sale');
        $actual_grams = $this->input->post('actual_grams_ret_sale');
        
        $total_return_sale_amount = 0;
        $total_return_sale_grams = 0;
        
        for ($x = 0; $x < count($sale_item_ids); $x++) {
            if($item_amount[$x] != ''){
                $total_return_sale_amount += $item_amount[$x];
                $total_return_sale_grams += $sales_grams[$x];
            }
        }
        
        try {
            $sale_details = $this->admin_db->get_box_sale_details_by_id($sale_id);

            $customer_details = $this->admin_db->get_customer_by_id($customer_id);

            $sale_amounts['balance_amount'] = $sale_details->balance_amount - $total_return_sale_amount;
            $sale_amounts['return_sale_amount'] = $sale_details->return_sale_amount + $total_return_sale_amount;

            if($sale_amounts['balance_amount'] <= 0){

                if($customer_details->status == 4 && $customer_details->customer_type == 'Walk-In'){
                    $this->admin_db->change_customer_status($customer_id, 1);
                }

                $this->admin_db->change_sale_status($sale_id, 1);
            }else{

                $this->admin_db->change_sale_status($sale_id, 2);
            }
            $this->admin_db->update_return_box_sale_amounts($sale_id, $sale_amounts);

            if($sale_type == "Credit Sale"){

                if($customer_details->box_debt_amount_cash == '' || $customer_details->box_debt_amount_cash == 0.00){
                    $amounts['box_over_paid_cash'] = $customer_details->box_over_paid_cash + $total_return_sale_amount;
                    $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash;
                }else{
                    $amounts['box_over_paid_cash'] = $customer_details->box_over_paid_cash;
                    $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash - $total_return_sale_amount;
                }

                $amounts['box_over_paid_gold'] = $customer_details->box_over_paid_gold;
                $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold;

            }else if($sale_type == "Gold Sale"){

                if($customer_details->box_debt_amount_gold == '' || $customer_details->box_debt_amount_gold == 0.00){
                    $amounts['box_over_paid_gold'] = $customer_details->box_over_paid_gold + $total_return_sale_amount;
                    $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold;
                }else{
                    $amounts['box_over_paid_gold'] = $customer_details->box_over_paid_gold;
                    $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold - $total_return_sale_amount;
                }

                $amounts['box_over_paid_cash'] = $customer_details->box_over_paid_cash;
                $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash;
            }

            $this->admin_db->update_customer_box_accounts($customer_id, $amounts);

            header('Content-Type: application/json');

            if($sale_type == 'Credit Sale'){
                $data['24k_rate'] = $this->input->post('k_rate_ret_sale');
            }else{
                $data['24k_rate'] = NULL; 
            }

            $data['amount'] = $total_return_sale_amount;

            $added_return_sale = $this->admin_db->add_return_box_sale($data);

            $total_sale_grams = 0;

            for ($x = 0; $x < count($sale_item_ids); $x++) {
                if($item_amount[$x] != ''){
                    $added_ret_sale_item['return_sale_id'] = $added_return_sale['id'];
                    $added_ret_sale_item['item_id'] = $sale_item_ids[$x];
                    $added_ret_sale_item['selling_percentage'] = $selling_percentage[$x];
                    $added_ret_sale_item['selling_rate'] = $selling_rate[$x];
                    $added_ret_sale_item['sales_grams'] = $sales_grams[$x];
                    $added_ret_sale_item['item_name'] = $item_name[$x];
                    $added_ret_sale_item['description'] = $item_description[$x];
                    $added_ret_sale_item['amount'] = $item_amount[$x];

                    $total_sale_grams += $sales_grams[$x];

                    $this->admin_db->add_return_box_sale_items($added_ret_sale_item);  

                    $actual_grams_after_ret = $actual_grams[$x] - $sales_grams[$x];

                    $this->admin_db->update_box_sale_item_actual_grams($sale_item_ids[$x], $actual_grams_after_ret); 

                }
            }

            $stock_details = $this->admin_db->get_stock_details();

            $box_tt_gold_in_hand = $stock_details->box_tt_gold_in_hand;
            $new_box_tt_gold_in_hand = $box_tt_gold_in_hand + $total_sale_grams;

            $this->admin_db->update_stock_details('box_tt_gold_in_hand', $new_box_tt_gold_in_hand);

            $account['item_type'] = 'return sale';
            $account['item_id'] = $added_return_sale['id'];
            $account['action_type'] = 'Credited';
            $account['amount'] = $total_sale_grams;
            $account['description'] = 'Returned Sale From '.$customer_details->customer_name;

            $this->admin_db->add_box_22k_gold_logs($account);

            echo json_encode(array("message" => "Sale Return Added Successfully", "status" => "1", "sale_id" => $sale_id));
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }

    }

    public function view_returned_box_sale()
    {
        $return_box_sale_id = $this->input->get('return_box_sale_id');
        
        $data['title'] = 'View Returned Sale Details';
        
        $data['returned_sale_details'] = $this->admin_db->get_returned_box_sale_details_by_id($return_box_sale_id);
        
        if($data['returned_sale_details']){
            $data['returned_sale_items'] = $this->admin_db->get_returned_box_sale_items_by_returned_box_sale_id($return_box_sale_id);
            
        }else{
            $data['returned_sale_items'] = '';
            
        }
                
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/view_returned_sale', $data);
        $this->load->view('dashboard/footer');
    }

    public function print_returned_box_sale()
    {
        $return_sale_id = $this->input->get('return_sale_id');
        
        $data['title'] = 'View Returned Sale Details';
        
        $data['returned_sale_details'] = $this->admin_db->get_returned_sale_details_by_id($return_sale_id);
        
        $data['returned_sale_items'] = $this->admin_db->get_returned_sale_items_by_returned_sale_id($return_sale_id);
        
                
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/print_returned_box_sale', $data);
        $this->load->view('dashboard/footer');
    }

    public function box_debtors()
    {
        $data['title'] = 'Box Debtors';
        
        $data['active'] = "active";
        $data['inactive'] = "";
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/box_debtors', $data);
        $this->load->view('dashboard/footer');
    }

    public function view_box_debtor()
    {
        $id = $this->input->get('customer_id');
        $data['debtor_type'] = $debtor_type = $this->input->get('debtor_type');
        
        $data['title'] = 'View Box Debtor Details';
        
        if($debtor_type == 'credit'){
            $sales_type = 'Credit Sale';
        }elseif($debtor_type == 'gold'){
            $sales_type = 'Gold Sale';
        }
        
        $statuses = [2, 3];
        
        $data['customer_details'] = $this->admin_db->get_customer_by_id($id);
        $data['credit_sale_details'] = $this->admin_db->get_box_debt_details_by_cus_id($id, $statuses, 'Credit Sale');
        $data['gold_sale_details'] = $this->admin_db->get_box_debt_details_by_cus_id($id, $statuses, 'Gold Sale');
        $data['tot_credit_sale_details'] = $this->admin_db->get_summery_box_debt_details_by_cus_id($id, $statuses, 'Credit Sale');
        $data['tot_gold_sale_details'] = $this->admin_db->get_summery_box_debt_details_by_cus_id($id, $statuses, 'Gold Sale');
        $data['sale_items'] = $this->admin_db->get_box_sale_items_by_sale_id($id);
        $data['payment_items'] = $this->admin_db->get_box_payment_items_by_sale_id($id);
        $data['pending_cheques'] = $this->admin_db->get_box_sale_cheques_by_customer_id($id, 'Pending');
        
//        echo '<pre>'. print_r($data['customer_details'],1). '</pre>'; exit;
        
//        print_r($data['payment_items']);exit;
                
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/view_box_debtor', $data);
        $this->load->view('dashboard/footer');
    }

    public function save_make_normal_debtor_box_payment()
    {                  
        $data['customer_id'] = $customer_id = $this->input->post('customer_id');
        $invoice_date = $this->input->post('invoice_date');
        $data['date'] = date("Y-m-d", strtotime($invoice_date));
        
        $data['payment_method'] = $payment_method = $this->input->post('payment_method');
        
        if($payment_method == 'Gold'){
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 1;
            
        }elseif($payment_method == 'Over Paid Gold'){
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 1;
            
        }elseif($payment_method == 'Over Paid Cash'){
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 1;
            
        }elseif($payment_method == 'Cash'){
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 1;
            
        }else if($payment_method == 'Cheque'){
            $data['cheq_bank'] = $this->input->post('cheq_bank');
            $data['cheq_cheque_number'] = $this->input->post('cheq_cheque_number');
            $cheq_deposit_date = $this->input->post('cheq_deposit_date');
            $data['cheq_deposit_date'] = date("Y-m-d", strtotime($cheq_deposit_date));
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 2;
            
        }else if($payment_method == 'Bank Deposit'){
            $data['deposit_bank_account'] = $bank_account_id = $this->input->post('deposit_bank_account');
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['status'] = 1;
            
        }
        
        try {
            if($payment_method == 'Gold' || $payment_method == 'Over Paid Gold'){
                $data['payment_amount'] = $payment_amount = $this->input->post('payment_amount_gold');
                $payment_amounts = $this->input->post('debtor_payment_amount_gold');
                $balance_amounts = $this->input->post('debtor_balance_amount_gold');
                $tot_payment_amount = $this->input->post('tot_payment_amount_gold');
                $sale_ids = $this->input->post('sale_ids_gold');

                $tot_balance_amount = $payment_amount - $tot_payment_amount;

                if($tot_balance_amount > 0 && min($balance_amounts) > 0 || $tot_balance_amount > 0){

                    $customer_details = $this->admin_db->get_customer_by_id($customer_id);

                    $amounts['box_over_paid_gold'] = $customer_details->box_over_paid_gold + $tot_balance_amount;
                    $amounts['box_over_paid_cash'] = $customer_details->box_over_paid_cash;
                    $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold;
                    $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash;

                    $this->admin_db->update_customer_box_accounts($customer_id, $amounts);

                }

            }else{
                $data['payment_amount'] = $payment_amount = $this->input->post('payment_amount_credit');
                $payment_amounts = $this->input->post('debtor_payment_amount');
                $balance_amounts = $this->input->post('debtor_balance_amount');
                $tot_payment_amount = $this->input->post('tot_payment_amount');
                $sale_ids = $this->input->post('sale_ids');

                if($payment_method != 'Cheque'){

                    $tot_balance_amount = $payment_amount - $tot_payment_amount;

                    if(($tot_balance_amount > 0 && min($balance_amounts) > 0) || $tot_balance_amount > 0){

                        $customer_details = $this->admin_db->get_customer_by_id($customer_id);

                        $amounts['box_over_paid_cash'] = $customer_details->box_over_paid_cash + $tot_balance_amount;
                        $amounts['box_over_paid_gold'] = $customer_details->box_over_paid_gold;
                        $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold;
                        $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash;

                        $this->admin_db->update_customer_box_accounts($customer_id, $amounts);

                    }

                }
            }

            $data['payment_type'] = 'Normal';
            $added_payment = $this->admin_db->add_box_payment_details($data);

            $added_payment['status'] = 1;

            header('Content-Type: application/json');

            if($added_payment['status'] == 1){
                $data1['payment_id'] = $added_payment['id'];

                for ($x = 0; $x < count($sale_ids); $x++) {

                    if($payment_amounts[$x] != ''){
                        $payment_amounts[$x] = $payment_amounts[$x];
                    }else{
                        $payment_amounts[$x] = 0;
                    }


                    $data1['sale_id'] = $sale_ids[$x];
                    $data1['payment_amount'] = $payment_amounts[$x];

                    $this->admin_db->add_box_payment_items($data1);

                    if($payment_method != 'Cheque'){

                        if($balance_amounts[$x] < 0){
                            $this->admin_db->update_box_sale_bal_amount($sale_ids[$x], 0);
                            $payment_amounts[$x] = $payment_amounts[$x] - abs($balance_amounts[$x]);
                        }else{
                            $this->admin_db->update_box_sale_bal_amount($sale_ids[$x], $balance_amounts[$x]);

                        }

                        $customer_details = $this->admin_db->get_customer_by_id($customer_id);

                        if($balance_amounts[$x] <= 0){

                            if($customer_details->status == 4 && $customer_details->customer_type == 'Walk-In'){
                                $this->admin_db->change_customer_status($customer_id, 1);
                            }

                            $this->admin_db->change_box_sale_status($sale_ids[$x], 1);
                        }else{

                            $this->admin_db->change_box_sale_status($sale_ids[$x], 2);
                        }

                        if($payment_method == "Gold"){

                            if($balance_amounts[$x] < 0){

                                $new_box_over_paid_gold = $customer_details->box_over_paid_gold + abs($balance_amounts[$x]);
                                $amounts['box_over_paid_gold'] = $new_box_over_paid_gold;

                            }else{

                                $amounts['box_over_paid_gold'] = $customer_details->box_over_paid_gold;

                            }

                            $amounts['box_over_paid_cash'] = $customer_details->box_over_paid_cash;
                            $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold - $payment_amounts[$x];
                            $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash;


                        }elseif($payment_method == "Over Paid Gold"){

                            $new_box_over_paid_gold = $customer_details->box_over_paid_gold - $payment_amounts[$x];
                            $amounts['box_over_paid_gold'] = $new_box_over_paid_gold;

                            $amounts['box_over_paid_cash'] = $customer_details->box_over_paid_cash;
                            $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold - $payment_amounts[$x];
                            $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash;

                        }elseif($payment_method == "Over Paid Cash"){

                            $new_box_over_paid_cash = $customer_details->box_over_paid_cash - $payment_amounts[$x];
                            $amounts['box_over_paid_cash'] = $new_box_over_paid_cash;

                            $amounts['box_over_paid_gold'] = $customer_details->box_over_paid_gold;
                            $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold;
                            $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash - $payment_amounts[$x];

                        }else{
                            if($balance_amounts[$x] < 0){

                                $new_box_over_paid_cash = $customer_details->box_over_paid_cash + abs($balance_amounts[$x]);
                                $amounts['box_over_paid_cash'] = $new_box_over_paid_cash;

                            }else{

                                $amounts['box_over_paid_cash'] = $customer_details->box_over_paid_cash;

                            }

                            $amounts['box_over_paid_gold'] = $customer_details->box_over_paid_gold;
                            $amounts['box_debt_amount_gold'] = $customer_details->box_debt_amount_gold;
                            $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash - $payment_amounts[$x];
                        }

                        $this->admin_db->update_customer_box_accounts($customer_id, $amounts);

                    }
                }

                $stock_details = $this->admin_db->get_stock_details();

                if($payment_method == 'Cash'){
                    $box_cash_in_hand = $stock_details->box_cash_in_hand;
                    $new_box_cash_in_hand = $box_cash_in_hand + $payment_amount;

                    $this->admin_db->update_stock_details('box_cash_in_hand', $new_box_cash_in_hand);

                    $account['action_date'] = $data['date'];
                    $account['item_type'] = 'receipt amount';
                    $account['item_id'] = $added_payment['id'];
                    $account['action_type'] = 'Credited';
                    $account['amount'] = $payment_amount;
                    $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                    $this->admin_db->add_box_cash_logs($account);

                }

                if($payment_method == 'Cheque'){
                    $cheque['bank_id'] = $data['cheq_bank'];
                    $cheque['payment_id'] = $added_payment['id'];
                    $cheque['customer_id'] = $customer_id;
                    $cheque['cheque_type'] = 'Box Sale';
                    $cheque['cheque_number'] = $data['cheq_cheque_number'];
                    $cheque['cheque_amount'] = $payment_amount;
                    $cheque['deposit_date'] = $data['cheq_deposit_date'];

                    $this->admin_db->add_cheque_details($cheque);

                }

                if($payment_method == 'Gold'){
                    $box_tf_gold_in_hand = $stock_details->box_tf_gold_in_hand;
                    $new_box_tf_gold_in_hand = $box_tf_gold_in_hand + $payment_amount;

                    $this->admin_db->update_stock_details('box_tf_gold_in_hand', $new_box_tf_gold_in_hand);

                    $account['item_type'] = 'receipt amount';
                    $account['item_id'] = $added_payment['id'];
                    $account['action_type'] = 'Credited';
                    $account['amount'] = $payment_amount;
                    $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                    $this->admin_db->add_box_24k_gold_logs($account);

                }

                if($payment_method == 'Bank Deposit'){
                    $account_details = $this->admin_db->get_bank_account_by_id($bank_account_id);

                    $bank_balance = $account_details->bank_balance;
                    $new_bank_balance  = $bank_balance + $payment_amount;

                    $this->admin_db->update_bank_balance($bank_account_id, $new_bank_balance);

                    $account['account_id'] = $bank_account_id;
                    $account['item_type'] = 'receipt amount';
                    $account['item_id'] = $added_payment['id'];
                    $account['action_type'] = 'Credited';
                    $account['amount'] = $payment_amount;
                    $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                    $this->admin_db->add_box_bank_account_logs($account);

                }

                echo json_encode(array("message" => "Payments Made Successfully", "status" => "1", "customer_id" => $customer_id));

            }else{
                echo json_encode(array("message" => "Error Occured while making the payment", "status" => "0", "customer_id" => $customer_id));

            }
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }
    }

    public function save_make_fixing_debtor_box_payment()
    {        
        $data['customer_id'] = $customer_id = $this->input->post('customer_id');
        $invoice_date = $this->input->post('invoice_date');
        $data['date'] = date("Y-m-d", strtotime($invoice_date));
        $data['24k_rate'] = $this->input->post('k_rate_debtor_fixing');
        
        $data['payment_method'] = $payment_method = $this->input->post('payment_method_debtor_fixing');
        
        if($payment_method == 'Gold'){
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 1;
            
        }elseif($payment_method == 'Cash'){
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 1;
            
        }else if($payment_method == 'Cheque'){
            $data['cheq_bank'] = $this->input->post('cheq_bank');
            $data['cheq_cheque_number'] = $this->input->post('cheq_cheque_number');
            $cheq_deposit_date = $this->input->post('cheq_deposit_date');
            $data['cheq_deposit_date'] = date("Y-m-d", strtotime($cheq_deposit_date));
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 2;
            
        }else if($payment_method == 'Bank Deposit'){
            $data['deposit_bank_account'] = $bank_account_id = $this->input->post('deposit_bank_account');
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['status'] = 1;
            
        }
        $data['payment_amount'] = $tot_payment_amount = $this->input->post('tot_debtor_fixing_payment_amount_cash');
        $data['payment_type'] = 'Fixing';
        
        try {
            $sale_ids = $this->input->post('debtor_fixing_sale_ids');
            $payment_amounts = $this->input->post('debtor_fixing_payment_amount');
            $total_balance_amounts_gold = $this->input->post('debtor_fixing_total_balance_amount_gold');
            $balance_amounts_gold = $this->input->post('debtor_fixing_balance_amount_gold');
        //        $balance_amounts_cash = $this->input->post('debtor_fixing_balance_amount_cash');
            $added_payment = $this->admin_db->add_box_payment_details($data);

            header('Content-Type: application/json');

            if($added_payment['status'] == 1){
                $data1['payment_id'] = $data['payment_id'] = $added_payment['id'];

                for ($x = 0; $x < count($sale_ids); $x++) {
                    $data1['sale_id'] = $data['sale_id'] = $sale_ids[$x];
                    $data1['payment_amount'] = $payment_amounts[$x];

                    $added_payment_item = $this->admin_db->add_box_payment_items($data1);
                    $data['payment_item_id'] = $added_payment_item['id'];

                    $data['paid_amount_in_cash'] = $payment_amounts[$x];
                    $data['paid_amount_in_gold'] = $total_balance_amounts_gold[$x] - $balance_amounts_gold[$x];

                    $this->admin_db->add_fixing_box_payments($data);

                    if($payment_method != 'Cheque'){

                        $this->admin_db->update_box_sale_bal_amount($sale_ids[$x], $balance_amounts_gold[$x]);

                        $customer_details = $this->admin_db->get_customer_by_id($customer_id);

                        if($balance_amounts_gold[$x] <= 0){

                            if($customer_details->status == 4 && $customer_details->customer_type == 'Walk-In'){
                                $this->admin_db->change_customer_status($customer_id, 1);
                            }

                            $this->admin_db->change_box_sale_status($sale_ids[$x], 1);
                        }else{

                            $this->admin_db->change_box_sale_status($sale_ids[$x], 2);
                        }

                        $box_debt_amount_gold = $customer_details->box_debt_amount_gold - $data['paid_amount_in_gold'];

                        $amounts['box_debt_amount_gold'] = $box_debt_amount_gold;
                        $amounts['box_debt_amount_cash'] = $customer_details->box_debt_amount_cash;

                        $amounts['box_over_paid_gold'] = $customer_details->box_over_paid_gold;
                        $amounts['box_over_paid_cash'] = $customer_details->box_over_paid_cash;

                        $this->admin_db->update_customer_box_accounts($customer_id, $amounts);
                    }
                }

                $stock_details = $this->admin_db->get_stock_details();

                if($payment_method == 'Cash'){
                    $box_cash_in_hand = $stock_details->box_cash_in_hand;
                    $new_box_cash_in_hand = $box_cash_in_hand + $tot_payment_amount;

                    $this->admin_db->update_stock_details('box_cash_in_hand', $new_box_cash_in_hand);

                    $account['action_date'] = $data['date'];
                    $account['item_type'] = 'receipt amount';
                    $account['item_id'] = $added_payment['id'];
                    $account['action_type'] = 'Credited';
                    $account['amount'] = $tot_payment_amount;
                    $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                    $this->admin_db->add_box_cash_logs($account);

                }

                if($payment_method == 'Cheque'){
                    $cheque['bank_id'] = $data['cheq_bank'];
                    $cheque['payment_id'] = $added_payment['id'];
                    $cheque['customer_id'] = $customer_id;
                    $cheque['cheque_type'] = 'Box Sale';
                    $cheque['cheque_number'] = $data['cheq_cheque_number'];
                    $cheque['cheque_amount'] = $tot_payment_amount;
                    $cheque['deposit_date'] = $data['cheq_deposit_date'];

                    $this->admin_db->add_cheque_details($cheque);

                }

                if($payment_method == 'Gold'){
                    $box_tf_gold_in_hand = $stock_details->box_tf_gold_in_hand;
                    $new_box_tf_gold_in_hand = $box_tf_gold_in_hand + $tot_payment_amount;

                    $this->admin_db->update_stock_details('box_tf_gold_in_hand', $new_box_tf_gold_in_hand);

                    $account['item_type'] = 'receipt amount';
                    $account['item_id'] = $added_payment['id'];
                    $account['action_type'] = 'Credited';
                    $account['amount'] = $tot_payment_amount;
                    $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                    $this->admin_db->add_box_24k_gold_logs($account);

                }

                if($payment_method == 'Bank Deposit'){
                    $account_details = $this->admin_db->get_bank_account_by_id($bank_account_id);

                    $bank_balance = $account_details->bank_balance;
                    $new_bank_balance  = $bank_balance + $tot_payment_amount;

                    $this->admin_db->update_bank_balance($bank_account_id, $new_bank_balance);

                    $account['account_id'] = $bank_account_id;
                    $account['item_type'] = 'receipt amount';
                    $account['item_id'] = $added_payment['id'];
                    $account['action_type'] = 'Credited';
                    $account['amount'] = $tot_payment_amount;
                    $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                    $this->admin_db->add_box_bank_account_logs($account);

                }

                echo json_encode(array("message" => "Payments Made Successfully", "status" => "1", "customer_id" => $customer_id));

            }else{
                echo json_encode(array("message" => "Error Occured while making the payment", "status" => "0", "customer_id" => $customer_id));

            }
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }
    }

    public function twofourk_customers()
    {
        $data['title'] = '24K Customers';
        
        $data['active'] = "active";
        $data['inactive'] = "";
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/24k_customers', $data);
        $this->load->view('dashboard/footer');
    }

    public function change_24k_customer_status()
    {
        $id = $this->input->get('id');
        $status = $this->input->get('status');
        
        $this->admin_db->change_24k_customer_status($id, $status);
        
        // 1 - active, 2 - inactive, 3 - deleted
        if ($status == 2) {

            $data['success_msg'] = '24K Customer Inactivated Successfully';
            $data['inactive'] = "active";
            $data['active'] = "";
            
        } else if ($status == 1) {

            $data['success_msg'] = '24K Customer Activated Successfully';
            $data['active'] = "active";
            $data['inactive'] = "";
            
        } else if ($status == 3) {

            $data['success_msg'] = '24K Customer Deleted Successfully';
            $data['active'] = "active";
            $data['inactive'] = "";
        }

        $data['title'] = '24K Customers';
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/24k_customers', $data);
        $this->load->view('dashboard/footer');

    }
    
    public function save_add_24k_customer_details()
    {
        $data['customer_name'] = $this->input->post('customer_name');
        $data['contact_number'] = $this->input->post('contact_num');
        $data['tel_number'] = $this->input->post('tel_number');
        
        header('Content-Type: application/json');
              
        $up_user = $this->admin_db->save_add_24k_customer_details($data);

        if($up_user == true){
            echo json_encode(array("message" => "24K Customer Added Successfully", "status" => "1"));

        }else{
            echo json_encode(array("message" => "An Error Occured while Adding 24K Customer", "status" => "0"));

        }
    }

    public function view_24k_customer()
    {
        $id = $this->input->get('24k_customer_id');
        
        $data['customer_details'] = $this->admin_db->get_24k_customer_by_id($id);
        
        $data['title'] = '24K Customer Profile';
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/24k_customer_profile', $data);
        $this->load->view('dashboard/footer');
    }
    
    public function save_edit_24k_customer_details()
    {
        $id = $this->input->post('24k_customer_id');
        $data['customer_name'] = $this->input->post('customer_name');
        $data['contact_number'] = $this->input->post('contact_num');
        $data['tel_number'] = $this->input->post('tel_number');
        
        header('Content-Type: application/json');
        
        $up_user = $this->admin_db->save_edit_24k_customer_details($id, $data);

        if($up_user == true){
            echo json_encode(array("message" => "24K Customer Details Successfully Edited", "status" => "1"));

        }else{
            echo json_encode(array("message" => "An Error Occured while Editing 24K Customer Details", "status" => "0"));

        }
    }
    
    public function save_add_previous_debts_24k_sale()
    {
        $data['customer_id'] = $customer_id = $this->input->post('customer_id');
        $invoice_date = $this->input->post('bill_date');
        $data['date'] = date("Y-m-d", strtotime($invoice_date));
        $data['invoice_number'] = $this->input->post('invoice_number');
        $data['sale_type'] = $sale_type = $this->input->post('sale_type');
        $data['24k_rate'] = $this->input->post('twofourk_customer_sale_24k_rate');
        $data['gold_amount'] = $sale_grams = $this->input->post('twofourk_customer_sale_grams');
        $data['total_amount'] = $total_amount =  $this->input->post('total_amount');
        $data['description'] = $this->input->post('description');
        $data['sale_category'] = 'Old Debts';
        $data['discount'] = 0.00;
        
        header('Content-Type: application/json');
        $data['status'] = 3; // 3 - Pending Payment 
        
        try {
            $up_debts = $this->admin_db->add_24k_sale($data);    

            $customer_details = $this->admin_db->get_24k_customer_by_id($customer_id);

            if($sale_type == '24K DXB Sale'){

                $tot_amount_gold = $customer_details->dxb_gold_tot_amount + $sale_grams;
                $tot_amount_cash = $customer_details->dxb_cash_tot_amount + $total_amount;
                $balance_amount = $customer_details->dxb_balance_amount + $total_amount;

                $amounts['dxb_gold_tot_amount'] = $tot_amount_gold;
                $amounts['dxb_cash_tot_amount'] = $tot_amount_cash;
                $amounts['dxb_paid_amount'] = $customer_details->dxb_paid_amount;

                $amounts['dxb_balance_amount'] = $balance_amount;

                $this->admin_db->update_24k_customer_dxb_accounts($customer_id, $amounts);

            }elseif($sale_type == '24K BOX Sale'){

                $tot_amount_gold = $customer_details->box_gold_tot_amount + $sale_grams;
                $tot_amount_cash = $customer_details->box_cash_tot_amount + $total_amount;
                $balance_amount = $customer_details->box_balance_amount + $total_amount;

                $amounts['box_gold_tot_amount'] = $tot_amount_gold;
                $amounts['box_cash_tot_amount'] = $tot_amount_cash;
                $amounts['box_paid_amount'] = $customer_details->box_paid_amount;

                $amounts['box_balance_amount'] = $balance_amount;

                $this->admin_db->update_24k_customer_box_accounts($customer_id, $amounts);

            }

            if($up_debts['status'] == true){
                echo json_encode(array("message" => "Previous Debts Added Successfully", "status" => "1"));

            }else{
                echo json_encode(array("message" => "An Error Occured while Adding Previous Debts", "status" => "0"));

            }
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }
    }

    public function view_24k_payments()
    {
        $id = $this->input->get('payment_id');
        
        $data['title'] = 'View Payment Details';
        
        $data['payment_details'] = $this->admin_db->get_24k_payment_details_by_id($id);  
        $data['payment_items'] = $this->admin_db->get_24k_payment_items_by_payment_id($id);    
                
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/view_24k_payment_details', $data);
        $this->load->view('dashboard/footer');
    }

    public function twofourk_sales()
    {
        $data['title'] = '24K Sales';
        
        $data['all'] = "active";
        $data['pay_completed'] = "";
        $data['pay_incompleted'] = "";
        $data['pay_pending'] = "";
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/24k_sales', $data);
        $this->load->view('dashboard/footer');
    }

    public function do_24k_sales()
    {
        $data['title'] = 'Do 24K Sales';
        $data['k_rate'] = $this->admin_db->get_rate_detail_by_id(1)->item_rate;
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/do_24k_sales', $data);
        $this->load->view('dashboard/footer');
    }

    public function ajax_get_24k_customer_details()
    {
        $id = $this->input->post('customer_id');
        header('Content-Type: application/json');
        
        $customer_details = $this->admin_db->get_24k_customer_by_id($id);
        
        echo json_encode(array("contact_number" => $customer_details->contact_number, "tel_number" => $customer_details->tel_number, "supplier_status" => $customer_details->status));
    }

    public function save_24k_do_sale()
    {                      
        $invoice_date = $this->input->post('invoice_date');
        $data['invoice_number'] = $this->input->post('invoice_number');
        $data['sale_type'] = $sale_type = $this->input->post('sale_type');
        $data['24k_rate'] = $rate = $this->input->post('24k_rate');
        $select_customer = $this->input->post('select_customer');
        $total_sum_credit = $this->input->post('debit_sum_txt_credit');
        $total_gold_sale = $this->input->post('total_gold_sale');
        $data['discount'] = $discount = $this->input->post('discount');
        
        $sale_data = $this->input->post('24k_sale_data');
        
        $user_type = $this->session->userdata('user_type_id');
        
        $data['date'] = date("Y-m-d", strtotime($invoice_date));
        
        header('Content-Type: application/json');
        
        try {
            if($discount != ''){
                $total_amount = $total_sum_credit - $discount;
            }else{
                $total_amount = $total_sum_credit;
            }

            $data['gold_amount'] = $total_gold_sale;
            $data['bill_amount'] = $total_sum_credit;
            $data['total_amount'] = $total_amount;
            $data['24k_rate'] = $rate;

            if($select_customer == "Add New Customer"){
                $data['customer_name'] = $customer_name = $this->input->post('customer_name');
                $data['contact_number'] = $customer_number = $this->input->post('contact_num');
                $data['tel_number'] = $this->input->post('tel_number');

                $data['status'] = 1;

                if($sale_type == '24K DXB Sale'){

                    if($user_type == 1){
                        $data['dxb_gold_tot_amount'] = $total_gold_sale;
                        $data['dxb_cash_tot_amount'] = $total_amount;
                        $data['dxb_balance_amount'] = $total_amount;
                    }else{
                        $data['dxb_gold_tot_amount'] = 0.000;
                        $data['dxb_cash_tot_amount'] = 0.00;
                        $data['dxb_balance_amount'] = 0.00;
                    }
                    $data['dxb_paid_amount'] = 0.000;

                }elseif($sale_type == '24K BOX Sale'){

                    if($user_type == 1){
                        $data['box_gold_tot_amount'] = $total_gold_sale;
                        $data['box_cash_tot_amount'] = $total_amount;
                        $data['box_balance_amount'] = $total_amount;
                    }else{
                        $data['box_gold_tot_amount'] = 0.000;
                        $data['box_cash_tot_amount'] = 0.00;
                        $data['box_balance_amount'] = 0.00;
                    }
                    $data['box_paid_amount'] = 0.000;

                }

                $data['status'] = 1; // 1 - active, 2 - inactive, 3 - deleted

                $added_customer = $this->admin_db->add_24k_customer_details_sale($data);

                $data['customer_id'] = $added_customer['id'];

            }else{
                $data['customer_id'] = $select_customer;

                if($user_type == 1){

                    $customer_details = $this->admin_db->get_24k_customer_by_id($select_customer);

                    if($sale_type == '24K DXB Sale'){

                        $tot_amount_gold = $customer_details->dxb_gold_tot_amount + $total_gold_sale;
                        $tot_amount_cash = $customer_details->dxb_cash_tot_amount + $total_amount;
                        $balance_amount = $customer_details->dxb_balance_amount + $total_amount;

                        $amounts['dxb_gold_tot_amount'] = $tot_amount_gold;
                        $amounts['dxb_cash_tot_amount'] = $tot_amount_cash;
                        $amounts['dxb_paid_amount'] = $customer_details->dxb_paid_amount;

                        $amounts['dxb_balance_amount'] = $balance_amount;

                        $this->admin_db->update_24k_customer_dxb_accounts($select_customer, $amounts);

                    }elseif($sale_type == '24K BOX Sale'){

                        $tot_amount_gold = $customer_details->box_gold_tot_amount + $total_gold_sale;
                        $tot_amount_cash = $customer_details->box_cash_tot_amount + $total_amount;
                        $balance_amount = $customer_details->box_balance_amount + $total_amount;

                        $amounts['box_gold_tot_amount'] = $tot_amount_gold;
                        $amounts['box_cash_tot_amount'] = $tot_amount_cash;
                        $amounts['box_paid_amount'] = $customer_details->box_paid_amount;

                        $amounts['box_balance_amount'] = $balance_amount;

                        $this->admin_db->update_24k_customer_box_accounts($select_customer, $amounts);

                    }

                }
            }

            $data['sale_category'] = 'Normal';
            $data['description'] = NULL;

            if($user_type != 1){

                $data['status'] = 4;   
                $added_sale = $this->admin_db->add_24k_sale($data);

                $amount = number_format($total_gold_sale,3,'.',',').' g';

                $data['item_id'] = $added_sale['id'];
                $data['item_type'] = '24K Sale';
                $data['amount'] = $amount;
                $data['description'] = NULL;
                $this->admin_db->add_approval_requests($data);

            }else{
                $data['status'] = 3;   
                $added_sale = $this->admin_db->add_24k_sale($data);

                if($select_customer == "Add New Customer"){
                    $customer_name = $customer_name;
                    $customer_number = $customer_number;
                    $send_msg = 'true';
                }else{
                    $customer_details = $this->admin_db->get_24k_customer_by_id($select_customer);
                    $customer_name = $customer_details->customer_name;
                    $customer_number = $customer_details->contact_number;
                    if($customer_details->send_sms == 1){
                        $send_msg = 'true';
                    }else{
                        $send_msg = 'false';
                    }
                }

                if($customer_number != '' && $send_msg == 'true'){
                    $customer_number = preg_replace('/^0/','94',$customer_number); 

    //            print_r($customer_number);exit;

                    $total_sum = number_format($total_gold_sale,3,'.',',').' g';

                    $text = 'Hi '.$customer_name.'!<br>Thank you doing business of '.$total_sum.'<br>Ref. No : '.$data['invoice_number'].'<br>Bill Date : '.$data['date'].'<br><br>AVA Jewellers';

                    $user = "94777979679";
                    $password = "1739";
                    $text = urlencode($text);
                    $to = $customer_number;

                    $baseurl ="http://www.textit.biz/sendmsg";
                    $url = "$baseurl/?id=$user&pw=$password&to=$to&text=$text";
                    $ret = get_web_page($url);
                }

            }

            $total_sale_grams = 0;

            for ($x = 0; $x < count($sale_data['sales_grams']); $x++) {

                $data1['sale_id'] = $added_sale['id'];
                $data1['item_name'] = $sale_data['item_name'][$x];
                $data1['description'] = $sale_data['description'][$x];
                $data1['sales_grams'] = $sale_data['sales_grams'][$x];
                $data1['amount'] = $sale_data['sub_total'][$x];

                $total_sale_grams += $sale_data['sales_grams'][$x];

                $this->admin_db->add_24k_sale_items($data1);

            }

            if($user_type == 1){

                $stock_details = $this->admin_db->get_stock_details();

                if($sale_type == "24K DXB Sale"){

                    $tf_gold_in_hand = $stock_details->tf_gold_in_hand;
                    $new_tf_gold_in_hand = $tf_gold_in_hand - $total_sale_grams;

                    $this->admin_db->update_stock_details('tf_gold_in_hand', $new_tf_gold_in_hand);

                    $customer_details = $this->admin_db->get_24k_customer_by_id($data['customer_id']);

                    $account['item_type'] = 'sale';
                    $account['item_id'] = $added_sale['id'];
                    $account['action_type'] = 'Debited';
                    $account['amount'] = $total_sale_grams;
                    $account['description'] = 'Sold To '.$customer_details->customer_name;

                    $this->admin_db->add_24k_gold_logs($account);

                }else if($sale_type == "24K BOX Sale"){

                    $box_tf_gold_in_hand = $stock_details->box_tf_gold_in_hand;
                    $new_box_tf_gold_in_hand = $box_tf_gold_in_hand - $total_sale_grams;

                    $this->admin_db->update_stock_details('tf_box_gold_in_hand', $new_box_tf_gold_in_hand);

                    $account['item_type'] = 'sale';
                    $account['item_id'] = $added_sale['id'];
                    $account['action_type'] = 'Debited';
                    $account['amount'] = $total_sale_grams;
                    $account['description'] = 'Sold To '.$customer_details->customer_name;

                    $this->admin_db->add_box_24k_gold_logs($account);

                }

            }
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }
        
        if($added_sale['status'] == 1){
            echo json_encode(array("message" => "24K Sale Added Successfully", "status" => "1"));
            
        }
    }

    public function view_24k_sale()
    {
        $id = $this->input->get('24k_sale_id');
        
        $data['title'] = 'View 24K Sale Details';
        
        $data['sale_details'] = $this->admin_db->get_24k_sale_details_by_id($id);
        $data['sale_items'] = $this->admin_db->get_24k_sale_items_by_sale_id($id);    
        $data['payment_items'] = $this->admin_db->get_24k_payment_items_by_sale_id($id);
        
        if($data['sale_details']->status == 4){
            $data['approval_details'] = $this->admin_db->get_approval_by_item_type_id('24k Sale', $id);
        }
        
//        echo '<pre>'. print_r($data['returned_sale_details'],1). '</pre>'; exit;
        
//        print_r($data['sale_details']);exit;
                
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/view_24k_sale', $data);
        $this->load->view('dashboard/footer');
    }

    public function save_make_24k_normal_payment()
    {     
        $data['sale_id'] = $sale_id = $this->input->post('sale_id');
        $data['customer_id'] = $customer_id = $this->input->post('customer_id');
        $invoice_date = $this->input->post('invoice_date');
        $sale_type = $this->input->post('sale_type');
        $data['date'] = date("Y-m-d", strtotime($invoice_date));
        
        $data['payment_method'] = $payment_method = $this->input->post('payment_method');
        
        if($payment_method == 'Over Paid Gold'){
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 1;
            
        }elseif($payment_method == 'Over Paid Cash'){
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 1;
            
        }elseif($payment_method == 'Cash'){
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 1;
            
        }else if($payment_method == 'Cheque'){
            $data['cheq_bank'] = $this->input->post('cheq_bank');
            $data['cheq_cheque_number'] = $this->input->post('cheq_cheque_number');
            $cheq_deposit_date = $this->input->post('cheq_deposit_date');
            $data['cheq_deposit_date'] = date("Y-m-d", strtotime($cheq_deposit_date));
            $data['deposit_bank_account'] = NULL;
            $data['status'] = 2;
            
        }else if($payment_method == 'Bank Deposit'){
            $data['deposit_bank_account'] = $bank_account_id = $this->input->post('deposit_bank_account');
            $data['cheq_bank'] = NULL;
            $data['cheq_cheque_number'] = NULL;
            $data['cheq_deposit_date'] = NULL;
            $data['status'] = 1;
            
        }
        
        $payment_total = $this->input->post('payment_total');
        $data['payment_amount'] = $payment_amount = $this->input->post('payment_amount');
        $data['payment_type'] = 'Normal';
        
        header('Content-Type: application/json');
        
        try {
            $added_payment = $this->admin_db->add_24k_payment_details($data);

            $added_payment['status'] = 1;

            if($added_payment['status'] == 1){
                $data['payment_id'] = $added_payment['id'];
                $this->admin_db->add_24k_payment_items($data);
                
                $sale_details = $this->admin_db->get_24k_sale_by_id($sale_id);

                if($payment_method != 'Cheque'){

                    $balance_total = $payment_total - $payment_amount;

                    if($balance_total < 0){

                        $amounts['balance_amount'] = 0.00;
                        $amounts['paid_amount'] = $payment_amount;

                        $this->admin_db->update_24k_sale_bal_amount($sale_id, $amounts);
                        $payment_amount = $payment_total;
                    }else{

                        $amounts['balance_amount'] = $payment_total - $payment_amount;
                        $amounts['paid_amount'] = $payment_amount;

                        $this->admin_db->update_24k_sale_bal_amount($sale_id, $amounts);

                    }

                    $customer_details = $this->admin_db->get_24k_customer_by_id($customer_id);
                    
                    if($sale_details->status != 4){

                        if($balance_total <= 0){ 

                            $this->admin_db->change_24k_sale_status($sale_id, 1);
                        }else{

                            $this->admin_db->change_24k_sale_status($sale_id, 2);
                        }

                        if($payment_method == "Over Paid Cash"){

                            $new_over_paid_cash = $customer_details->over_paid_cash - $payment_amount;
                            $amounts['over_paid_cash'] = $new_over_paid_cash;

                            if($balance_total < 0){

                                $over_paid_cash = $customer_details->over_paid_cash - $payment_amount;
                                $new_over_paid_cash = $over_paid_cash + ($payment_amount - $payment_total);

                                $amounts['over_paid_cash'] = $new_over_paid_cash;

                            }

                        }else{

                            if($balance_total < 0){

                                $new_over_paid_cash = $customer_details->over_paid_cash + abs($balance_total);
                                $amounts['over_paid_cash'] = $new_over_paid_cash;

                            }else{

                                $amounts['over_paid_cash'] = $customer_details->over_paid_cash;

                            }

                        }

                        if($sale_type == '24K DXB Sale'){

                            $amounts['dxb_gold_tot_amount'] = $customer_details->dxb_gold_tot_amount;
                            $amounts['dxb_cash_tot_amount'] = $customer_details->dxb_cash_tot_amount;
                            $amounts['dxb_paid_amount'] = $customer_details->dxb_paid_amount + $payment_amount;

                            $amounts['dxb_balance_amount'] = $customer_details->dxb_balance_amount - $payment_amount;

                            $this->admin_db->update_24k_customer_dxb_accounts($customer_id, $amounts);

                        }elseif($sale_type == '24K BOX Sale'){

                            $amounts['box_gold_tot_amount'] = $customer_details->box_gold_tot_amount;
                            $amounts['box_cash_tot_amount'] = $customer_details->box_cash_tot_amount;
                            $amounts['box_paid_amount'] = $customer_details->box_paid_amount + $payment_amount;

                            $amounts['box_balance_amount'] = $customer_details->box_balance_amount - $payment_amount;

                            $this->admin_db->update_24k_customer_box_accounts($customer_id, $amounts);

                        }
                    }
                }
                    
                if($sale_details->status != 4){

                    $stock_details = $this->admin_db->get_stock_details();

                    if($payment_method == 'Cash'){
                        $cash_in_hand = $stock_details->cash_in_hand;
                        $new_cash_in_hand = $cash_in_hand + $payment_amount;

                        $this->admin_db->update_stock_details('cash_in_hand', $new_cash_in_hand);

                        $account['action_date'] = $data['date'];
                        $account['item_type'] = 'receipt amount';
                        $account['item_id'] = $added_payment['id'];
                        $account['action_type'] = 'Credited';
                        $account['amount'] = $payment_amount;
                        $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                        $this->admin_db->add_cash_logs($account);

                    }

                    if($payment_method == 'Cheque'){
                        $cheque['bank_id'] = $data['cheq_bank'];
                        $cheque['payment_id'] = $added_payment['id'];
                        $cheque['customer_id'] = $customer_id;
                        $cheque['cheque_type'] = '24K Sale';
                        $cheque['cheque_number'] = $data['cheq_cheque_number'];
                        $cheque['cheque_amount'] = $payment_amount;
                        $cheque['deposit_date'] = $data['cheq_deposit_date'];

                        $this->admin_db->add_cheque_details($cheque);

                    }

                    if($payment_method == 'Bank Deposit'){
                        $account_details = $this->admin_db->get_bank_account_by_id($bank_account_id);

                        $bank_balance = $account_details->bank_balance;
                        $new_bank_balance  = $bank_balance + $payment_amount;

                        $this->admin_db->update_bank_balance($bank_account_id, $new_bank_balance);

                        $account['account_id'] = $bank_account_id;
                        $account['item_type'] = 'receipt amount';
                        $account['item_id'] = $added_payment['id'];
                        $account['action_type'] = 'Credited';
                        $account['amount'] = $payment_amount;
                        $account['description'] = 'Payment Received From '.$customer_details->customer_name;

                        $this->admin_db->add_bank_account_logs($account);

                    }
                }

                echo json_encode(array("message" => "Payment Made Successfully", "status" => "1", "sale_id" => $sale_id));

            }else{
                echo json_encode(array("message" => "Error Occured while making the payment", "status" => "0", "sale_id" => $sale_id));

            }
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }
    }

    public function delete_24k_sale()
    {
        $id = $this->input->get('id');
        $status = $this->input->get('status');
        
        try {
            $status_updated = $this->admin_db->change_24k_sale_status($id, $status);
            $status_updated = true;
            if($status_updated == true){

                // 6 - Deleted
                if ($status == 6) {

                    $data['success_msg'] = 'Sale Deleted Successfully';

                    $sale_items = $this->admin_db->get_24k_sale_items_by_sale_id($id);

                    if ($sale_items) {

                        $total_sale_grams = 0;

                        foreach($sale_items as $sale_item){

                            $total_sale_grams += $sale_item['sales_grams'];

                        }

                        $stock_details = $this->admin_db->get_stock_details();

                        $tf_gold_in_hand = $stock_details->tf_gold_in_hand;
                        $new_tf_gold_in_hand = $tf_gold_in_hand + $total_sale_grams;

                        $this->admin_db->update_stock_details('tf_gold_in_hand', $new_tf_gold_in_hand);

                        $account['item_type'] = 'delete sale';
                        $account['item_id'] = $id;
                        $account['action_type'] = 'Credited';
                        $account['amount'] = $total_sale_grams;
                        $account['description'] = 'Sale Deleted. Sale No.'.$id;

                        $this->admin_db->add_24k_gold_logs($account);

                    }

                    $sale_details = $this->admin_db->get_24k_sale_details_by_id($id);

                    $customer_details = $this->admin_db->get_24k_customer_by_id($sale_details->customer_id);

                    $paid_amount = $sale_details->total_amount - $sale_details->balance_amount;

                    if($paid_amount == 0){
                        $overpayments['over_paid_cash'] = $customer_details->over_paid_cash;

                    }else{
                        $overpayments['over_paid_cash'] = $customer_details->over_paid_cash + $paid_amount;

                    }

                    if($sale_details->sale_type == '24K DXB Sale'){

                        $tot_amount_gold = $customer_details->dxb_gold_tot_amount;
                        $tot_amount_cash = $customer_details->dxb_cash_tot_amount - $sale_details->total_amount;
                        $balance_amount = $customer_details->dxb_balance_amount - $sale_details->balance_amount;

                        $amounts['dxb_gold_tot_amount'] = $tot_amount_gold;
                        $amounts['dxb_cash_tot_amount'] = $tot_amount_cash;
                        $amounts['dxb_paid_amount'] = $customer_details->dxb_paid_amount;

                        $amounts['dxb_balance_amount'] = $balance_amount;

                        $this->admin_db->update_24k_customer_dxb_accounts($sale_details->customer_id, $amounts);


                    }elseif($sale_details->sale_type == 'Gold Sale'){

                        $tot_amount_gold = $customer_details->box_gold_tot_amount;
                        $tot_amount_cash = $customer_details->box_cash_tot_amount - $sale_details->total_amount;
                        $balance_amount = $customer_details->box_balance_amount - $sale_details->balance_amount;

                        $amounts['box_gold_tot_amount'] = $tot_amount_gold;
                        $amounts['box_cash_tot_amount'] = $tot_amount_cash;
                        $amounts['box_paid_amount'] = $customer_details->dxb_paid_amount;

                        $amounts['box_balance_amount'] = $balance_amount;

                        $this->admin_db->update_24k_customer_box_accounts($sale_details->customer_id, $amounts);

                    }

                }
            }

            redirect(base_url().'view_24k_sale?24k_sale_id='.$sale_details->id);
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }

    }
    
    public function save_withdraw_cash()
    {        
        $account_id = $this->input->post('account_id');
        $withdraw_date = $this->input->post('withdraw_date');
        $data['withdraw_date'] = date("Y-m-d", strtotime($withdraw_date));
        $withdrawal_amount = $this->input->post('withdrawal_amount');
        
        $account_details = $this->admin_db->get_bank_account_by_id($account_id);
                
        $bank_balance = $account_details->bank_balance;
        $new_bank_balance  = $bank_balance - $withdrawal_amount;

        try {
            $this->admin_db->update_bank_balance($account_id, $new_bank_balance);

            $account['account_id'] = $account_id;
            $account['item_type'] = 'cash withdrawal';
            $account['item_id'] = NULL;
            $account['action_type'] = 'Debited';
            $account['amount'] = $withdrawal_amount;
            $account['description'] = 'Cash Withdrawal On - '.$withdraw_date;
            
            if($account_details->account_type == 'Dxb'){
                $this->admin_db->add_bank_account_logs($account);
            }else if($account_details->account_type == 'Box'){
                $this->admin_db->add_box_bank_account_logs($account); 
            }
            
            $stock_details = $this->admin_db->get_stock_details();

            if($account_details->account_type == 'Dxb'){
                $cash_in_hand = $stock_details->cash_in_hand;
                $new_cash_in_hand = $cash_in_hand + $withdrawal_amount;
                
                $this->admin_db->update_stock_details('cash_in_hand', $new_cash_in_hand);
            
            }else if($account_details->account_type == 'Box'){
                $box_cash_in_hand = $stock_details->box_cash_in_hand;
                $new_cash_in_hand = $box_cash_in_hand + $withdrawal_amount;
                
                $this->admin_db->update_stock_details('box_cash_in_hand', $new_cash_in_hand);
            }

            $account['action_date'] = $data['withdraw_date'];
            $account['item_type'] = 'income';
            $account['item_id'] = NULL;
            $account['action_type'] = 'Credited';
            $account['amount'] = $withdrawal_amount;
            $account['description'] = 'Cash Withdrawed From Account Name - '.$account_details->account_name.' - '.$account_details->account_number;

            if($account_details->account_type == 'Dxb'){
                $this->admin_db->add_cash_logs($account);
                
            }else if($account_details->account_type == 'Box'){   
                $this->admin_db->add_box_cash_logs($account);
                
            } 
            header('Content-Type: application/json');

            echo json_encode(array("message" => "Cash Withdrawal Added Successfully", "status" => "1", "account_id" => $account_id));
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }

    }    

    public function returned_sales()
    {
        
        $data['type'] = $type = $this->input->get('type');
        
        if($type == 'dxb'){        
            $data['title'] = 'Returned DXB Sales';
            $data['credit_sales_title'] = 'Returned DXB Credit Sales';
            $data['gold_sales_title'] = 'Returned DXB Gold Sales';            
        }else if($type == 'box'){
            $data['title'] = 'Returned Box Sales';
            $data['credit_sales_title'] = 'Returned Box Credit Sales';
            $data['gold_sales_title'] = 'Returned Box Gold Sales';
        }
        
        $data['credit_sales'] = 'active';
        $data['gold_sales'] = '';
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/returned_sales', $data);
        $this->load->view('dashboard/footer');
    }   

    public function stock_item_categories()
    {
        $data['title'] = 'Stock Item Categories';
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/stock_item_categories', $data);
        $this->load->view('dashboard/footer');
    }
    
    public function save_add_stock_item_category_details()
    {
        $data['category_name'] = $this->input->post('category_name');
        $data['description'] = $this->input->post('description');
        
        header('Content-Type: application/json');
              
        $up_user = $this->admin_db->save_add_stock_item_category_details($data);

        if($up_user == true){
            echo json_encode(array("message" => "Stock Item Category Added Successfully", "status" => "1"));

        }else{
            echo json_encode(array("message" => "An Error Occured while Adding Stock Item Category", "status" => "0"));

        }
    }

    public function change_stock_item_category_status()
    {
        $id = $this->input->get('id');
        $status = $this->input->get('status');
        
        $this->admin_db->change_stock_item_category_status($id, $status);
        
        // 2 - deleted
        if ($status == 2) {

            $data['success_msg'] = 'Stock Item Category Deleted Successfully';
            
        }

        $data['title'] = 'Stock Item Categories';
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/stock_item_categories', $data);
        $this->load->view('dashboard/footer');

    }

    public function view_stock_item_category()
    {
        $id = $this->input->get('category_id');
        
        $data['category_details'] = $this->admin_db->get_stock_item_category_details_by_id($id);
        
        $data['title'] = 'Stock Item Category Details';
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/stock_item_category_details', $data);
        $this->load->view('dashboard/footer');
    }
    
    public function save_edit_stock_item_category_details()
    {
        $id = $this->input->post('category_id');
        $data['category_name'] = $this->input->post('category_name');
        $data['description'] = $this->input->post('description');
        
        header('Content-Type: application/json');
        
        $up_account = $this->admin_db->save_edit_stock_item_category_details($id, $data);

        if($up_account == true){
            echo json_encode(array("message" => "Expense Category Successfully Edited", "status" => "1", "category_id" => $id));

        }else{
            echo json_encode(array("message" => "An Error Occured while Editing Expense Category", "status" => "0", "category_id" => $id));

        }
    }

    public function suppliers()
    {
        $data['title'] = 'Suppliers';
        
        $data['active'] = "active";
        $data['inactive'] = "";
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/suppliers', $data);
        $this->load->view('dashboard/footer');
    }

    public function change_supplier_status()
    {
        $id = $this->input->get('id');
        $status = $this->input->get('status');
        
        $this->admin_db->change_supplier_status($id, $status);
        
        // 1 - active, 2 - inactive, 3 - deleted
        if ($status == 2) {

            $data['success_msg'] = 'Supplier Inactivated Successfully';
            $data['inactive'] = "active";
            $data['active'] = "";
            
        } else if ($status == 1) {

            $data['success_msg'] = 'Supplier Activated Successfully';
            $data['active'] = "active";
            $data['inactive'] = "";
            
        } else if ($status == 3) {

            $data['success_msg'] = 'Supplier Deleted Successfully';
            $data['active'] = "active";
            $data['inactive'] = "";
        }

        $data['title'] = 'Suppliers';
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/suppliers', $data);
        $this->load->view('dashboard/footer');

    }
    
    public function save_add_supplier_details()
    {
        $data['supplier_name'] = $this->input->post('supplier_name');
        $data['contact_number'] = $this->input->post('contact_num');
        $data['tel_number'] = $this->input->post('tel_number');
        
        $data['gold_tot_amount'] = 0.000;
        $data['cash_tot_amount'] = 0.00;
        $data['paid_amount'] = 0.00;
        $data['balance_amount'] = 0.00;
        
        header('Content-Type: application/json');
              
        $up_user = $this->admin_db->save_add_supplier_details($data);

        if($up_user == true){
            echo json_encode(array("message" => "Supplier Added Successfully", "status" => "1"));

        }else{
            echo json_encode(array("message" => "An Error Occured while Adding Supplier", "status" => "0"));

        }
    }

    public function view_supplier()
    {
        $id = $this->input->get('supplier_id');
        
        $data['supplier_details'] = $this->admin_db->get_supplier_by_id($id);
        
        $data['title'] = 'Supplier Profile';
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/supplier_profile', $data);
        $this->load->view('dashboard/footer');
    }
    
    public function save_edit_supplier_details()
    {
        $id = $this->input->post('supplier_id');
        $data['supplier_name'] = $this->input->post('supplier_name');
        $data['contact_number'] = $this->input->post('contact_num');
        $data['tel_number'] = $this->input->post('tel_number');
        
        header('Content-Type: application/json');
        
        $up_user = $this->admin_db->save_edit_supplier_details($id, $data);

        if($up_user == true){
            echo json_encode(array("message" => "Supplier Details Successfully Edited", "status" => "1"));

        }else{
            echo json_encode(array("message" => "An Error Occured while Editing Supplier Details", "status" => "0"));

        }
    }

    public function carriers()
    {
        $data['title'] = 'Carriers';
        
        $data['active'] = "active";
        $data['inactive'] = "";
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/carriers', $data);
        $this->load->view('dashboard/footer');
    }

    public function change_carrier_status()
    {
        $id = $this->input->get('id');
        $status = $this->input->get('status');
        
        $this->admin_db->change_carrier_status($id, $status);
        
        // 1 - active, 2 - inactive, 3 - deleted
        if ($status == 2) {

            $data['success_msg'] = 'Carrier Inactivated Successfully';
            $data['inactive'] = "active";
            $data['active'] = "";
            
        } else if ($status == 1) {

            $data['success_msg'] = 'Carrier Activated Successfully';
            $data['active'] = "active";
            $data['inactive'] = "";
            
        } else if ($status == 3) {

            $data['success_msg'] = 'Carrier Deleted Successfully';
            $data['active'] = "active";
            $data['inactive'] = "";
        }

        $data['title'] = 'Carriers';
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/carriers', $data);
        $this->load->view('dashboard/footer');

    }
    
    public function save_add_carrier_details()
    {
        $data['carrier_name'] = $this->input->post('carrier_name');
        $data['contact_number'] = $this->input->post('contact_num');
        $data['tel_number'] = $this->input->post('tel_number');
        
        $data['gold_tot_amount'] = 0.000;
        $data['cash_tot_amount'] = 0.00;
        $data['paid_amount'] = 0.00;
        $data['balance_amount'] = 0.00;
        
        header('Content-Type: application/json');
              
        $up_user = $this->admin_db->save_add_carrier_details($data);

        if($up_user == true){
            echo json_encode(array("message" => "Carrier Added Successfully", "status" => "1"));

        }else{
            echo json_encode(array("message" => "An Error Occured while Adding Carrier", "status" => "0"));

        }
    }

    public function view_carrier()
    {
        $id = $this->input->get('carrier_id');
        
        $data['carrier_details'] = $this->admin_db->get_carrier_by_id($id);
        
        $data['title'] = 'Carrier Profile';
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/carrier_profile', $data);
        $this->load->view('dashboard/footer');
    }
    
    public function save_edit_carrier_details()
    {
        $id = $this->input->post('carrier_id');
        $data['carrier_name'] = $this->input->post('carrier_name');
        $data['contact_number'] = $this->input->post('contact_num');
        $data['tel_number'] = $this->input->post('tel_number');
        
        header('Content-Type: application/json');
        
        $up_user = $this->admin_db->save_edit_carrier_details($id, $data);

        if($up_user == true){
            echo json_encode(array("message" => "Carrier Details Successfully Edited", "status" => "1"));

        }else{
            echo json_encode(array("message" => "An Error Occured while Editing Carrier Details", "status" => "0"));

        }
    }

    public function grns()
    {
        $data['title'] = 'Good Received Notes';
        
        $data['all'] = "active";
        $data['completed'] = "";
        $data['incompleted'] = "";
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/grns', $data);
        $this->load->view('dashboard/footer');
    }

    public function do_purchases()
    {
        $data['title'] = 'Do Pruchases';
        
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/do_purchases', $data);
        $this->load->view('dashboard/footer');
    }

    public function ajax_get_carrier_details()
    {
        $id = $this->input->post('carrier_id');
        header('Content-Type: application/json');
        
        $carrier_details = $this->admin_db->get_carrier_by_id($id);
        
        echo json_encode(array("contact_number" => $carrier_details->contact_number, "tel_number" => $carrier_details->tel_number, "carrier_status" => $carrier_details->status));
    }

    public function save_do_purchase()
    {                
        $user_type = $this->session->userdata('user_type_id');
        
        $invoice_date = $this->input->post('invoice_date');
        $select_carrier = $this->input->post('select_carrier');
        $data['invoice_number'] = $this->input->post('invoice_number');
        $data['22k_stock_type'] = $k_stock_type = $this->input->post('k_stock_type');
        
        $data['quantity_1'] = $this->input->post('quantity_1');
        $data['rate_1'] = $this->input->post('rate_1');
        $data['amount_1'] = $this->input->post('amount_1');
        
        $data['quantity_2'] = $this->input->post('quantity_2');
        $data['rate_2'] = $this->input->post('rate_2');
        $data['amount_2'] = $this->input->post('amount_2');
        
        $data['quantity_3'] = $this->input->post('quantity_3');
        $data['rate_3'] = $this->input->post('rate_3');
        $data['amount_3'] = $this->input->post('amount_3');
        
        $data['quantity_4'] = $this->input->post('quantity_4');
        $data['rate_4'] = $this->input->post('rate_4');
        $data['amount_4'] = $this->input->post('amount_4');
        
        $data['quantity_5'] = $this->input->post('quantity_5');
        $data['rate_5'] = $this->input->post('rate_5');
        $data['amount_5'] = $this->input->post('amount_5');
        
        $purchase_data = $this->input->post('purchase_data');
        
//        echo '<pre>'. print_r($purchase_data,1). '</pre>'; exit;
        
        $data['date'] = date("Y-m-d", strtotime($invoice_date));
        
        $tot_gold_qty = $data['quantity_1'] + $data['quantity_2'] + $data['quantity_3'] + $data['quantity_4'] + $data['quantity_5'];
        $tot_amount = $data['amount_1'] + $data['amount_2'] + $data['amount_3'] + $data['amount_4'] + $data['amount_5'];
        
        header('Content-Type: application/json');
        
        try {

            if($select_carrier == "Add New Carrier"){
                $data['carrier_name'] = $carrier_name = $this->input->post('carrier_name');
                $data['contact_number'] = $customer_number = $this->input->post('contact_num');
                $data['tel_number'] = $this->input->post('tel_number');
                
                if($user_type == 1){
                    $data['gold_tot_amount'] = $tot_gold_qty;
                    $data['cash_tot_amount'] = $tot_amount;
                    $data['balance_amount'] = $tot_amount;
                }else{
                    $data['gold_tot_amount'] = 0.000;
                    $data['cash_tot_amount'] = 0.00;
                    $data['balance_amount'] = 0.00;
                }

                $data['paid_amount'] = 0.00;

                $added_carrier = $this->admin_db->save_add_carrier_details($data);

                $data['carrier_id'] = $added_carrier['id'];

            }else{
                $data['carrier_id'] = $select_carrier;

                $carrier_details = $this->admin_db->get_carrier_by_id($select_carrier);
                
                if($user_type == 1){

                    $amounts['gold_tot_amount'] = $carrier_details->gold_tot_amount + $tot_gold_qty;
                    $amounts['cash_tot_amount'] = $carrier_details->cash_tot_amount + $tot_amount;

                    $amounts['paid_amount'] = $carrier_details->paid_amount;
                    $amounts['balance_amount'] = $carrier_details->balance_amount + $tot_amount;

                    $this->admin_db->update_carrier_accounts($select_carrier, $amounts);
                
                }

            }

            $data['total_amount'] = $tot_amount;  
            $data['paid_amount'] = 0.00;  
            $data['balance_amount'] = $tot_amount;  
            
            $data['description'] = NULL; 
            
            if($tot_amount > 3){
                $data['payment_status'] = 1;  
                
            }else{
                $data['payment_status'] = 3; 
                
            }

            if($user_type != 1){

                $data['status'] = 2;   
                $added_purchase = $this->admin_db->add_purchase($data);

                $data['item_id'] = $added_purchase['id'];
                
                if($k_stock_type == 'DXB 22K'){
                    $data['item_type'] = 'Dxb Purchase';
                }elseif($k_stock_type == 'BOX 22K'){
                    $data['item_type'] = 'Box Purchase';
                }              
                
                $data['amount'] = number_format($tot_gold_qty,3,'.',',').' g';
                $data['description'] = NULL;
                $this->admin_db->add_approval_requests($data);

            }else{

                $data['status'] = 1;   
                $added_purchase = $this->admin_db->add_purchase($data);
                
            }
               
            $total_purchase_grams = 0;

            for ($x = 0; $x < count($purchase_data['purchase_supplier_id']); $x++) {
                
                $purchase_invoice = $purchase_data['purchase_invoice_select'][$x];
                
                if($purchase_invoice == "Add New Invoice"){
                    $data1['purchase_id'] = $added_purchase['id'];
                    $data1['supplier_id'] = $purchase_data['purchase_supplier_id'][$x];                
                    $data1['invoice_num'] = $purchase_data['new_purchase_invoice'][$x];
                    $data1['invoice_weight'] = $purchase_data['invoice_weight'][$x];
                    $data1['actual_weight'] = $purchase_data['actual_weight'][$x];
                    $data1['pending_weight'] = $purchase_data['pending_weight'][$x];
                    $data1['received_weight'] = $purchase_data['received_weight'][$x];

                    if($data1['pending_weight'] != 0 && $data1['received_weight'] < $data1['actual_weight']){
                        $data1['status'] = 2;
                    }else{
                        $data1['status'] = 1;
                    }

                    $total_purchase_grams += $purchase_data['received_weight'][$x];

                    $this->admin_db->add_purchase_suppliers($data1);
                }else{
                    
                    $purchase_invoice_id = $purchase_data['purchase_invoice_id'][$x];
                    
                    $invoice_details = $this->admin_db->get_purchase_supplier_by_id($purchase_invoice_id);
                    
                    $data2['actual_weight'] = $purchase_data['actual_weight'][$x];
                    
                    $data2['pending_weight'] = $invoice_details->pending_weight - $purchase_data['received_weight'][$x];
                    $data2['received_weight'] = $invoice_details->received_weight + $purchase_data['received_weight'][$x];

                    if($data2['pending_weight'] != 0 && $data2['received_weight'] < $data2['actual_weight']){
                        $data2['status'] = 2;
                    }else{
                        $data2['status'] = 1;
                    }

                    if($user_type == 1){
                        $total_purchase_grams += $purchase_data['received_weight'][$x];
                        $this->admin_db->update_purchase_supplier_accounts($purchase_invoice_id, $data2);
                    }
                    
                    $data2['purchase_id'] = $added_purchase['id'];
                    $data2['supplier_id'] = $purchase_data['purchase_supplier_id'][$x];                
                    $data2['invoice_num'] = $invoice_details->invoice_num;
                    $data2['invoice_weight'] = $purchase_data['invoice_weight'][$x];

                    $this->admin_db->add_purchase_suppliers($data2);
                    
                }
            }

            if($user_type == 1){
            
                if($k_stock_type == 'DXB 22K'){

                    $stock_details = $this->admin_db->get_stock_details();

                    $tt_gold_in_hand = $stock_details->tt_gold_in_hand;
                    $new_tt_gold_in_hand = $tt_gold_in_hand + $total_purchase_grams;

                    $this->admin_db->update_stock_details('tt_gold_in_hand', $new_tt_gold_in_hand);

                    $carrier_details = $this->admin_db->get_carrier_by_id($select_carrier);

                    $account['item_type'] = 'purchase';
                    $account['item_id'] = $added_purchase['id'];
                    $account['action_type'] = 'Credited';
                    $account['amount'] = $total_purchase_grams;
                    $account['description'] = 'Purchased, Carrier - '.$carrier_details->carrier_name;

                    $this->admin_db->add_22k_gold_logs($account);

                }elseif($k_stock_type == 'BOX 22K'){

                    $stock_details = $this->admin_db->get_stock_details();

                    $box_tt_gold_in_hand = $stock_details->box_tt_gold_in_hand;
                    $new_box_tt_gold_in_hand = $box_tt_gold_in_hand + $total_purchase_grams;

                    $this->admin_db->update_stock_details('box_tt_gold_in_hand', $new_box_tt_gold_in_hand);

                    $carrier_details = $this->admin_db->get_carrier_by_id($select_carrier);

                    $account['item_type'] = 'purchase';
                    $account['item_id'] = $added_purchase['id'];
                    $account['action_type'] = 'Credited';
                    $account['amount'] = $total_purchase_grams;
                    $account['description'] = 'Purchased, Carrier - '.$carrier_details->carrier_name;

                    $this->admin_db->add_box_22k_gold_logs($account);

                }
            }
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }
        
        if($added_purchase['status'] == 1){
            echo json_encode(array("message" => "Purchase Added Successfully", "status" => "1"));
            
        }
    }

    public function view_purchase()
    {
        $id = $this->input->get('purchase_id');
        
        $data['title'] = 'View Good Received Note';
        
        $data['purchase_details'] = $this->admin_db->get_purchase_details_by_id($id);
        $data['purchase_suppliers'] = $this->admin_db->get_purchase_suppliers_by_sale_id($id); 
        
//        echo '<pre>'. print_r($data['purchase_suppliers'],1). '</pre>'; exit;
                
        $this->load->view('dashboard/header');
        $this->load->view('dashboard/left_nav', $data);
        $this->load->view('dashboard/view_purchase', $data);
        $this->load->view('dashboard/footer');
    }

    public function ajax_get_pending_purchase_supplier_invoices()
    {
        $supplier_id = $this->input->post('supplier_id');
        header('Content-Type: application/json');
        
        $invoice_details = $this->admin_db->get_pending_purchase_supplier_invoices($supplier_id);
        
        echo json_encode($invoice_details);
    }

    public function ajax_get_invoice_details_purchase()
    {
        $purchase_supplier_id = $this->input->post('purchase_supplier_id');
        header('Content-Type: application/json');
        
        $invoice_details = $this->admin_db->get_purchase_supplier_by_id($purchase_supplier_id);
        
        echo json_encode($invoice_details);
    }

    public function save_make_carrier_charges_payment()
    {     
        $data['purchase_id'] = $purchase_id = $this->input->post('purchase_id');
        $data['carrier_id'] = $carrier_id = $this->input->post('carrier_id');
        $invoice_date = $this->input->post('invoice_date');
        $data['date'] = date("Y-m-d", strtotime($invoice_date));
        
        $data['payment_method'] = $payment_method = $this->input->post('payment_method');
        $payment_amount = $data['amount'] = $this->input->post('payment_amount');
        
        $bank_id = NULL;
        
        if($payment_method == 'Cash'){
            $data['account_id'] = NULL;
            $data['cheque_number'] = NULL;
            $data['cheque_deposit_date'] = NULL;
            $data['third_party_bank_id'] = NULL;
            $data['third_party_account_number'] = NULL;
            
        }elseif($payment_method == 'Cheque'){
            $bank_account_id = $data['account_id'] = $this->input->post('cheq_bank_account');
            $cheque_number = $data['cheque_number'] = $this->input->post('cheq_cheque_number');
            $cheque_deposit_date = $this->input->post('cheq_deposit_date');
            $data['cheque_deposit_date'] = date("Y-m-d", strtotime($cheque_deposit_date));
            $data['third_party_bank_id'] = NULL;
            $data['third_party_account_number'] = NULL;
            
        }elseif($payment_method == 'Bank Transfer'){
            $bank_account_id = $data['account_id'] = $this->input->post('transfer_bank_account');
            $cheque_number = $data['cheque_number'] = NULL;
            $data['cheque_deposit_date'] = NULL;
            $bank_id = $data['third_party_bank_id'] = $this->input->post('bank_bank_name');
            $data['third_party_account_number'] = $this->input->post('bank_account_number');
            
        }elseif($payment_method == 'Bank Deposit'){
            $data['account_id'] = NULL;
            $data['cheque_number'] = NULL;
            $data['cheque_deposit_date'] = NULL;
            $bank_id = $data['third_party_bank_id'] = $this->input->post('bank_bank_name');
            $data['third_party_account_number'] = $this->input->post('bank_account_number');
            
        }
        
        header('Content-Type: application/json');
        
        $data['status'] = 1;
        
        try {  
            
            $added_payment = $this->admin_db->add_carrier_charges_payment($data);
            
            $purchase_details = $this->admin_db->get_purchase_details_by_id($purchase_id);

            $p_amounts['total_amount'] = $purchase_details->total_amount;
            $p_amounts['paid_amount'] = $purchase_details->paid_amount + $payment_amount;
            $p_amounts['balance_amount'] = $balance_amount = $purchase_details->balance_amount - $payment_amount;
            
            if($balance_amount > 0){
                $p_amounts['payment_status'] = 2;
            }else{
                $p_amounts['payment_status'] = 1;
            }

            $this->admin_db->update_purchase_accounts($purchase_id, $p_amounts);
            
            $carrier_details = $this->admin_db->get_carrier_by_id($carrier_id);

            $cc_amounts['gold_tot_amount'] = $carrier_details->gold_tot_amount;
            $cc_amounts['cash_tot_amount'] = $carrier_details->cash_tot_amount;
            $cc_amounts['paid_amount'] = $carrier_details->paid_amount + $payment_amount;
            $cc_amounts['balance_amount'] = $carrier_details->balance_amount - $payment_amount;

            $this->admin_db->update_carrier_accounts($carrier_id, $cc_amounts);
            
            if($bank_id){
                $bank_details = $this->admin_db->get_bank_by_id($bank_id);
            }

            if($added_payment['status'] == 1){
                
                $stock_details = $this->admin_db->get_stock_details();

                if($payment_method == 'Cash'){
                    $cash_in_hand = $stock_details->cash_in_hand;
                    $new_cash_in_hand = $cash_in_hand - $payment_amount;

                    $this->admin_db->update_stock_details('cash_in_hand', $new_cash_in_hand);

                    $account['action_date'] = $data['date'];
                    $account['item_type'] = 'payment';
                    $account['item_id'] = $added_payment['id'];
                    $account['action_type'] = 'Debited';
                    $account['amount'] = $payment_amount;
                    $account['description'] = 'Carrier Charges For '.$carrier_details->carrier_name;

                    $this->admin_db->add_cash_logs($account);

                }

                if($payment_method == 'Cheque'){
                    $account_details = $this->admin_db->get_bank_account_by_id($bank_account_id);

                    $bank_balance = $account_details->bank_balance;
                    $new_bank_balance  = $bank_balance - $payment_amount;

                    $this->admin_db->update_bank_balance($bank_account_id, $new_bank_balance);

                    $account['account_id'] = $bank_account_id;
                    $account['item_type'] = 'payment';
                    $account['item_id'] = $added_payment['id'];
                    $account['action_type'] = 'Debited';
                    $account['amount'] = $payment_amount;
                    $account['description'] = 'Cheque Issued For Carrier Charges, Cheque Number - '.$cheque_number;

                    $this->admin_db->add_bank_account_logs($account);

                }

                if($payment_method == 'Bank Deposit'){
                    $cash_in_hand = $stock_details->cash_in_hand;
                    $new_cash_in_hand = $cash_in_hand - $payment_amount;

                    $this->admin_db->update_stock_details('cash_in_hand', $new_cash_in_hand);

                    $account['action_date'] = $data['date'];
                    $account['item_type'] = 'payment';
                    $account['item_id'] = $added_payment['id'];
                    $account['action_type'] = 'Debited';
                    $account['amount'] = $payment_amount;
                    $account['description'] = 'Carrier Charges - Bank Deposited To - '.$bank_details->bank_name.', Bank A/C No. - '.$data['third_party_account_number'];

                    $this->admin_db->add_cash_logs($account);

                }

                if($payment_method == 'Bank Transfer'){
                    $account_details = $this->admin_db->get_bank_account_by_id($bank_account_id);

                    $bank_balance = $account_details->bank_balance;
                    $new_bank_balance  = $bank_balance - $payment_amount;

                    $this->admin_db->update_bank_balance($bank_account_id, $new_bank_balance);

                    $account['account_id'] = $bank_account_id;
                    $account['item_type'] = 'payment';
                    $account['item_id'] = $added_payment['id'];
                    $account['action_type'] = 'Debited';
                    $account['amount'] = $payment_amount;
                    $account['description'] = 'Carrier Charges - Bank Tranfered To - '.$bank_details->bank_name.', Bank A/C No. - '.$data['third_party_account_number'];

                    $this->admin_db->add_bank_account_logs($account);

                }

                echo json_encode(array("message" => "Carrier Charges Payment Added Successfully", "status" => "1", 'approval' => false, "purchase_id" => $purchase_id));

            }else{
                echo json_encode(array("message" => "An Error Occured while Adding Carrier Charges Payment", "status" => "0", "purchase_id" => $purchase_id));

            }
        }

        catch(Exception $e) {
          echo 'Message: ' .$e->getMessage();
        }
    }
}
