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

class Customers extends CI_Controller
{

    var $main_menu_name = "people";
    var $sub_menu_name = "customers";

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

        $this->load->model('Customer_Model');
        $this->load->model('Common_Model');
        $this->load->model('Sequerty_Model');
        $this->load->model('Warehouse_Model');
        $this->load->model('Route_Model');
        $this->load->library('form_validation');
        $this->load->library('upload');
    }

    public function index()
    {
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name'] = $this->sub_menu_name;

        $this->load->view('customers/index', $data);
    }

    public function get_personal_info($cus_id)
    {
        $customer = $this->Customer_Model->get_customer_info($cus_id); // Fetch personal info
        $spouse     = $this->Customer_Model->get_spouse_info($cus_id);
        $guarantor  = $this->Customer_Model->get_customer_guarantor_info($cus_id);
        $banks = $this->Customer_Model->get_customer_banks($cus_id);
        $loans = $this->Customer_Model->get_customer_loans($cus_id);

        if (!empty($customer)) {
            // Check if business info exists
            $hasBusinessInfo = !empty($customer['cus_company']) || !empty($customer['cus_type']);

            // Check if documents exist
            $documents = $this->Customer_Model->get_documents($cus_id);
            $hasDocuments = !empty($documents);

            $response = [
                'success' => true,
                'customer' => [
                    'title'                 => $customer['title'],
                    'full_name'             => $customer['full_name'],
                    'date_of_birth'         => $customer['date_of_birth'],
                    'nic'                   => $customer['cus_nic'],
                    'nic_issue_date'        => $customer['nic_issue_date'],
                    'passport_number'       => $customer['passport_number'],
                    'mobile'                => $customer['cus_mobile'],
                    'mobile2'               => $customer['cus_mobile_2'],
                    'email'                 => $customer['cus_email'],
                    'home_phone'            => $customer['cus_home_phone'],
                    'permanent_address'     => $customer['cus_address'],
                    'correspondent_address' => $customer['correspondent_address'],
                    'position_held'         => $customer['position_held'],
                    'business_type'         => $customer['business_type'],
                    // Financial / family
                    'income'                        => $customer['income'],
                    'dependents'                    => $customer['dependents'],
                    'status_residential_address'    => $customer['status_residential_address'],
                    'residential_property_value'    => $customer['residential_property_value'],
                    'motor_vehicles_value'          => $customer['motor_vehicles_value'],
                    'investments'                   => $customer['investments'],
                    'aoowaev_other'                 => $customer['aoowaev_other'],
                    'other_connected_activities'    => $customer['other_connected_activities'],
                    'spouse' => !empty($spouse) ? $spouse : null,
                    'guarantor' => !empty($guarantor) ? $guarantor : null,
                    'banks' => $banks,
                    'loans' => $loans
                ],

                'hasBusinessInfo' => $hasBusinessInfo,
                'hasDocuments'    => $hasDocuments
            ];
        } else {
            $response = ['success' => false, 'message' => 'Customer not found'];
        }

        header('Content-Type: application/json');
        echo json_encode($response);
    }


    public function get_business_info($cus_id)
    {
        $customer_business = $this->Customer_Model->get_business_info($cus_id);
        $bankAccounts = $this->Customer_Model->get_bank_accounts($customer_business->id);

        if (!empty($customer_business)) {
            $response = [
                'success' => true,
                'business' => $customer_business,
                'bankAccounts' => $bankAccounts,
            ];
        } else {
            $response = ['success' => false, 'message' => 'Business info not found'];
        }

        header('Content-Type: application/json');
        echo json_encode($response);
    }


    public function customer_detail($cus_id)
    {
        $customer = $this->Customer_Model->get_customer_info($cus_id);

        if (!$customer) {
            show_404();
        }
        //echo '<pre>',print_r($customer); die();
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'customer_detail';
        $data['customer']       = $customer;

        // If you have business info & documents in separate tables, load them here
        $data['business_info']  = $this->Customer_Model->get_business_info($cus_id);
        $data['documents']      = $this->Customer_Model->get_documents($cus_id);
        $data['bank_accounts'] = $this->Customer_Model->get_customer_banks($cus_id);
        $data['loans'] = $this->Customer_Model->get_customer_loans($cus_id);
        $data['spouse_details'] = $this->Customer_Model->get_spouse_info($cus_id);;
        $data['guarantor_details'] = $this->Customer_Model->get_customer_guarantor_info($cus_id);

        $this->load->view('customers/customer_detail', $data);
    }




    // Process form submission 
    public function add_customer()
    {
        // Validation rules (basic only, you can expand as needed)
        $this->form_validation->set_rules('cus_code', 'Code', 'required|is_unique[customer.cus_code]');
        $this->form_validation->set_rules('full_name', 'Name', 'required');
        $this->form_validation->set_rules('nic', 'NIC', 'required');
        //$this->form_validation->set_rules('mobile', 'Mobile', 'required');
        //$this->form_validation->set_rules('permanent_address', 'Address', 'required');


        if ($this->form_validation->run() == FALSE) {
            $response = array(
                'status' => 0,
                'validation' => validation_errors()
            );
        } else {
            // Generate customer code
            //$cus_code = $this->Customer_Model->generate_customer_code();

            // Main customer data
            $customer_data = array(
                'title' => $this->input->post('title'),
                'full_name' => $this->input->post('full_name'),
                'date_of_birth' => $this->input->post('date_of_birth'),
                'cus_nic' => $this->input->post('nic'),
                'nic_issue_date' => $this->input->post('nic_issue_date'),
                'passport_number' => $this->input->post('passport_number'),
                'cus_mobile' => $this->input->post('mobile'),
                'cus_mobile_2' => $this->input->post('mobile2'),
                'cus_home_phone' => $this->input->post('home_phone'),
                'cus_email' => $this->input->post('email'),
                'cus_company' => $this->input->post('cus_company'),
                'cus_address' => $this->input->post('permanent_address'),
                'correspondent_address' => $this->input->post('correspondent_address_personal'),
                'cus_state' => $this->input->post('cus_state'),
                'cus_postal_code' => $this->input->post('cus_postal_code'),
                'country_id' => $this->input->post('country_id'),
                'city_name' => $this->input->post('city_name'),
                'cus_route' => $this->input->post('cus_route'),
                'position_held' => $this->input->post('position_held'),
                'status_residential_address' => $this->input->post('status_residential_address'),
                'residential_property_value' => $this->input->post('residential_property_value'),
                'motor_vehicles_value' => $this->input->post('motor_vehicles_value'),
                'investments' => $this->input->post('investments'),
                'aoowaev_other' => $this->input->post('aoowaev_other'),
                'other_connected_activities' => $this->input->post('other_connected_activities'),
                'dependents' => $this->input->post('dependents'),
                'income' => $this->input->post('income'),
                'business_type' => $this->input->post('business_type'),
                'warehouse_id' => $this->session->userdata('ss_warehouse_id'),
                'cus_code' => $this->input->post('cus_code'),
                'cus_type' => 'loan',
                'cus_status' => 1,
                'location_status' => 0,
                'locaton_update_user_id' => 0
            );

            $cus_id = $this->input->post('customer_id');
            $type = $this->input->post('cus_type');

            if ($type == 'A') {
                // Insert new customer
                $customer_id = $this->Customer_Model->add_customer($customer_data);

                if ($customer_id) {
                    // ---- Save spouse details ----
                    $spouse_data = array(
                        'cus_id' => $customer_id,
                        'spouse_name' => $this->input->post('spouse_name'),
                        'spouse_occupation' => $this->input->post('spouse_occupation'),
                        'spouse_contact' => $this->input->post('spouse_contact'),
                        'spouse_nic' => $this->input->post('spouse_nic'),
                        'spouse_em_address' => $this->input->post('spouse_em_address')
                    );
                    $this->Customer_Model->save_spouse($spouse_data);

                    if (!empty($this->input->post('guarantor_name'))) {
                        // ---- Save guarantor details ----
                        $guarantor_data = array(
                            'cus_id' => $customer_id,
                            'guarantor_name' => $this->input->post('guarantor_name'),
                            'guarantor_contact' => $this->input->post('guarantor_contact'),
                            'guarantor_nic' => $this->input->post('guarantor_nic'),
                            'guarantor_address' => $this->input->post('guarantor_address')
                        );
                        $this->Customer_Model->save_guarantor($guarantor_data);
                    }


                    $banks = $this->input->post('banks');   // array of bank rows
                    $loans = $this->input->post('loans');   // array of loan rows

                    if (!empty($banks)) {
                        $this->Customer_Model->save_customer_banks($customer_id, $banks);
                    }

                    if (!empty($loans)) {
                        $this->Customer_Model->save_customer_loans($customer_id, $loans);
                    }


                    $response = array(
                        'status' => 1,
                        'customer_id' => $customer_id,
                        'message' => 'Customer data saved successfully!'
                    );
                } else {
                    $response = array(
                        'status' => 0,
                        'message' => 'Failed to save customer data.'
                    );
                }
            } else {
                // Update existing customer
                $this->Customer_Model->save_customer($customer_data, $cus_id);

                // Update spouse
                $spouse_data = array(
                    'cus_id' => $cus_id,
                    'spouse_name' => $this->input->post('spouse_name'),
                    'spouse_occupation' => $this->input->post('spouse_occupation'),
                    'spouse_contact' => $this->input->post('spouse_contact'),
                    'spouse_nic' => $this->input->post('spouse_nic'),
                    'spouse_em_address' => $this->input->post('spouse_em_address')
                );
                $this->Customer_Model->update_spouse($spouse_data, $cus_id);

                if (!empty($this->input->post('guarantor_name'))) {
                    // Update guarantor
                    $guarantor_data = array(
                        'cus_id' => $cus_id,
                        'guarantor_name' => $this->input->post('guarantor_name'),
                        'guarantor_contact' => $this->input->post('guarantor_contact'),
                        'guarantor_nic' => $this->input->post('guarantor_nic'),
                        'guarantor_address' => $this->input->post('guarantor_address')
                    );
                    $this->Customer_Model->update_guarantor($guarantor_data, $cus_id);
                }

                $response = array(
                    'status' => 1,
                    'customer_id' => $cus_id,
                    'message' => 'Customer data updated successfully!'
                );
            }
        }

        echo json_encode($response);
    }



    // Handle document uploads
    public function upload_document()
    {
        $response = array('success' => false, 'message' => '');

        // Check if document and doc_type are provided
        if (empty($_FILES['document']['name']) || !$this->input->post('doc_type') || !$this->input->post('customer_id')) {
            $response['message'] = 'Required parameters missing';
            echo json_encode($response);
            return;
        }

        $customer_id = $this->input->post('customer_id');
        $doc_type = $this->input->post('doc_type');

        // Configure upload
        $config['upload_path'] = './uploads/documents/' . $customer_id . '/';
        $config['allowed_types'] = 'jpg|jpeg|png|pdf|doc|docx';
        $config['max_size'] = 5120; // 5MB
        $config['file_name'] = $doc_type . '_' . time();

        // Create directory if it doesn't exist
        if (!is_dir($config['upload_path'])) {
            mkdir($config['upload_path'], 0777, true);
        }

        $this->upload->initialize($config);

        if ($this->upload->do_upload('document')) {
            $upload_data = $this->upload->data();

            // Save document info to database
            $document_data = array(
                'cus_id' => $customer_id,
                'doc_type' => $doc_type,
                'file_name' => $upload_data['file_name'],
                'original_name' => $upload_data['orig_name'],
                'file_path' => $config['upload_path'],
                'uploaded_at' => date('Y-m-d H:i:s')
            );

            if ($this->Customer_Model->save_document($document_data)) {
                $response['success'] = true;
                $response['message'] = 'Document uploaded successfully';
            } else {
                $response['message'] = 'Failed to save document information';
            }
        } else {
            $response['message'] = $this->upload->display_errors('', '');
        }

        echo json_encode($response);
    }

    // Get customer documents
    public function get_documents($cus_id)
    {
        $documents = $this->Customer_Model->get_documents($cus_id);

        if (!empty($documents)) {
            $response = [
                'success' => true,
                'documents' => $documents
            ];
        } else {
            $response = ['success' => false, 'documents' => []];
        }

        header('Content-Type: application/json');
        echo json_encode($response);
    }



    public function create_customers()
    {
        $data['id'] = 1;
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name'] = 'create_customer';

        $data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();

        if (isset($_GET['cus_id'])) {
            $cus_id = $_GET['cus_id'];
        } else {
            $cus_id = 0;
        }
        if ($cus_id) {
            $data['cus_id'] = $cus_id;
            $data['type'] = 'E';
            $data['pageName'] = 'UPDATE CUSTOMER';
            $data['btnText'] = 'Update Customer';
            $data['customer'] = $this->Customer_Model->get_customer_info($cus_id);
        } else {
            $data['cus_id'] = '';
            $data['type'] = 'A';
            $data['pageName'] = 'ADD CUSTOMER';
            $data['btnText'] = 'Add Customer';
            $data['customer'] = array();
        }
        if (isset($_GET['btn_id'])) {
            $data['btn_id'] = $_GET['btn_id'];
        }
        $data['routes_list'] = $this->Route_Model->get_all_active_routes();
        $data['country_list'] = $this->Common_Model->get_all_country();
        $this->load->view('models/create_customer', $data);
    }

    function get_all_customers()
    {
        $this->db->select('cus_name', 'cus_id');
        $this->db->order_by("cus_name", "asc");
        $this->db->where("cus_status=1"); //("id !=",$id);
        $query = $this->db->get('customers');
        return $query->result_array();
    }


    public function save_customer()
    {
        $cus_id = $this->input->post('customer_id');
        $type = $this->input->post('type');
        $country_id = $this->input->post('country_id');
        $city_name = $this->input->post('city_name');
        $cus_name = $this->input->post('cus_name');
        $cus_email = $this->input->post('cus_email');
        $cus_phone = $this->input->post('cus_phone');
        $cus_address = $this->input->post('cus_address');
        $cus_state = $this->input->post('cus_state');
        $cus_postal_code = $this->input->post('cus_postal_code');
        $cus_mobile = $this->input->post('cus_mobile');
        $cus_mobile_2 = $this->input->post('cus_mobile_2');
        $cus_home_phone = $this->input->post('cus_home_phone');
        $warehouse_id = $this->input->post('warehouse_id_c');
        $cus_nic = $this->input->post('cus_nic');
        $route_id = $this->input->post('route_id');
        $cus_type = $this->input->post('cus_type');

        $this->load->library('form_validation'); //form validation lib		
        $this->form_validation->set_rules('cus_name', 'Name', 'required');
        $this->form_validation->set_rules('cus_address', 'Address', 'required');
        $this->form_validation->set_rules('cus_mobile', 'Mobile 01', 'required');
        if ($type == 'A') {
            $this->form_validation->set_rules('cus_nic', 'NIC', 'required|is_unique[customer.cus_nic]');
        }

        if ($this->form_validation->run() == FALSE) {
            $st = array('status' => 0, 'validation' => validation_errors());
            echo json_encode($st);
        } else {
            $data = array(
                'country_id' => $country_id,
                'city_name' => $city_name,
                'cus_name' => $cus_name,
                'cus_email' => $cus_email,
                'cus_phone' => $cus_phone,
                'cus_address' => $cus_address,
                'cus_state' => $cus_state,
                'cus_postal_code' => $cus_postal_code,
                'cus_mobile' => $cus_mobile,
                'cus_mobile_2' => $cus_mobile_2,
                'cus_home_phone' => $cus_home_phone,
                'warehouse_id' => 1,
                'cus_nic' => $cus_nic,
                'cus_route' => $route_id,
                'cus_type' => $cus_type,
            );
            if ($type == 'A') {
                $_insert = $this->Customer_Model->save_customer($data, '');
                //echo $this->db->last_query();
                $lastid = $this->db->insert_id();
                //set session			
                if ($lastid) {
                    $data1 = array(
                        'ss_cus_id' => $lastid,
                    );
                    $this->session->set_userdata($data1);
                    echo json_encode(array('id' => $lastid, 'type' => $type, 'status' => 1));
                } else {
                    echo json_encode(array('status' => '0', 'validation' => 'Error'));
                }
                //update cus_code
                $data2 = array();
                $data2 = array(
                    'cus_code' => 'CUS/' . $lastid,
                );
                $this->Customer_Model->save_customer($data2, $lastid);
            }
            if ($type == 'E') {
                $_insert = $this->Customer_Model->save_customer($data, $cus_id);
                echo json_encode(array('type' => $type, 'status' => 1));
            }
            // $st = array('status' =>1,'validation' => validation_errors());
            // echo json_encode($st);
        }
    }

    public function list_customer()
    {
        $requestData = $_REQUEST;

        $columns = array(
            0 => 'cus_id',
            1 => 'cus_name',
            2 => 'cus_email',
            3 => 'cus_phone',
            4 => 'cus_phone',
            5 => 'cus_id'
        );
        $start            = $this->input->get('start');
        $length           = $this->input->get('length');
        $search           = $this->input->get('search');

        $data = array();
        $customers = $this->Customer_Model->get_all_customer($start, $length, $search['value']);
        $count = $this->Customer_Model->get_all_customer("", "", $search['value']);

        //print_r($count);
        $totalData = $count;
        $totalFiltered = $totalData;

        foreach ($customers as $row) {
            $nestedData = array();
            $nestedData[] = $row['cus_code'];
            $nestedData[] = $row['business_name'];
            $nestedData[] = $row['full_name'];
            $nestedData[] = $row['registered_address'];
            $nestedData[] = $row['cus_mobile'];
            $actionTxtDisble = '';
            $actionTxtEnable = '';
            $actionTxtUpdate = '';
            $actionTxtDelete = '';
            $actionTxtUpdate = '<a onClick="click_customer_update_btn(' . $row['cus_id'] . ')" data-toggle="modal" href="#" class="btn btn-xs btn-blue tooltips" data-placement="top" data-original-title="Edit customers"><i class="glyphicon fa fa-edit"></i></a> <a href="' . base_url('customers/customer_detail/' . $row['cus_id']) . '"  class="btn btn-xs btn-info tooltips" data-placement="top" data-original-title="customers Details"><i class="glyphicon fa fa-info"></i></a>&nbsp;';
            if ($row['cus_status'] == 1) {
                $actionTxtDisble = '<a class="btn btn-xs btn-green tooltips" data-placement="top" data-original-title="Disable customer" onClick="disableCustomerData(' . $row['cus_id'] . ')"><i class="glyphicon fa fa-check"></i></a> &nbsp;';
            }
            if ($row['cus_status'] == 0) {
                $actionTxtEnable = '<a class="btn btn-xs btn-warning tooltips" data-placement="top" data-original-title="Disable customer" onClick="enableCustomerData(' . $row['cus_id'] . ')"><i class="glyphicon fa fa-minus-circle"></i></a> &nbsp;';
            }
            /*$actionTxtDelete='<a class="btn btn-xs btn-bricky tooltips" data-placement="top" data-original-title="Delete customer" onClick="deleteCustomerData('.$row['cus_id'].')">
															<i class="glyphicon fa fa-trash-o"></i></a>';*/

            $nestedData[] = $actionTxtUpdate . $actionTxtDisble . $actionTxtEnable . $actionTxtDelete;
            $data[] = $nestedData;
        }

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

        echo json_encode($json_data);
    }


    function delete_customer()
    {
        $cus_id    = $this->input->post('cus_id');
        $this->Customer_Model->delete_customer($cus_id);
        if ($cus_id) {
            echo json_encode(array('id' => $cus_id));
        } else {
            echo json_encode(array('status' => 'error'));
        }
    }

    function disable_customer()
    {
        $cus_id    = $this->input->post('cus_id');
        $this->Customer_Model->disable_customer($cus_id);
        if ($cus_id) {
            echo json_encode(array('id' => $cus_id));
        } else {
            echo json_encode(array('status' => 'error'));
        }
    }

    function enable_customer()
    {
        $cus_id    = $this->input->post('cus_id');
        $this->Customer_Model->enable_customer($cus_id);
        if ($cus_id) {
            echo json_encode(array('id' => $cus_id));
        } else {
            echo json_encode(array('status' => 'error'));
        }
    }

    function filter_customer()
    {
        $search           = $this->input->get('search_string');
        $customers = $this->Customer_Model->get_all_customer_filter($search);

        echo json_encode($customers);
    }

    function filter_guarantor()
    {
        $search           = $this->input->get('search_string');
        $customers = $this->Customer_Model->get_all_guarantor_filter($search);

        echo json_encode($customers);
    }


    public function save_business_info()
    {
        // Set validation rules
        $this->form_validation->set_rules('customer_id', 'Customer ID', 'required|numeric');
        $this->form_validation->set_rules('business_name', 'Business Name', 'required');
        //$this->form_validation->set_rules('registered_address', 'Registered Address', 'required');
        //$this->form_validation->set_rules('registration_number', 'Registration Number', 'required');
        //$this->form_validation->set_rules('incorporation_date', 'Date of Incorporation', 'required');
        //$this->form_validation->set_rules('business_nature', 'Nature of Business', 'required');
        //$this->form_validation->set_rules('contact_number', 'Contact Number', 'required');
        //$this->form_validation->set_rules('email_address', 'Email Address', 'required|valid_email');

        if ($this->form_validation->run() == FALSE) {
            // Validation failed
            $response = array(
                'status' => 'error',
                'message' => validation_errors()
            );
        } else {
            // Validation passed, save data
            $customer_id = $this->input->post('customer_id');

            // Prepare business data
            $business_data = array(
                'customer_id' => $customer_id,
                'business_name' => $this->input->post('business_name'),
                'registered_address' => $this->input->post('registered_address'),
                'correspondent_address' => $this->input->post('correspondent_address'),
                'registration_number' => $this->input->post('registration_number'),
                'date_of_incorporation' => $this->input->post('incorporation_date'),
                'nature_of_business' => $this->input->post('business_nature'),
                'contact_number' => $this->input->post('contact_number'),
                'email_address' => $this->input->post('email_address'),
                'property_asset_value' => $this->input->post('property_value') ?: 0,
                'vehicles_asset_value' => $this->input->post('vehicles_value') ?: 0,
                'investments_asset_value' => $this->input->post('investments_value') ?: 0,
                'daily_turnover' => $this->input->post('daily_turnover') ?: 0,
                'daily_profit' => $this->input->post('daily_profit') ?: 0,
                'total_liabilities' => $this->input->post('total_liabilities') ?: 0,
                'created_at' => date('Y-m-d H:i:s')
            );

            // Save business information
            $business_id = $this->Customer_Model->save_business_info($business_data);

            if ($business_id) {
                // Save bank accounts
                $bank_names = $this->input->post('bank_name');
                $bank_branches = $this->input->post('bank_branch');
                $account_numbers = $this->input->post('account_number');
                $account_types = $this->input->post('account_type');

                if (!empty($bank_names)) {
                    foreach ($bank_names as $index => $bank_name) {
                        if (!empty($bank_name) && !empty($account_numbers[$index])) {
                            $bank_data = array(
                                'business_id' => $business_id,
                                'bank_name' => $bank_name,
                                'branch' => $bank_branches[$index],
                                'account_number' => $account_numbers[$index],
                                'account_type' => $account_types[$index],
                                'created_at' => date('Y-m-d H:i:s')
                            );

                            $this->Customer_Model->save_bank_account($bank_data);
                        }
                    }
                }

                $response = array(
                    'status' => 'success',
                    'message' => 'Business information saved successfully!'
                );
            } else {
                $response = array(
                    'status' => 'error',
                    'message' => 'Failed to save business information. Please try again.'
                );
            }
        }

        // Return JSON response
        header('Content-Type: application/json');
        echo json_encode($response);
    }

    public function guarantor()
    {
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name'] = $this->sub_menu_name;
        $this->load->view('guarantors/list', $data);
    }

    public function guarantor_list()
    {
        $requestData = $_REQUEST;

        $columns = array(
            0 => 'route_code',
            1 => 'route_name'
        );

        $data = array();
        $guarantors = $this->Customer_Model->get_all_guarantors();
        $totalData = count($guarantors);
        $totalFiltered = $totalData;

        foreach ($guarantors as $row) {
            $nestedData = array();
            $nestedData[] = $row['code'];
            $nestedData[] = $row['name'];
            $nestedData[] = $row['address'];
            $nestedData[] = $row['phone'];
            $actionTxtDisble = '';
            $actionTxtEnable = '';
            $actionTxtUpdate = '';
            $actionTxtDelete = '';
            $actionTxtUpdate = '<a onClick="click_guarantor_update_btn(' . $row['id'] . ')" data-toggle="modal" href="#" class="btn btn-xs btn-blue tooltips" data-placement="top" data-original-title="Edit suppliers"><i class="glyphicon fa fa-edit"></i></a> &nbsp;';
            if ($row['status'] == 1) {
                $actionTxtDisble = '<a class="btn btn-xs btn-green tooltips" data-placement="top" data-original-title="Disable supplier" onClick="disableUnitData(' . $row['id'] . ')"><i class="glyphicon fa fa-check"></i></a> &nbsp;';
            }
            if ($row['status'] == 0) {
                $actionTxtEnable = '<a class="btn btn-xs btn-warning tooltips" data-placement="top" data-original-title="Disable supplier" onClick="enableUnitData(' . $row['id'] . ')"><i class="glyphicon fa fa-minus-circle"></i></a> &nbsp;';
            }
            $actionTxtDelete = '<a class="btn btn-xs btn-bricky tooltips" data-placement="top" data-original-title="Delete supplier" onClick="deleteUnitData(' . $row['id'] . ')">
															<i class="glyphicon fa fa-trash-o"></i></a>';

            $nestedData[] = $actionTxtUpdate . $actionTxtDisble . $actionTxtEnable . $actionTxtDelete;
            $data[] = $nestedData;
        }

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

        echo json_encode($json_data);
    }

    public function add_guarantor()
    {
        if (isset($_GET['id'])) {
            $id = $_GET['id'];
        } else {
            $id = '';
        }
        if ($id) {
            $data['guarantor_id'] = $id;
            $data['type'] = 'E';
            $data['pageName'] = 'UPDATE  guarantor';
            $data['btnText'] = 'Update guarantor';
            $data['guarantor_details'] = $this->Customer_Model->get_guarantor_info($id);
        } else {
            $data['guarantor_id'] = '';
            $data['type'] = 'A';
            $data['pageName'] = 'ADD Guarantor';
            $data['btnText'] = 'Add Guarantor';
            $data['guarantor_details'] = array();
        }
        $this->load->view('models/create_guarantor', $data);
    }

    public function save_guarantor()
    {
        $id = $this->input->post('id');
        $type = $this->input->post('type');
        $name = $this->input->post('name');
        $code = $this->input->post('code');
        $address = $this->input->post('address');
        $phone = $this->input->post('phone');
        $data = array(
            'name' => $name,
            'code' => $code,
            'address' => $address,
            'phone' => $phone,
        );

        $this->load->library('form_validation'); //form validation lib
        if ($type == 'A') {
            $this->form_validation->set_rules('code', 'Code', 'required|is_unique[guarantors.code]');
        } else if ($type == 'E') {
            $this->form_validation->set_rules('code', 'Code', 'required');
        }

        if ($this->form_validation->run() == FALSE) {
            $st = array('status' => 0, 'validation' => validation_errors());
            echo json_encode($st);
        } else {

            $_insert = $this->Customer_Model->save_guarantor($data, $id);
            $lastid = $this->db->insert_id();

            if ($type == 'A') {
                if ($lastid) {
                    echo json_encode(array('id' => $lastid, 'type' => $type));
                } else {
                    echo json_encode(array('status' => 'error'));
                }
            }
            if ($type == 'E') {
                echo json_encode(array('type' => $type));
            }
        }
    }


    function delete_guarantor()
    {
        $id    = $this->input->post('id');
        $response = $this->Customer_Model->delete_guarantor($id);
        if ($response) {
            echo json_encode(array('id' => $id));
        } else {
            echo json_encode(array('status' => 'error'));
        }
    }

    function disable_guarantor()
    {
        $id    = $this->input->post('id');
        $response = $this->Customer_Model->disable_guarantor($id);
        if ($response) {
            echo json_encode(array('id' => $id));
        } else {
            echo json_encode(array('status' => 'error'));
        }
    }

    function enable_guarantor()
    {
        $id    = $this->input->post('id');
        $response = $this->Customer_Model->enable_guarantor($id);
        if ($response) {
            echo json_encode(array('id' => $id));
        } else {
            echo json_encode(array('status' => 'error'));
        }
    }
}
