<?php

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

class Supplier extends Admin_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model('common_model');
        $this->load->model('purchase_model');
        $this->load->model('return_stock_model');
    }

    public function index($id = NULL)
    {
        //echo 'testing'; exit;
        $data['title'] = lang('all') . ' ' . lang('supplier');
        $data['page_title'] = lang('supplier');
        $data['page_description'] = lang('all') . ' ' . lang('supplier');
        $data['datatable'] = true;
        $data['datatable_preload'] = $this->capture_datatable_preload(function () {
            $this->supplierList();
        });
        $data['active'] = 1;
        if (!empty(can_action('151', 'created')) || !empty(can_action('151', 'edited'))) {
            $data['header_actions'] = array(
                array(
                    'label' => lang('new') . ' ' . lang('supplier'),
                    'icon' => 'plus',
                    'href' => base_url('admin/supplier/create_supplier'),
                    'style' => 'primary',
                ),
            );
        }
        $data['subview'] = $this->load->view('admin/supplier/supplier_list', $data, TRUE);
        $this->load->view('admin/_layout_main', $data); //page load
    }

    public function supplierList()
    {
        if ($this->input->is_ajax_request()) {
            $this->load->model('datatables');
            $this->datatables->table = 'tbl_suppliers';

            $custom_field = custom_form_table_search(19);
            $action_array = array('supplier_id');
            $main_column = array('name', 'mobile', 'phone', 'email', 'address', 'vat');
            $result = array_merge($main_column, $custom_field, $action_array);
            $this->datatables->column_order = $result;
            $this->datatables->column_search = $result;

            $this->datatables->order = array('supplier_id' => 'desc');

            $fetch_data = make_datatables();

            $data = array();

            $edited = can_action('151', 'edited');
            $deleted = can_action('151', 'deleted');
            foreach ($fetch_data as $_key => $v_items) {
                $action = null;
                $sub_array = array();
                $sub_array[] = '<a data-toggle="modal" data-target="#myModal_extra_lg" href="' . base_url('admin/supplier/supplier_details/' . $v_items->supplier_id) . '" class="text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300">' . $v_items->name . '</a>';
                $sub_array[] = $v_items->mobile;
                $sub_array[] = $v_items->phone;
                $sub_array[] = $v_items->email;
                $sub_array[] = $v_items->address;
                $sub_array[] = $v_items->vat;

                $custom_form_table = custom_form_table(19, $v_items->supplier_id);
                if (!empty($custom_form_table)) {
                    foreach ($custom_form_table as $c_label => $v_fields) {
                        $sub_array[] = $v_fields;
                    }
                }
                if (!empty($edited)) {
                    $action .= btn_edit('admin/supplier/create_supplier/' . $v_items->supplier_id) . ' ';
                }
                if (!empty($deleted)) {
                    $action .= ajax_anchor(base_url("admin/supplier/delete_supplier/$v_items->supplier_id"), '', array("class" => "", "title" => lang('delete'), "data-fade-out-on-success" => "#table_" . $_key)) . ' ';
                }
                $sub_array[] = $action;
                $data[] = $sub_array;
            }
            render_table($data);
        } else {
            redirect('admin/dashboard');
        }
    }

    public function new_supplier()
    {
        $data['title'] = lang('new') . ' ' . lang('supplier');
        $data['permission_user'] = $this->common_model->all_permission_user('151');
        $data['subview'] = $this->load->view('admin/supplier/new_supplier', $data, FALSE);
    }

    public function create_supplier($id = NULL)
    {
        $data['title'] = lang('all') . ' ' . lang('supplier');
        if (!empty($id) && is_numeric($id)) {
            $edited = can_action('151', 'edited');
            if (!empty($edited)) {
                $data['supplier_info'] = $this->common_model->check_by(array('supplier_id' => $id), 'tbl_suppliers');
            }
        }
        $data['active'] = 2;
        $data['permission_user'] = $this->common_model->all_permission_user('151');
        $data['subview'] = $this->load->view('admin/supplier/create_supplier', $data, TRUE);
        $this->load->view('admin/_layout_main', $data); //page load
    }

    public function saved_supplier($id = NULL)
    {
        $created = can_action('151', 'created');
        $edited = can_action('151', 'edited');
        if (!empty($created) && !empty($edited)) {

            if (!empty($id) && $id == 'inline') {
                $id = null;
                $inline = true;
            }
            $this->common_model->_table_name = 'tbl_suppliers';
            $this->common_model->_primary_key = 'supplier_id';

            $data = $this->common_model->array_from_post(array('name', 'mobile', 'phone', 'email', 'address', 'vat'));
            // update root category
            $where = array('name' => $data['name'], 'email' => $data['email']);
            // duplicate value check in DB
            if (!empty($id)) { // if id exist in db update data
                $supplier_id = array('supplier_id !=' => $id);
            } else { // if id is not exist then set id as null
                $supplier_id = null;
            }
            // check whether this input data already exist or not
            $check_items = $this->common_model->check_update('tbl_suppliers', $where, $supplier_id);
            if (!empty($check_items)) { // if input data already exist show error alert
                // massage for user
                $type = 'error';
                $msg = "<strong style='color:#000'>" . $data['name'] . '</strong>  ' . lang('already_exist');
            } else { // save and update query
                $permission = $this->input->post('permission', true);
                if (!empty($permission)) {
                    if ($permission == 'everyone') {
                        $assigned = 'all';
                    } else {
                        $assigned_to = $this->common_model->array_from_post(array('assigned_to'));
                        if (!empty($assigned_to['assigned_to'])) {
                            foreach ($assigned_to['assigned_to'] as $assign_user) {
                                $assigned[$assign_user] = $this->input->post('action_' . $assign_user, true);
                            }
                        }
                    }
                    if (!empty($assigned)) {
                        if ($assigned != 'all') {
                            $assigned = json_encode($assigned);
                        }
                    } else {
                        $assigned = 'all';
                    }
                    $data['permission'] = $assigned;
                } else {
                    set_message('error', lang('assigned_to') . ' Field is required');
                    if (empty($_SERVER['HTTP_REFERER'])) {
                        redirect('admin/supplier');
                    } else {
                        redirect($_SERVER['HTTP_REFERER']);
                    }
                }
                $return_id = $this->common_model->save($data, $id);

                save_custom_field(19, $id);

                if (!empty($id)) {
                    $id = $id;
                    $action = 'update_supplier';
                    $msg = lang('update_supplier');
                } else {
                    $id = $return_id;
                    $action = 'save_supplier';
                    $msg = lang('save_supplier');
                }
                $activity = array(
                    'user' => $this->session->userdata('user_id'),
                    'module' => 'supplier',
                    'module_field_id' => $id,
                    'activity' => $action,
                    'icon' => 'fa-circle-o',
                    'value1' => $data['name']
                );
                $this->common_model->_table_name = 'tbl_activities';
                $this->common_model->_primary_key = 'activities_id';
                $this->common_model->save($activity);
                // messages for user
                $type = "success";
            }
            if (!empty($inline)) {
                if (!empty($return_id)) {
                    $result = array(
                        'id' => $id,
                        'name' => $data['name'],
                        'status' => $type,
                        'message' => $msg,
                    );
                } else {
                    $result = array(
                        'status' => $type,
                        'message' => $msg,
                    );
                }
                echo json_encode($result);
                exit();
            } else {
                $message = $msg;
                set_message($type, $message);
            }
        }
        redirect('admin/supplier');
    }

    public function delete_supplier($id)
    {
        $supplier_info = $this->common_model->check_by(array('supplier_id' => $id), 'tbl_suppliers');
        $activity = array(
            'user' => $this->session->userdata('user_id'),
            'module' => 'items',
            'module_field_id' => $id,
            'activity' => 'supplier_deleted',
            'icon' => 'fa-circle-o',
            'value1' => $supplier_info->name
        );
        $this->common_model->_table_name = 'tbl_activities';
        $this->common_model->_primary_key = 'activities_id';
        $this->common_model->save($activity);

        $this->common_model->_table_name = 'tbl_suppliers';
        $this->common_model->_primary_key = 'supplier_id';
        $this->common_model->delete($id);
        $type = 'success';
        $message = lang('supplier_deleted');
        echo json_encode(array("status" => $type, 'message' => $message));
        exit();
    }

    public function supplier_details($id = NULL)
    {
        $data['title'] = lang('supplier') . ' ' . lang('details');
        if (!empty($id)) {
            $data['supplier_info'] = $this->common_model->check_by(array('supplier_id' => $id), 'tbl_suppliers');
        }
        if (!empty($data['supplier_info'])) {
            $supplier_id = $data['supplier_info']->supplier_id;
            $data['currency'] = $this->common_model->check_by(array('code' => config_item('default_currency')), 'tbl_currencies');
            $history_per_page = 8;
            $active_tab = trim((string) $this->input->get('tab', true));
            if (!in_array($active_tab, array('overview', 'purchases', 'returns'), true)) {
                $active_tab = 'overview';
            }
            $purchase_page = (int) $this->input->get('purchase_page', true);
            $return_page = (int) $this->input->get('return_page', true);
            if ($purchase_page < 1) {
                $purchase_page = 1;
            }
            if ($return_page < 1) {
                $return_page = 1;
            }

            $data['purchases'] = $this->db->where('supplier_id', $supplier_id)
                ->order_by('purchase_id', 'desc')
                ->limit(6)
                ->get('tbl_purchases')
                ->result();

            $data['purchase_payments'] = $this->db->select('tbl_purchase_payments.*, tbl_purchases.reference_no, tbl_purchases.purchase_id')
                ->from('tbl_purchase_payments')
                ->join('tbl_purchases', 'tbl_purchases.purchase_id = tbl_purchase_payments.purchase_id', 'left')
                ->where('tbl_purchases.supplier_id', $supplier_id)
                ->order_by('tbl_purchase_payments.payment_date', 'desc')
                ->limit(6)
                ->get()
                ->result();

            $data['return_stocks'] = $this->db->where(array('module' => 'supplier', 'module_id' => $supplier_id))
                ->order_by('return_stock_id', 'desc')
                ->limit(6)
                ->get('tbl_return_stock')
                ->result();

            $data['return_stock_payments'] = $this->db->select('tbl_return_stock_payments.*, tbl_return_stock.reference_no, tbl_return_stock.return_stock_id')
                ->from('tbl_return_stock_payments')
                ->join('tbl_return_stock', 'tbl_return_stock.return_stock_id = tbl_return_stock_payments.return_stock_id', 'left')
                ->where('tbl_return_stock.module', 'supplier')
                ->where('tbl_return_stock.module_id', $supplier_id)
                ->order_by('tbl_return_stock_payments.payment_date', 'desc')
                ->limit(6)
                ->get()
                ->result();

            $data['supplier_purchase_count'] = $this->db->where('supplier_id', $supplier_id)->count_all_results('tbl_purchases');
            $data['supplier_return_count'] = $this->db->where(array('module' => 'supplier', 'module_id' => $supplier_id))->count_all_results('tbl_return_stock');
            $purchase_pages = $data['supplier_purchase_count'] > 0 ? (int) ceil($data['supplier_purchase_count'] / $history_per_page) : 1;
            $return_pages = $data['supplier_return_count'] > 0 ? (int) ceil($data['supplier_return_count'] / $history_per_page) : 1;
            if ($purchase_page > $purchase_pages) {
                $purchase_page = $purchase_pages;
            }
            if ($return_page > $return_pages) {
                $return_page = $return_pages;
            }
            $data['purchase_history_page'] = $purchase_page;
            $data['purchase_history_pages'] = $purchase_pages;
            $data['purchase_history'] = $this->db->where('supplier_id', $supplier_id)
                ->order_by('purchase_id', 'desc')
                ->limit($history_per_page, ($purchase_page - 1) * $history_per_page)
                ->get('tbl_purchases')
                ->result();
            $data['return_history_page'] = $return_page;
            $data['return_history_pages'] = $return_pages;
            $data['return_history'] = $this->db->where(array('module' => 'supplier', 'module_id' => $supplier_id))
                ->order_by('return_stock_id', 'desc')
                ->limit($history_per_page, ($return_page - 1) * $history_per_page)
                ->get('tbl_return_stock')
                ->result();
            $data['supplier_active_tab'] = $active_tab;
            $data['supplier_paid_total'] = $this->db->select_sum('tbl_purchase_payments.amount', 'total')
                ->from('tbl_purchase_payments')
                ->join('tbl_purchases', 'tbl_purchases.purchase_id = tbl_purchase_payments.purchase_id', 'left')
                ->where('tbl_purchases.supplier_id', $supplier_id)
                ->get()
                ->row()
                ->total;

            $purchase_ids = $this->db->select('purchase_id')->where('supplier_id', $supplier_id)->get('tbl_purchases')->result();
            $total_amount = 0;
            $total_due = 0;
            if (!empty($purchase_ids)) {
                foreach ($purchase_ids as $purchase_row) {
                    $total_amount += (float) $this->purchase_model->get_purchase_total_amount($purchase_row->purchase_id);
                    $total_due += (float) $this->purchase_model->get_purchase_due_amount($purchase_row->purchase_id);
                }
            }
            $data['supplier_total_amount'] = $total_amount;
            $data['supplier_total_due'] = $total_due;
            $data['page_title'] = !empty($data['supplier_info']->name) ? $data['supplier_info']->name : (lang('supplier') . ' ' . lang('details'));
            $data['page_description'] = (!empty($data['supplier_info']->email) ? $data['supplier_info']->email : lang('no_email')) . ' . ' . (!empty($data['supplier_info']->phone) ? $data['supplier_info']->phone : lang('no_phone'));
            $data['header_badge'] = array(
                'label' => 'SUP-' . str_pad((string) $supplier_id, 4, '0', STR_PAD_LEFT),
                'tone' => 'primary',
            );
            $data['header_actions'] = array(
                array(
                    'label' => lang('new') . ' ' . lang('purchase'),
                    'icon' => 'plus',
                    'style' => 'primary',
                    'href' => base_url('admin/purchase/new_purchase?module=supplier&module_id=' . $supplier_id),
                ),
				array(
					'label' => lang('new') . ' ' . lang('return'),
					'icon' => 'corner-up-left',
					'style' => 'danger',
					'href' => base_url('admin/return_stock/create_returnstock?module=supplier&module_id=' . $supplier_id),
				),
            );
            if (!empty(can_action('151', 'edited'))) {
                $data['header_actions'][] = array(
                    'label' => lang('edit'),
                    'icon' => 'pencil',
                    'href' => base_url('admin/supplier/create_supplier/' . $supplier_id),
					'style' => 'info',
                );
            }
            $data['header_filters'] = array();
        }
        $data['subview'] = $this->load->view('admin/supplier/supplier_details', $data, true);
        $this->load->view('admin/_layout_main', $data); //page load
    }
}
