<?php

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

/* * *****************Purchase.php**********************************
 * @product name    : Hospital Management System
 * @type            : Class
 * @class name      : Purchase
 * @description     : Manage purchase medicine company.
 * @author          : South Bangla IT Zone Team
 * @url             : http://hms.sbitzone.com
 * @support         : rabibd.it@gmail.com
 * @copyright       : South Bangla IT Zone Team
 * ********************************************************** */

class Purchase extends MY_Controller {

    public $data = array();

    function __construct() {
        parent::__construct();
        $this->load->model('Purchase_Model', 'purchase', true);
    }

    /*****************Function index**********************************
     * @type            : Function
     * @function name   : index
     * @description     : Load "Purchase List" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */
    public function index() {

        check_permission(VIEW);

        if ($_GET && $this->input->get('date')) {
            $keyword = trim($this->input->get('keyword'));
            $payment_type = $this->input->get('payment_type');
            $date = $this->input->get('date');
            $exp = explode('-', $date);
            $form_date = date('Y-m-d', strtotime($exp[0]));
            $to_date = date('Y-m-d', strtotime($exp[1]));
            $manufacturer_id = $this->input->get('manufacturer_id');
            $created_by = $this->input->get('created_by');

            $config = array();
            $config = get_pagination(ADMIN_PER_PAGE);
            $config['base_url'] = site_url('pharmacy/purchase/?keyword=' . $keyword . '&payment_type=' . $payment_type . '&date=' . $date . '&manufacturer_id=' . $manufacturer_id . '&created_by=' . $created_by);
            if ($this->input->get('page')) {
                $sgm = (int) trim($this->input->get('page'));
                $offset = $config['per_page'] * ($sgm - 1);
            } else {
                $offset = 0;
            }

            $config['total_rows'] = $this->purchase->get_purchase_invoice_list($config['per_page'], $offset, $keyword, $payment_type, $form_date, $to_date, $manufacturer_id, $created_by, $count = TRUE);
            $this->pagination->initialize($config);
            $this->data['purchases'] = $this->purchase->get_purchase_invoice_list($config['per_page'], $offset, $keyword, $payment_type, $form_date, $to_date, $manufacturer_id, $created_by, $count = FALSE);
            $this->data['sl_count'] = ($this->input->get('page') == 0 ? 1 : (($this->input->get('page') - 1) * $config["per_page"] + 1));
            $this->data['keyword'] = $keyword;
            $this->data['payment_type'] = $payment_type;
            $this->data['date'] = $date;
            $this->data['manufacturer_id'] = $manufacturer_id;
            $this->data['created_by'] = $created_by;
        } else {
            $config = array();
            $config = get_pagination(ADMIN_PER_PAGE);
            $config['base_url'] = current_url();
            if ($this->input->get('page')) {
                $sgm = (int) trim($this->input->get('page'));
                $offset = $config['per_page'] * ($sgm - 1);
            } else {
                $offset = 0;
            }

            $config['total_rows'] = $this->purchase->get_purchase_invoice_list($config['per_page'], $offset, null, null, date('Y-m-d'), date('Y-m-d'), null, null, $count = TRUE);
            $this->pagination->initialize($config);
            $this->data['purchases'] = $this->purchase->get_purchase_invoice_list($config['per_page'], $offset, null, null, date('Y-m-d'), date('Y-m-d'), null, null, $count = FALSE);
            $this->data['sl_count'] = ($this->input->get('page') == 0 ? 1 : (($this->input->get('page') - 1) * $config["per_page"] + 1));
        }

        $this->data['manufacturers'] = $this->purchase->get_list('manufacturers', array('status' => 1), '', '', '', 'id', 'ASC');
        $this->data['employees'] = $this->purchase->get_employee_list();
        $this->data['list'] = TRUE;
        $this->layout->title($this->lang->line('manage_purchase') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('purchase/index', $this->data);
    }


    /*****************Function searchMedicine**********************************
     * @type            : Function
     * @function name   : searchMedicine
     * @description     : Load "Medicine List" user interface
     * @param           : null
     * @return          : null
     * ********************************************************** */
    public function searchMedicine() {
        $search = $this->purchase->get_medicine_search_list($this->input->post('manufacturer_id'), $this->input->post('medicine_name'));
        if (!empty($search)) {
            foreach ($search as $value) {
                $json_product[] = array(
                    'label' => $value->medicine_name,
                    'value' => $value->id,
                    'purchase_price' => $value->purchase_price,
                    'sell_price' => $value->sell_price,
                    'whole_sale_price' => $value->whole_sale_price
                );
            }
        } else {
            $json_product[] = 'No Medicine Found';
        }
        echo json_encode($json_product);
    }

    /*****************Function add**********************************
     * @type            : Function
     * @function name   : add
     * @description     : Load "Add new Purchase" user interface
     *                    and process to store "purchases" into database
     * @param           : null
     * @return          : null
     * ********************************************************** */
    public function add() {

        check_permission(ADD);

        if ($_POST) {

            $data['custom_invoice_id'] = get_custom_id('medicine_purchases', 'INV-', date('Y'), date('m'));
            $data['invoice_type'] = 'purchase';
            $data['manufacturer_id'] = $this->input->post('manufacturer_id');
            $data['purchase_date'] = date('Y-m-d H:i:s', strtotime($this->input->post('purchase_date')));
            $data['invoice_no'] = $this->input->post('invoice_no');
            $data['payment_type'] = $this->input->post('payment_type');
            $data['total_bill'] = $this->input->post('grand_total');
            $data['discount'] = $this->input->post('discount');
            $data['net_payable'] = $this->input->post('net_payable');
            $data['advanced'] = $this->input->post('advanced');
            $data['due_amount'] = $this->input->post('due_amount');
            $data['paid_status'] = 'unpaid';
            if ($data['due_amount'] <= 0) {
                $data['paid_status'] = 'paid';
            }
            $data['payment_status'] = 'complete';
            $data['note'] = $this->input->post('note');
            $data['status'] = 1;
            $data['created_at'] = date('Y-m-d H:i:s');
            $data['created_by'] = logged_in_user_id();

            $this->db->trans_start();
            $insert_id = $this->purchase->insert('medicine_purchases', $data);

            // Insert Medicine Purchase Details
            $medicine_id = $this->input->post('medicine_id');
            $batch_no = $this->input->post('batch_no');
            $expiry_date = $this->input->post('expiry_date');
            $quantity = $this->input->post('quantity');
            $purchase = $this->input->post('purchase');
            $sale = $this->input->post('sale');
            $wholesale = $this->input->post('wholesale');


            for ($i = 0, $n = count($medicine_id); $i < $n; $i++) {
                $medicinedata['purchase_id'] = $insert_id;
                $medicinedata['medicine_id'] = $medicine_id[$i];
                $medicinedata['batch_no'] = $batch_no[$i];
                $medicinedata['expiry_date'] = $expiry_date[$i];
                $medicinedata['quantity'] = $quantity[$i];
                $medicinedata['purchase'] = $purchase[$i];
                $medicinedata['sale'] = $sale[$i];
                $medicinedata['wholesale'] = $wholesale[$i];
                $medicinedata['total'] = ($medicinedata['purchase'] * $medicinedata['quantity']);
                $medicinedata['discount'] = 0;
                $medicinedata['total_discount'] = 0;

                $medicinedata['status'] = 1;
                $medicinedata['created_at'] = date('Y-m-d H:i:s');
                $medicinedata['created_by'] = logged_in_user_id();

                $this->purchase->insert('medicine_purchase_details', $medicinedata);
            }
            // Medicine Payment Data
            $paymentdata['invoice_id'] = $insert_id;
            $paymentdata['collection_type'] = '1';
            $paymentdata['payment_date'] = date('Y-m-d H:i:s', strtotime($this->input->post('purchase_date')));
            $paymentdata['amount'] = $this->input->post('advanced') ? $this->input->post('advanced') : '0.00';
            $paymentdata['status'] = 1;
            $paymentdata['created_at'] = date('Y-m-d H:i:s');
            $paymentdata['created_by'] = logged_in_user_id();
            $this->purchase->insert('medicine_purchase_payments', $paymentdata);
            $this->db->trans_complete();

            if ($insert_id) {
                create_log('Has been created a medicine purchase : ' . $insert_id);
                success($this->lang->line('insert_success'));
                redirect('pharmacy/purchase');
            } else {
                error($this->lang->line('insert_failed'));
                redirect('pharmacy/purchase/add');
            }
        }

        $this->data['manufacturers'] = $this->purchase->get_list('manufacturers', array('status' => 1));
        $this->data['add'] = TRUE;
        $this->layout->title($this->lang->line('add') . ' ' . $this->lang->line('purchase') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('purchase/add', $this->data);
    }


    /*****************Function edit**********************************
     * @type            : Function
     * @function name   : edit
     * @description     : Load "Edit new purchase" user interface
     *                    and process to store "medicine_purchases" into database
     * @param           : null
     * @return          : null
     * ********************************************************** */
    public function edit($id = NULL) {

        check_permission(EDIT);

        if ($_POST) {

            $data['purchase_date'] = date('Y-m-d H:i:s', strtotime($this->input->post('purchase_date')));
            $data['invoice_no'] = $this->input->post('invoice_no');
            $data['payment_type'] = $this->input->post('payment_type');
            $data['total_bill'] = $this->input->post('grand_total');
            $data['discount'] = $this->input->post('discount');
            $data['net_payable'] = $this->input->post('net_payable');
            $data['advanced'] = $this->input->post('advanced');
            $data['due_amount'] = $this->input->post('due_amount');
            $data['paid_status'] = 'unpaid';
            if ($data['due_amount'] <= 0) {
                $data['paid_status'] = 'paid';
            }
            $data['note'] = $this->input->post('note');
            $data['modified_at'] = date('Y-m-d H:i:s');
            $data['modified_by'] = logged_in_user_id();

            $this->db->trans_start();
            $updated_id = $this->purchase->update('medicine_purchases', $data, array('id' => $this->input->post('invoice_id')));

            // Insert Medicine Purchase Details
            $medicine_id = $this->input->post('medicine_id');
            $batch_no = $this->input->post('batch_no');
            $expiry_date = $this->input->post('expiry_date');
            $quantity = $this->input->post('quantity');
            $purchase = $this->input->post('purchase');
            $sale = $this->input->post('sale');
            $wholesale = $this->input->post('wholesale');

            for ($i = 0, $n = count($medicine_id); $i < $n; $i++) {
                $medicinedata['purchase_id'] = $this->input->post('invoice_id');
                $medicinedata['medicine_id'] = $medicine_id[$i];
                $medicinedata['batch_no'] = $batch_no[$i];
                $medicinedata['expiry_date'] = $expiry_date[$i];
                $medicinedata['quantity'] = $quantity[$i];
                $medicinedata['purchase'] = $purchase[$i];
                $medicinedata['sale'] = $sale[$i];
                $medicinedata['wholesale'] = $wholesale[$i];
                $medicinedata['total'] = ($medicinedata['purchase'] * $medicinedata['quantity']);
                $medicinedata['discount'] = 0;
                $medicinedata['total_discount'] = 0;

                $medicine = $this->purchase->get_single('medicine_purchase_details', array('purchase_id' => $medicinedata['purchase_id'], 'medicine_id' => $medicinedata['medicine_id']));

                if ($medicine) {
                    $medicinedata['modified_at'] = date('Y-m-d H:i:s');
                    $medicinedata['modified_by'] = logged_in_user_id();
                    $this->purchase->update('medicine_purchase_details', $medicinedata, array('purchase_id' => $medicinedata['purchase_id'], 'medicine_id' => $medicinedata['medicine_id']));
                } else {
                    $medicinedata['status'] = 1;
                    $medicinedata['created_at'] = date('Y-m-d H:i:s');
                    $medicinedata['created_by'] = logged_in_user_id();
                    $this->purchase->insert('medicine_purchase_details', $medicinedata);
                }
            }
            // Medicine Payment Data
            $this->purchase->delete('medicine_purchase_payments', array('invoice_id ' => $this->input->post('invoice_id')));

            $paymentdata['invoice_id'] = $this->input->post('invoice_id');
            $paymentdata['collection_type'] = '1';
            $paymentdata['payment_date'] = date('Y-m-d H:i:s', strtotime($this->input->post('purchase_date')));
            $paymentdata['amount'] = $this->input->post('advanced') ? $this->input->post('advanced') : '0.00';
            $paymentdata['status'] = 1;
            $paymentdata['created_at'] = date('Y-m-d H:i:s');
            $paymentdata['created_by'] = logged_in_user_id();
            $this->purchase->insert('medicine_purchase_payments', $paymentdata);
            $this->db->trans_complete();

            if ($updated_id) {
                create_log('Has been updated a medicine purchase : ' . $this->input->post('invoice_id'));
                success($this->lang->line('update_success'));
                redirect('pharmacy/purchase');
            } else {
                error($this->lang->line('update_failed'));
                redirect('pharmacy/purchase/edit/' . $id);
            }
        }

        $this->data['invoice'] = $this->purchase->get_single('medicine_purchases', array('id' => $id));
        $this->data['purchases'] = $this->purchase->get_medicine_purchase_list($id);
        $this->data['manufacturers'] = $this->purchase->get_list('manufacturers', array('status' => 1));
        $this->data['edit'] = TRUE;
        $this->layout->title($this->lang->line('edit') . ' ' . $this->lang->line('purchase') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('pharmacy/purchase/edit', $this->data);
    }

    /*****************Function invoice**********************************
     * @type            : Function
     * @function name   : invoice
     * @description     : Load "Purchase Invoice List" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */

    public function invoice() {

        check_permission(VIEW);

        $this->data['invoice'] = $this->purchase->get_single('medicine_purchases', array('id' => $this->uri->segment(4, 0)));
        $this->data['employee'] = $this->purchase->get_single('employees', array('user_id' => $this->data['invoice']->created_by));
        $this->data['manufacturer'] = $this->purchase->get_single('manufacturers', array('id' => $this->data['invoice']->manufacturer_id));
        $this->data['details'] = $this->purchase->get_medicine_purchase_list($this->uri->segment(4, 0));

        $this->data['list'] = TRUE;
        $this->layout->title($this->lang->line('purchase') . ' ' . $this->lang->line('invoice') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('purchase/invoice', $this->data);
    }

    /*****************Function print**********************************
     * @type            : Function
     * @function name   : print
     * @description     : Load "Purchase Invoice Print" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */

    public function print() {

        check_permission(VIEW);

        $this->load->library('Numbertowords');
        $this->data['invoice'] = $this->purchase->get_single('medicine_purchases', array('id' => $this->input->post('id')));
        $this->data['employee'] = $this->purchase->get_single('employees', array('user_id' => $this->data['invoice']->created_by));
        $this->data['manufacturer'] = $this->purchase->get_single('manufacturers', array('id' => $this->data['invoice']->manufacturer_id));
        $this->data['details'] = $this->purchase->get_medicine_purchase_list($this->input->post('id'));
        $this->load->view('pharmacy/purchase/print', $this->data);
    }

    /*****************Function history**********************************
     * @type            : Function
     * @function name   : history
     * @description     : Load "Purchase payment History List" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */

    public function history() {

        check_permission(VIEW);

        $this->data['invoice'] = $this->purchase->get_single('medicine_purchases', array('id' => $this->uri->segment(4, 0)));
        $this->data['manufacturer'] = $this->purchase->get_single('manufacturers', array('id' => $this->data['invoice']->manufacturer_id));
        $this->data['payments'] = $this->purchase->get_medicine_purchase_payment_list($this->uri->segment(4, 0));

        $this->data['list'] = TRUE;
        $this->layout->title($this->lang->line('purchase') . ' ' . $this->lang->line('history') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('purchase/history', $this->data);
    }


    /*****************Function get_payment_data**********************************
     * @type            : Function
     * @function name   : get_payment_data
     * @description     : Load "Payment Amount" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */

    public function get_payment_data() {
        $invoice = $this->purchase->get_single('medicine_purchases', array('id' => $this->uri->segment(4, 0)));
        $amount = array('amount' => $invoice->due_amount);
        echo json_encode($amount);
    }

    /*****************Function add_payment**********************************
     * @type            : Function
     * @function name   : add_payment
     * @description     : Load "Payment Amount" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */
    public function add_payment() {

        check_permission(ADD);

        if ($_POST) {
            $data['invoice_id'] = $this->input->post('invoice_id');
            $data['collection_type'] = '2';
            $data['payment_date'] = $this->input->post('date') ? date('Y-m-d H:i:s', strtotime($this->input->post('date'))) : NULL;
            $data['amount'] = $this->input->post('amount');
            $data['second_less'] = $this->input->post('second_less');
            $data['note'] = $this->input->post('note');

            if ($this->input->post('amount') > 0) {
                $due = $this->purchase->get_single('medicine_purchases', array('id' => $data['invoice_id']));
                if ($data['second_less'] > 0) {
                    $data_payment['net_payable'] =   $due->net_payable - $data['second_less'];
                }
                $data_payment['due_amount'] =   $due->due_amount - ($data['amount'] + $data['second_less']);
                $data_payment['advanced'] =   $due->advanced + $data['amount'];
                $data_payment['discount'] =   $due->discount + $data['second_less'];

                if ($data_payment['due_amount'] <= 0) {
                    $data_payment['paid_status'] = 'paid'; //
                }
                $this->purchase->update('medicine_purchases', $data_payment, array('id' =>  $data['invoice_id']));
            }

            $data['status'] = 1;
            $data['created_at'] = date('Y-m-d H:i:s');
            $data['created_by'] = logged_in_user_id();

            $this->purchase->insert('medicine_purchase_payments', $data);
            create_log('Has been created a payment : ' . $data['invoice_id']);
            $array = array('status' => 'success', 'error' => '', 'message' => $this->lang->line('insert_success'));
        } else {
            $msg = array(
                'amount' => form_error('amount'),
            );
            $array = array('status' => 'failed', 'error' => $msg, 'message' => '');
        }
        echo json_encode($array);
    }

    /*****************Function getInvoiceId**********************************
     * @type            : Function
     * @function name   : getInvoiceId
     * @description     : Load "Payment Amount" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */

    public function getInvoiceId() {
        $invoice = $this->purchase->get_single('medicine_purchases', array('id' => $this->uri->segment(4, 0)));
        echo json_encode($invoice);
    }

    /*****************Function payment_status**********************************
     * @type            : Function
     * @function name   : payment_status
     * @description     : Load "payment_status" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */

    public function payment_status() {

        check_permission(ADD);

        if ($_POST) {
            $this->load->library('form_validation');
            $this->form_validation->set_error_delimiters('<div class="error-message" style="color: red;">', '</div>');
            $this->form_validation->set_rules('payment_status', $this->lang->line('payment') . ' ' . $this->lang->line('status'), 'trim|required');

            if ($this->form_validation->run() === TRUE) {
                $data['payment_status'] = $this->input->post('payment_status');
                $data['note'] = $this->input->post('note');
                $data['modified_at'] = date('Y-m-d H:i:s');
                $data['modified_by'] = logged_in_user_id();

                $updated_id = $this->purchase->update('medicine_purchases', $data, array('id' => $this->input->post('invoice_id')));
                if ($updated_id) {
                    create_log('Has been update a medicine purchase invoice : ' . $this->input->post('invoice_id'));
                }
                $array = array('status' => 'success', 'message' => $this->lang->line('update_success'));
            } else {
                $this->data = $_POST;
                $msg = array(
                    'payment_status' => form_error('payment_status')
                );
                $array = array('status' => 'failed', 'error' => $msg);
            }
            echo json_encode($array);
        }
    }

    /*****************Function delete**********************************
     * @type            : Function
     * @function name   : delete
     * @description     : delete "Purchase" data from database
     *
     * @param           : $id integer value
     * @return          : null
     * ********************************************************** */
    public function delete($id = null) {

        check_permission(DELETE);

        if (!is_numeric($id)) {
            error($this->lang->line('unexpected_error'));
            redirect('pharmacy/purchase');
        }

        $purchase = $this->purchase->get_single('medicine_purchases', array('id' => $id));

        if ($this->purchase->delete('medicine_purchases', array('id' => $id))) {
            $this->purchase->delete('medicine_purchase_details', array('purchase_id' => $purchase->id));
            $this->purchase->delete('medicine_purchase_payments', array('invoice_id ' => $purchase->id));
            create_log('Has been deleted a medicine purchase : ' . $purchase->custom_invoice_id);
            success($this->lang->line('delete_success'));
        } else {
            error($this->lang->line('delete_failed'));
        }
        redirect($_SERVER['HTTP_REFERER']);
    }
}
