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

class invoices extends Admin_Controller
{

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

    public function index()
    {
        $where = $join = $limit = "";

        if (isset($_POST['firstPayDate']) && $_POST['firstPayDate'] != '') $where .= " AND `customer_invoices`.`invoice_date` >= '" . date('Y-m-d', strtotime(str_replace('/', '-', $_POST['firstPayDate']))) . " 00:00:00'";
        if (isset($_POST['firstPayToDate']) && $_POST['firstPayToDate'] != '') $where .= " AND `customer_invoices`.`invoice_date` <= '" . date('Y-m-d', strtotime(str_replace('/', '-', $_POST['firstPayToDate']))) . " 23:59:99'";

        // if (isset($_POST['invoice_types'])) {
        //     $ids = implode(',', $_POST['invoice_types']);
        //     $where .= " AND `customer_invoices`.`invoice_type` IN (" . $ids . ")";
        // }

        if (isset($_POST['customerId'])) {
            $ids = implode(',', $_POST['customerId']);
            $where .= " AND `customer_invoices`.`customerId` IN (" . $ids . ")";
        }


        if (empty($where)) {
            $invoices       = $this->db->query("SELECT * FROM `customer_invoices` WHERE `invoice_type`=2  ORDER BY `invoice_id` DESC ")->result();
        } else {
            $invoices       = $this->db->query("SELECT * FROM `customer_invoices` WHERE `invoice_type`=2  $where")->result();
        }

        $balance    = 0;
        $type_count = array(
            1 => 0,
            2 => 0,
            3 => 0,
            4 => 0
        );
        $part_count = array(
            0 => 0,
            1 => 0,
            2 => 0,
            3 => 0
        );
        foreach ($invoices as $invoice) {
            $balance += $invoice->total;
            $type_count[$invoice->invoice_type] = $type_count[$invoice->invoice_type] + 1;
        }

        $customers      = reindex_by_key($this->db->query("SELECT * FROM `customers`")->result(), 'customerId');
        $temp_details   = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_details_temp`")->result(), 'detail_id');
        $warehouse      = reindex_by_key($this->db->query("SELECT * FROM `warehouse`")->result(), 'ID');
        $invoiceId = $this->db->query("SELECT MAX(invoice_id) AS LastID FROM `customer_invoices`")->row();
        $invoiceId =  $invoiceId->LastID + 1;


        $this->template
            ->set('view', 'admin/invoices/index')
            ->set('invoices', $invoices)
            ->set('customers', $customers)
            ->set('temp_details', $temp_details)
            ->set('balance', $balance)
            ->set('type_count', $type_count)
            ->set('part_count', $part_count)
            ->set('warehouse', $warehouse)
            ->set('invoiceId', $invoiceId)
            ->render();
    }

    public function InvSuppliers()
    {
        $where = $join = $limit = "";

        if (isset($_POST['firstPayDate']) && $_POST['firstPayDate'] != '') $where .= " AND `suppliers_invoices`.`invoice_date` >= '" . date('Y-m-d', strtotime(str_replace('/', '-', $_POST['firstPayDate']))) . " 00:00:00'";
        if (isset($_POST['firstPayToDate']) && $_POST['firstPayToDate'] != '') $where .= " AND `suppliers_invoices`.`invoice_date` <= '" . date('Y-m-d', strtotime(str_replace('/', '-', $_POST['firstPayToDate']))) . " 23:59:99'";

        // if (isset($_POST['invoice_types'])) {
        //     $ids = implode(',', $_POST['invoice_types']);
        //     $where .= " AND `suppliers_invoices`.`invoice_type` IN (" . $ids . ")";
        // }

        if (isset($_POST['supplier_id'])) {
            $ids = implode(',', $_POST['supplier_id']);
            $where .= " AND `suppliers_invoices`.`supplier_id` IN (" . $ids . ")";
        }

        if (empty($where)) {
            $invoices       = $this->db->query("SELECT * FROM `suppliers_invoices` ORDER BY `invoice_id` DESC")->result();
        } else {
            $invoices       = $this->db->query("SELECT * FROM `suppliers_invoices` $where")->result();
        }

        $suppliers      = reindex_by_key($this->db->query("SELECT * FROM `suppliers`")->result(), 'supplier_id');
        $accounts       = $this->db->query("SELECT * FROM `accounts` WHERE `is_deleted` = 0")->result();
        $warehouse      = $this->db->query("SELECT * FROM `warehouse`")->result();

        $this->template
            ->set('view', 'admin/invoices/InvSuppliers')
            ->set('invoices', $invoices)
            ->set('suppliers', $suppliers)
            ->set('accounts', $accounts)
            ->set('warehouse', $warehouse)


            ->render();
    }

    public function view()
    {

        $invoice_id = $this->uri->segment(4);

        if (empty($invoice_id) || $invoice_id == FALSE) {
            redirect('admin/invoices/', 'refresh');
        } else {
            $invoice        = $this->db->query("SELECT * FROM `customer_invoices` WHERE `invoice_id` = $invoice_id")->row();
            $invoice_items  = $this->db->query("SELECT * FROM `customer_invoice_items` WHERE `invoice_id` = $invoice_id")->result();
            $customer       = $this->db->query("SELECT * FROM `customers` WHERE `customerId` = $invoice->customerId")->row();
            $payments       = $this->db->query("SELECT * FROM `customer_invoices_payments` WHERE `invoice_id` = $invoice_id")->result();
            $payment_boxes  = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_boxes`")->result(), 'box_id');
            $payment_types  = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_payments_type`")->result(), 'type_id');
            $temp_detail    = $this->db->query("SELECT * FROM `customer_invoices_details_temp` WHERE `detail_id` = '$invoice->detail_id' ")->row();
        }

        $this->template
            ->set('view', 'admin/invoices/view')
            ->set('invoice', $invoice)
            ->set('customer', $customer)
            ->set('payments', $payments)
            ->set('payment_boxes', $payment_boxes)
            ->set('payment_types', $payment_types)
            ->set('invoice_items', $invoice_items)
            ->set('temp_detail', $temp_detail)
            ->render();
    }
    public function viewInvSupplier()
    {

        $invoice_id = $this->uri->segment(4);

        if (empty($invoice_id) || $invoice_id == FALSE) {
            redirect('admin/invoices/', 'refresh');
        } else {
            $invoice        = $this->db->query("SELECT * FROM `suppliers_invoices` WHERE `invoice_id` = $invoice_id")->row();
            $invoice_items  = $this->db->query("SELECT * FROM `suppliers_invoices_items` WHERE `invoice_Id` = $invoice_id")->result();
            $supplier       = $this->db->query("SELECT * FROM `suppliers` WHERE `supplier_id` = $invoice->supplier_id")->row();
            $payments       = $this->db->query("SELECT * FROM `suppliers_payments` WHERE `invoice_id` = $invoice_id")->result();
            $payment_boxes  = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_boxes`")->result(), 'box_id');
            $payment_types  = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_payments_type`")->result(), 'type_id');
        }

        $this->template
            ->set('view', 'admin/invoices/viewInvSupplier')
            ->set('invoice', $invoice)
            ->set('supplier', $supplier)
            ->set('payments', $payments)
            ->set('payment_boxes', $payment_boxes)
            ->set('payment_types', $payment_types)
            ->set('invoice_items', $invoice_items)
            ->render();
    }

    public function viewPayment()
    {

        $payment_id = $this->uri->segment(4);
        // debug($payment_id);
        if (empty($payment_id) || $payment_id == FALSE) {
        } else {
            $payments       = $this->db->query("SELECT * FROM `customer_invoices_payments` WHERE `payment_id` = $payment_id")->row();
           
                $customer           = $this->db->query("SELECT * FROM `customers` WHERE `customerId` = $payments->customerId")->row();
                $payment_boxes      = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_boxes`")->result(), 'box_id');
                $payment_types      = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_payments_type`")->result(), 'type_id');
                $temp_details       = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_details_temp`")->result(), 'detail_id');
                $payed_amount       = $this->db->query("SELECT SUM(total) AS total FROM `customer_invoices_payments_connect` WHERE `payment_id` = '$payment_id'")->row();
                $all_payed_amount   = $this->db->query("SELECT * FROM `customer_invoices_payments_connect` WHERE `payment_id` = '$payment_id'")->result();
          
        }


        $this->template
            ->set('view', 'admin/invoices/viewPayment')
            ->set('customer', $customer)
            ->set('payments', $payments)
            ->set('payment_boxes', $payment_boxes)
            ->set('payment_types', $payment_types)
            ->set('temp_details', $temp_details)
            ->set('payed_amount', $payed_amount)
            ->set('all_payed_amount', $all_payed_amount)
            ->render();
    }

    public function payments()
    {
        $payments       = $this->db->query("SELECT * FROM `customer_invoices_payments` WHERE `type` = 0")->result();
        $customers      = reindex_by_key($this->db->query("SELECT * FROM `customers`")->result(), 'customerId');
        $payment_boxes  = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_boxes`")->result(), 'box_id');
        $payment_types  = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_payments_type`")->result(), 'type_id');
        $temp_details   = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_details_temp`")->result(), 'detail_id');
        $lastPaymentId = $this->db->query("SELECT MAX(payment_id) AS LastID FROM `customer_invoices_payments`")->row();
        $lastPaymentId =  $lastPaymentId->LastID + 1;

        $this->template
            ->set('view', 'admin/invoices/payments')
            ->set('payments', $payments)
            ->set('customers', $customers)
            ->set('payment_boxes', $payment_boxes)
            ->set('payment_types', $payment_types)
            ->set('temp_details', $temp_details)
            ->set('lastPaymentId', $lastPaymentId)
            ->render();
    }

    public function supplierPayments()
    {
        if (isset($_POST['firstPayDate']) && !empty($_POST['firstPayDate']) && isset($_POST['firstPayToDate']) && !empty($_POST['firstPayToDate'])) {
            $date_from  = date('Y-m-d 00:00:00', strtotime(str_replace('/', '-', $_POST['firstPayDate'])));
            $date_to    = date('Y-m-d 23:59:59', strtotime(str_replace('/', '-', $_POST['firstPayToDate'])));
        } else {
            $date_to    = date('Y-m-d 23:59:59', strtotime('now'));
            $date_from  = date('Y-m-d 00:00:00', strtotime('-1 Week'));
        }
        $payments       = $this->db->query("SELECT * FROM `suppliers_payments`")->result();
        $suppliers      = reindex_by_key($this->db->query("SELECT * FROM `suppliers`")->result(), 'supplier_id');
        $payment_boxes  = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_boxes`")->result(), 'box_id');
        $payment_types  = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_payments_type`")->result(), 'type_id');
        $lastSupplierPaymentId = $this->db->query("SELECT MAX(id) AS LastID FROM `suppliers_payments`")->row();
        $lastSupplierPaymentId =  $lastSupplierPaymentId->LastID + 1;
        // debug($payments);

        $this->template
            ->set('view', 'admin/invoices/supplierPayments')
            ->set('payments', $payments)
            ->set('suppliers', $suppliers)
            ->set('payment_boxes', $payment_boxes)
            ->set('payment_types', $payment_types)
            ->set('date_from', $date_from)
            ->set('date_to', $date_to)
            ->set('lastSupplierPaymentId', $lastSupplierPaymentId)
            ->render();
    }

    public function boxes()
    {

        $box_id = $this->uri->segment(4);

        if (empty($box_id) || $box_id == FALSE) {
            redirect('admin/payments/', 'refresh');
        } else {
            if (isset($_POST['from_date']) && !empty($_POST['from_date'])) {
                $date_from = date('Y-m-d 00:00:00', strtotime(str_replace('/', '-', $_POST['from_date'])));
                $date_from_bal = date('Y-m-d 23:59:59', strtotime("-1 DAY", strtotime(str_replace('/', '-', $_POST['from_date']))));
            } else {
                $date_from = date('Y-m-d 00:00:00', strtotime('-3 DAYS'));
                $date_from_bal = date('Y-m-d 23:59:59', strtotime('-4 DAYS'));
            }
            if (isset($_POST['to_date']) && !empty($_POST['to_date'])) {
                $date_to = date('Y-m-d 23:59:59', strtotime(str_replace('/', '-', $_POST['to_date'])));
            } else {
                $date_to = date('Y-m-d 23:59:59', strtotime('now'));
            }
            $box            = $this->general_model->getRowById('customer_invoices_boxes', 'box_id', $box_id);
            $payments       = $this->db->query("SELECT * FROM `customer_invoices_payments` WHERE `payment_box` = $box_id AND `payment_date` BETWEEN '$date_from' AND '$date_to' ORDER BY `payment_date` ASC")->result();
            $balance        = $this->db->query("SELECT SUM(`total`) AS `sTotal` FROM `customer_invoices_payments` WHERE `payment_box` = $box_id AND `payment_date` BETWEEN '1970-01-01 00:00:00' AND '$date_from_bal' ORDER BY `payment_id` ASC")->row();
            $full_balance   = $this->db->query("SELECT SUM(`total`) AS `sTotal` FROM `customer_invoices_payments` WHERE `payment_box` = $box_id ORDER BY `payment_id`")->row();
            $customers      = reindex_by_key($this->db->query("SELECT * FROM `customers`")->result(), 'customerId');
            $payment_types  = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_payments_type`")->result(), 'type_id');
            $payment_boxes  = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_boxes`")->result(), 'box_id');
            $temp_details   = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_details_temp`")->result(), 'detail_id');
            $suppliers      = reindex_by_key($this->db->query("SELECT * FROM `suppliers`")->result(), 'supplier_id');
            $sum = 0;
            foreach ($payments as $p) {
                $sum += $p->total;
            }

            $visa_payment_customers     = array();
            $visa_payment_customersPP   = array();
            $user_box               = $this->db->query("SELECT * FROM `users` WHERE `payment_box` = '$box_id' ")->row();
            if (!empty($user_box)) {
                $allowedSuppliers       = $user_box->allowedSuppliers;
                $visa_payment_customers = array();
                $visa_payment_customersPP   = array();
            }

            $open_requests = array();

            if ($box->category == 'agent') {
                $user = $this->general_model->getRowById('users', 'payment_box', $box_id);
                if (!empty($user)) {
                    $allowedSuppliersPayments = $user->allowedSuppliers == '' ? '' : 'AND customerId IN (' . trim($user->allowedSuppliers, ',') . ')';
                    $open_payments = $this->db->query("SELECT * FROM `customers_payments` WHERE isPaid = 0 $allowedSuppliersPayments")->result();
                } else {
                    $open_payments = array();
                }
            } else {
                $open_payments = array();
            }
        }

        $this->template
            ->set('view', 'admin/invoices/boxes')
            ->set('box_id', $box_id)
            ->set('box', $box)
            ->set('payments', $payments)
            ->set('customers', $customers)
            ->set('payment_types', $payment_types)
            ->set('payment_boxes', $payment_boxes)
            ->set('full_balance', $full_balance)
            ->set('temp_details', $temp_details)
            ->set('date_from', $date_from)
            ->set('date_to', $date_to)
            ->set('balance', $balance)
            ->set('visa_payment_customers', $visa_payment_customers)
            ->set('visa_payment_customersPP', $visa_payment_customersPP)
            ->set('sum', $sum)
            ->set('suppliers', $suppliers)
            ->set('open_requests', $open_requests)
            ->set('open_payments', $open_payments)
            ->render();
    }

    public function viewCustomer()
    {

        $customerId = $this->uri->segment(4);

        if (empty($customerId) || $customerId == FALSE) {
            redirect('admin/finance/', 'refresh');
        } else {
            $payments       = $this->db->query("SELECT * FROM `customer_invoices_payments` WHERE `customerId` = '$customerId' AND `invoice_id` > 0 AND no_need_invoice = 0 ORDER BY `dateCreation` ASC")->result();
            $invoices       = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices` WHERE `customerId` = '$customerId' AND `invoice_key` != '' ORDER BY `dateCreation` ASC")->result(), 'invoice_id');
            $customers      = $this->db->query("SELECT * FROM `customers` WHERE `customerId` = '$customerId' ")->result();
            $payment_types  = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_payments_type`")->result(), 'type_id');
            $payment_boxes  = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_boxes`")->result(), 'box_id');

            foreach ($invoices as $invoice) {
                $payed_amount = $this->db->query("SELECT * FROM `customer_invoices_payments_connect` WHERE `invoice_id` = '$invoice->invoice_id'")->result();
                if (!empty($payed_amounts)) {
                    $payed_sum  = 0;
                    $payments   = array();
                    foreach ($payed_amount as $am) {
                        $payed_sum += $am->total;
                        $payments[] = $am->payment_id;
                    }
                    $invoice->payed_amount      = $payed_sum;
                    $invoice->invoice_balance   = $payed_sum - $invoice->total;
                    $invoice->payment_id        = $payments;
                } else {
                    $payed_amount = $this->general_model->getRowById('customer_invoices_payments', 'invoice_id', $invoice->invoice_id);
                    if (!empty($payed_amount)) {
                        $invoice->payed_amount      = $payed_amount->total;
                        $invoice->invoice_balance   = $payed_amount->total - $invoice->total;
                        $invoice->payment_id        = $payed_amount->payment_id;
                    } else {
                        $invoice->payed_amount      = 0;
                        $invoice->invoice_balance   = $invoice->total * -1;
                        $invoice->payment_id        = 0;
                    }
                }
            }

            $balance            = 0;
            $invoice_balance    = 0;
            foreach ($payments as $payment) {
                $balance += $payment->total;
            }
            foreach ($invoices as $invoice) {
                $invoice_balance += $invoice->total;
            }
            $full_balance = $balance - $invoice_balance;

            $visa_payment_customers = $this->db->query("SELECT * FROM `customer_invoices_payments` WHERE `customerId` = '$customerId' ")->result();
        }

        $this->template
            ->set('view', 'admin/invoices/viewCustomer')
            ->set('customerId', $customerId)
            ->set('payments', $payments)
            ->set('invoices', $invoices)
            ->set('customers', $customers)
            ->set('payment_types', $payment_types)
            ->set('payment_boxes', $payment_boxes)
            ->set('balance', $balance)
            ->set('full_balance', $full_balance)
            ->set('visa_payment_customers', $visa_payment_customers)
            ->render();
    }

    public function paymentType()
    {

        $payment_type = $this->uri->segment(4);

        if (empty($payment_type) || $payment_type == FALSE) {
            redirect('admin/payments/', 'refresh');
        } else {
            $payments       = $this->db->query("SELECT * FROM `customer_invoices_payments` WHERE `payment_type` = $payment_type")->result();
            $customers      = reindex_by_key($this->db->query("SELECT * FROM `customers`")->result(), 'customerId');
            $payment_types  = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_payments_type`")->result(), 'type_id');
            $payment_boxes  = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_boxes`")->result(), 'box_id');
            $temp_details   = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_details_temp`")->result(), 'detail_id');
        }

        $this->template
            ->set('view', 'admin/invoices/paymentType')
            ->set('payment_type', $payment_type)
            ->set('payments', $payments)
            ->set('customers', $customers)
            ->set('payment_types', $payment_types)
            ->set('payment_boxes', $payment_boxes)
            ->set('temp_details', $temp_details)
            ->render();
    }

    public function create()
    {

        $customers      = reindex_by_key($this->db->query("SELECT * FROM `customers`")->result(), 'customerId');
        $payment_types  = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_payments_type`")->result(), 'type_id');
        $payment_boxes  = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_boxes`")->result(), 'box_id');
        $temp_clients   = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_details_temp`")->result(), 'detail_id');
        if ($this->uri->segment(4) !== FALSE) {
            $payment_id     = $this->uri->segment(4);
            $payment        = $this->db->query("SELECT * FROM `customer_invoices_payments` WHERE `payment_id` = $payment_id")->row();
            if ($payment->detail_id > 0) {
                $tempData       = $this->db->query("SELECT * FROM `customer_invoices_details_temp` WHERE `detail_id` = '$payment->detail_id'")->row();
                $customerData    = (object)array(
                    'customerName'  => $tempData->customer_name,
                    'invID'         => $tempData->customer_id_number,
                    'phoneNumber'   => $tempData->customer_phone,
                    'address'       => '',
                    'email'         => $tempData->customer_email,
                    'customerId'    => $tempData->detail_id . $tempData->customer_file_no
                );
            } else {
                $customerData    = $this->db->query("SELECT * FROM `customers` WHERE `customerId` = '$payment->customerId'")->row();
            }
        } else {
            $payment        = '';
            $customerData   = '';
        }


        $this->template
            ->set('view', 'admin/invoices/create')
            ->set('customers', $customers)
            ->set('payment_types', $payment_types)
            ->set('payment_boxes', $payment_boxes)
            ->set('payment', $payment)
            ->set('customerData', $customerData)
            ->set('temp_clients', $temp_clients)
            ->render();
    }

    public function createInvoice()
    {
        $data           = (object)$_POST;
        $apiItems       = array();
        $apiPayments    = array();

        if ($data->invoice_type == 1) {
            $document_type      = 'IR';
            $document_action    = '1';
        };
        if ($data->invoice_type == 2) {
            $document_type      = 'IN';
            $document_action    = '1';
        };
        if ($data->invoice_type == 3) {
            $document_type      = 'IN';
            $document_action    = '3';
        };
        if ($data->invoice_type == 4) {
            $document_type      = 'IR';
            $document_action    = '3';
        };

        if ($data->invoice_for != "temp_customer") {

            if ($document_action == 3) {
                $invoice_total  = ($data->total) * -1;
                $cancel_id      = $data->canceled_document;
            } else {
                $invoice_total  = $data->total;
                $cancel_id      = 0;
            }

            $customer = $this->general_model->getRowById('customers', 'customerId', $data->invoice_for);

            $MainInvoiceData = array(
                'invoice_type'    => $data->invoice_type,
                'total'           => $invoice_total,
                'invoice_date'    => date('Y-m-d H:i:s'),
                'customerId'      => $data->invoice_for,
                'cancel_id'       => $cancel_id,
                'dateCreation'    => date('Y-m-d H:i:s'),
                'lastUpdate'      => date('Y-m-d H:i:s')
            );
            $invoice_id = $this->general_model->insertRow('customer_invoices', $MainInvoiceData);
            if (!empty($invoice_id)) {
                $items      = (object)$data->items;
                $itemsI     = $items->item_description;
                $itemsP     = $items->item_price;
                foreach ($itemsI as $key => $value) {

                    if ($document_action == 3) {
                        $Ptotal = ($itemsP[$key]) * -1;
                    } else {
                        $Ptotal = $itemsP[$key];
                    }

                    $invoiceItemsData = array(
                        'invoice_id'      => $invoice_id,
                        'item_title'      => $value,
                        'item_price'      => $itemsP[$key],
                        'customerId'     => $data->invoice_for,
                        'dateCreation'    => date('Y-m-d H:i:s'),
                        'lastUpdate'      => date('Y-m-d H:i:s')
                    );

                    $item_id = $this->general_model->insertRow('customer_invoice_items', $invoiceItemsData);
                }
                if ($data->invoice_type == 1 || $data->invoice_type == 3) {

                    $payments   = (object)$data->payments;
                    $paymentBox = (object)$payments->payment_box;

                    if ($document_action == 3) {
                        $total_payment = ($items->item_price[$key] * 1.17) * -1;
                    } else {
                        $total_payment = $items->item_price[$key] * 1.17;
                    }

                    foreach ($paymentBox as $key => $value) {

                        $invoicePaymentData = array(
                            'invoice_id'        => $invoice_id,
                            'customerId'       => $data->invoice_for,
                            'payment_type'      => $payments->payment_type[$key],
                            'payment_box'       => $payments->payment_box[$key],
                            'payment_date'      => date('Y-m-d H:i:s', strtotime(str_replace('/', '-', $payments->payment_date[$key]))),
                            'bank_visa'         => $payments->bank_visa[$key],
                            'branch_digits'     => $payments->branch_digits[$key],
                            'account_card'      => $payments->account_card[$key],
                            'reference_id'      => $payments->reference_id[$key],
                            'total'             => $total_payment,
                            'dateCreation'      => date('Y-m-d H:i:s'),
                            'lastUpdate'        => date('Y-m-d H:i:s')
                        );
                        // payment_method : 1=Visa , 3=Check, 4=Transfer, 5=Cash, 6=Paypal
                        if ($payments->payment_type[$key] == 1) {
                            $payment_method = 4;
                        };
                        if ($payments->payment_type[$key] == 2) {
                            $payment_method = 4;
                        };
                        if ($payments->payment_type[$key] == 3) {
                            $payment_method = 5;
                        };
                        if ($payments->payment_type[$key] == 4) {
                            $payment_method = 1;
                        };
                        if ($payments->payment_type[$key] == 5) {
                            $payment_method = 3;
                        };

                        if (!empty($data->payment_id)) {
                            $invoicePaymentData['invoice_id'] =  $invoice_id;
                            $payment_id     = $data->payment_id;
                            $update_payment = $this->general_model->updateRowById('customer_invoices_payments', 'payment_id', $payment_id, $invoicePaymentData);
                        } else {
                            $payment_id = $this->general_model->insertRow('customer_invoices_payments', $invoicePaymentData);
                        }
                    }
                }
                redirect("admin/invoices/view/$invoice_id", 'refresh');
            }
        }
    }

    public function createInv()
    {
        $customers      = reindex_by_key($this->db->query("SELECT * FROM `customers`")->result(), 'customerId');
        $payment_types  = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_payments_type`")->result(), 'type_id');
        $payment_boxes  = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_boxes`")->result(), 'box_id');

        $this->template
            ->set('view', 'admin/invoices/createInv')
            ->set('customers', $customers)
            ->set('payment_types', $payment_types)
            ->set('payment_boxes', $payment_boxes)
            ->render();
    }

    public function createInvoiceOnly()
    {
        $data = (object)$_POST;
        $items     = (object)$data->items;
        $date_invoice = str_replace("/", "-", $data->invoice_date);
        $finall_total = 0;
        if (!empty($items) && isset($items)) {
            $invoice_id =   getCustomerNewInvoiceNo();
            for ($i = 0; $i < count($data->items['description']); $i++) {
                $price           =  $items->price[$i];
                $units           =  $items->unit[$i];
                $total_price     =  $price * $units;
                $finall_total   += $total_price;
                $id =  $items->product_id[$i];
                $item_details = getProductDetails($id);
                $finall_quantity = $item_details->quantity + $items->unit[$i];
                $invoiceItemsData = array(
                    'invoice_id'    => $invoice_id,
                    'customerId'    => $data->invoice_for,
                    'store_id'      => $data->storage,
                    'product_id'   => $items->product_id[$i],
                    'product_code'  => $items->code[$i],
                    'item_price'    => $items->price[$i],
                    'unit'          => $items->unit[$i],
                    'full_price'    => $items->full_price[$i],
                    'invoice_date'  => date("Y-m-d H:i:s", strtotime($date_invoice)),
                    'dateCreation'  => date('Y-m-d H:i:s'),
                    'lastUpdate'    => date('Y-m-d H:i:s')
                );
                $item_id = $this->general_model->insertRow('customer_invoice_items', $invoiceItemsData);
                if ($item_details->type == 1) {
                    $update_row = $this->db->query("SELECT `ID`, `quantity` FROM `warehouse_items` WHERE `warehouse_id` =  $data->storage AND `product_id` = $id ")->row();
                    //    debug($update_row);
                    $finall_quantity = $update_row->quantity - $items->unit[$i];
                    $update_data = array(
                        'quantity'    => $finall_quantity,
                        'update_date' => date('Y-m-d H:i:s')
                    );
                    $item_update = $this->general_model->updateRowById('warehouse_items', 'ID', $update_row->ID, $update_data);
                }
            }
            $MainInvoiceData = array(
                'invoice_type'    => 2,
                'total'           => $data->total,
                'invoice_date'    => date("Y-m-d H:i:s", strtotime($date_invoice)),
                'customerId'      => $data->invoice_for,
                'warehouse_id'    => $data->storage,
                'bossComment'     => $data->boss_Comment,
                'custComment'     => $data->custComment,
                'comment1'        => $data->comment1,
                'comment2'        => $data->comment2,
                'dateCreation'    => date('Y-m-d H:i:s'),
                'lastUpdate'      => date('Y-m-d H:i:s')
            );
            $invoice_id = $this->general_model->insertRow('customer_invoices', $MainInvoiceData);




            redirect("admin/invoices/view/$invoice_id", 'refresh');
        }
        redirect("admin/invoices", 'refresh');
    }

    // ajax functions 
    public function getInvoiceData()
    {
        $id = $_POST['id'];
        if (isset($id) && !empty($id)) {
            $invoice_data['invoice_info'] = $this->db->query("SELECT * FROM `customer_invoices` WHERE `invoice_id` = $id")->row();
            $customerName = getCustomerName($invoice_data['invoice_info']->customerId);
            $warehouseName = getWarehouseById($invoice_data['invoice_info']->warehouse_id);
            $invoice_data['invoice_info']->customerName = $customerName;
            $invoice_data['invoice_info']->warehouseName = $warehouseName;
            $customerId = $invoice_data['invoice_info']->customerId;

            $invoice_data['invoice_info']->invoice_date = date("d/m/Y", strtotime($invoice_data['invoice_info']->invoice_date));
            $customerCredit           = $this->db->query("SELECT `credits` FROM `customers` WHERE `customerId` = '$customerId'")->row();
            if (!empty($customerCredit)) {
                $invoice_data['invoice_info']->customerCredit = $customerCredit->credits;
            }
            $invoice_items = $this->db->query("SELECT * FROM `customer_invoice_items` WHERE `invoice_id` = $id")->result();
            $invoice_data['items'] = $invoice_items;

            foreach ($invoice_items as $item) {
                $item->item_title = getItemNameById($item->product_id);
                $item->code = $item->product_id;
            }


            // debug($invoice_items);

            echo json_encode(array("result" => true, "data" => $invoice_data));
        }
    }

    // ajax functions 
    public function getPaymentData()
    {
        $id = $_POST['id'];
        if (isset($id) && !empty($id)) {
            $payment_data['payment_info'] = $this->db->query("SELECT * FROM `customer_invoices_payments` WHERE `payment_id` = $id")->row();
            $customerName = getCustomerName($payment_data['payment_info']->customerId);
            $payment_data['payment_info']->customerName = $customerName;
            $customerId = $payment_data['payment_info']->customerId;

            $payment_data['payment_info']->payment_date = date("d/m/Y", strtotime($payment_data['payment_info']->payment_date));
            $customerCredit           = $this->db->query("SELECT `credits` FROM `customers` WHERE `customerId` = '$customerId'")->row();
            if (!empty($customerCredit)) {
                $payment_data['payment_info']->customerCredit = $customerCredit->credits;
            }
            $payment_items = $this->db->query("SELECT * FROM `customer_invoices_payments_items` WHERE `payment_id` = $id")->result();
            $payment_data['items'] = $payment_items;

            foreach ($payment_items as $item) {
                $item->item_title = getItemNameById($item->item_id);
                $item->code = $item->item_id;
                $item->payment_box = getPaymentBox($item->payment_box);
                $item->payment_type = getPaymentMethod($item->payment_type);
            }

            // debug($payment_items);

            echo json_encode(array("result" => true, "data" => $payment_data));
        }
    }

    public function getSupplierPaymentData()
    {
        $id = $_POST['id'];
        if (isset($id) && !empty($id)) {
            $payment_data['payment_info'] = $this->db->query("SELECT * FROM `suppliers_payments` WHERE `id` = $id")->row();
            $supplierName = getSupplierName($payment_data['payment_info']->supplier_id);
            $payment_data['payment_info']->customerName = $supplierName;
            $supplier_id = $payment_data['payment_info']->supplier_id;

            $payment_data['payment_info']->payment_date = date("d/m/Y", strtotime($payment_data['payment_info']->dateCreation));
            $supplierCredit           = $this->db->query("SELECT `credit` FROM `suppliers` WHERE `supplier_id` = '$supplier_id'")->row();
            if (!empty($supplierCredit)) {
                $payment_data['payment_info']->supplierCredit = $supplierCredit->credit;
            }
            $payment_items = $this->db->query("SELECT * FROM `supplier_payments_items` WHERE `payment_id` = $id")->result();
            $payment_data['items'] = $payment_items;

            foreach ($payment_items as $item) {
                $item->item_title = getItemNameById($item->id);
                $item->code = $item->id;
                $item->box = getPaymentBox($item->box);
                $item->payment_method = getPaymentMethod($item->payment_method);
            }
            echo json_encode(array("result" => true, "data" => $payment_data));
        }
    }

    public function getInvoiceDate()
    {
        $Date = array();
        $last_Date = 0;
        $lastDate = $this->db->query("SELECT MAX(invoice_date) as last FROM customer_invoices")->row();
        $last_Date =  date("d/m/Y", strtotime($lastDate->last));
        if (!empty($last_Date)) {

            echo json_encode(array("result" => true, "date" => $last_Date));
        } else {
            echo json_encode(array("result" => false, "date" => 0));
        }
    }

    public function getSupplierInvoiceData()
    {
        $id = $_POST['id'];

        if (isset($id) && !empty($id)) {
            $invoice_data['invoice_info'] = $this->db->query("SELECT * FROM `suppliers_invoices` WHERE `invoice_id` = $id")->row();
            $supplierName = getSupplierName($invoice_data['invoice_info']->supplier_id);
            $warehouseName = getWarehouseById($invoice_data['invoice_info']->store_id);
            $invoice_data['invoice_info']->storeName = $warehouseName;
            $invoice_data['invoice_info']->supplierName = $supplierName;
            $supplierId = $invoice_data['invoice_info']->supplier_id;

            $invoice_data['invoice_info']->invoice_date = date("d/m/Y", strtotime($invoice_data['invoice_info']->invoice_date));
            $supplierCredit = $this->db->query("SELECT `credit` FROM `suppliers` WHERE `supplier_id` = '$supplierId'")->row();
            if (!empty($supplierCredit)) {
                $invoice_data['invoice_info']->supplierCredit = $supplierCredit->credit;
            }
            $invoice_items = $this->db->query("SELECT * FROM `suppliers_invoices_items` WHERE `invoice_id` = $id")->result();
            $invoice_data['items'] = $invoice_items;

            foreach ($invoice_items as $item) {
                $item->item_title = getItemNameById($item->product_Id);
            }

            // debug($invoice_data);

            echo json_encode(array("result" => true, "data" => $invoice_data));
        }
    }

    public function deleteInvoiceOnly()
    {
        $data = (object)$_POST;
        // debug($_POST);
        if (isset($_POST['invoice_id']) && !empty($_POST['invoice_id'])) {
            $invoice_data = $this->db->query("SELECT * FROM `customer_invoices` WHERE `invoice_id` = $data->invoice_id")->row();
            if (!empty($invoice_data) && $invoice_data->cancel_id == 0) {
                $date_invoice = str_replace("/", "-", $invoice_data->invoice_date);
                $invoice_data->total *= -1;
                $MainInvoiceData = array(
                    'total'           => $invoice_data->total,
                    'invoice_type'    => 2,
                    'invoice_date'    => date("Y-m-d H:i:s", strtotime($date_invoice)),
                    'customerId'      => $invoice_data->customerId,
                    'warehouse_id'    => $invoice_data->warehouse_id,
                    'bossComment'     => $invoice_data->bossComment,
                    'custComment'     => $invoice_data->custComment,
                    'comment1'        => $invoice_data->comment1,
                    'comment2'        => $invoice_data->comment2,
                    'cancel_id'       => $invoice_data->invoice_id,
                    'dateCreation'    => date('Y-m-d H:i:s'),
                    'lastUpdate'      => date('Y-m-d H:i:s')
                );


                $invoice_id = $this->general_model->insertRow('customer_invoices', $MainInvoiceData);
                $this->db->query("UPDATE `customer_invoices` SET `cancel_id` = $invoice_id WHERE  `invoice_id` = $data->invoice_id");

                if (!empty($invoice_id)) {
                    $items = $this->db->query("SELECT * FROM `customer_invoice_items` WHERE `invoice_id` = $data->invoice_id")->result();
                    if (!empty($items)) {

                        foreach ($items as $item) {
                            $item->item_price *= -1;
                            $item->full_price *= -1;

                            $invoiceItemsData = array(
                                'invoice_id'    => $invoice_id,
                                'customerId'    => $invoice_data->customerId,
                                'product_id	'   => $item->product_id,
                                'item_price'    => $item->item_price,
                                'unit'          => $item->unit,
                                'full_price'    => $item->full_price,
                                'store_id'      => $item->store_id,
                                'invoice_date'  => date("Y-m-d H:i:s", strtotime($date_invoice)),
                                'dateCreation'  => date('Y-m-d H:i:s'),
                                'lastUpdate'    => date('Y-m-d H:i:s')
                            );
                            $this->general_model->insertRow('customer_invoice_items', $invoiceItemsData);
                        }
                        echo json_encode(array("result" => true));
                    } else {
                        echo json_encode(array("result" => false, "message" => "Invoice has no items connected to it"));
                    }
                }
            } else {
                echo json_encode(array("result" => false, "message" => "either the invoice doesn't have data or it has been canceled before"));
            }
        } else {
            echo json_encode(array("result" => false, "message" => "No Invoice selected"));
        }
    }

    public function deleteSupplierInvoiceOnly()
    {
        $data = (object)$_POST;
        // debug($data);
                
        $invoice_data = $this->db->query("SELECT * FROM `suppliers_invoices` WHERE `invoice_id` = $data->invoice_id")->row();
        if (!empty($invoice_data) && $invoice_data->cancel_id == 0) {

            $date_invoice = str_replace("/", "-", $invoice_data->invoice_date);
            $invoice_data->invoice_total *= -1;

            $MainInvoiceData = array(
                'invoice_total'   => $invoice_data->invoice_total,
                'invoice_date'    => date("Y-m-d H:i:s", strtotime($date_invoice)),
                'supplier_id'     => $invoice_data->supplier_id,
                'store_id'        => $invoice_data->store_id,
                'status'          => $invoice_data->status,
                'bossComment'     => $invoice_data->bossComment,
                'custComment'     => $invoice_data->custComment,
                'comment1'        => $invoice_data->comment1,
                'comment2'        => $invoice_data->comment2,
                'cancel_id'       => $invoice_data->invoice_id,
                'deleteComment'   => $invoice_data->comment2,
                'dateCreation'    => date('Y-m-d H:i:s'),
                'lastUpdate'      => date('Y-m-d H:i:s')
            );

            $invoice_id = $this->general_model->insertRow('suppliers_invoices', $MainInvoiceData);
            $this->db->query("UPDATE `suppliers_invoices` SET `cancel_id` = $invoice_id WHERE  `invoice_id` = $data->invoice_id");

            if (!empty($invoice_id)) {
                $items = $this->db->query("SELECT * FROM `suppliers_invoices_items` WHERE `invoice_id` = $data->invoice_id")->result();
                // debug($items);
                if (!empty($items)) {
                    foreach ($items as $item) {
                        $item->item_price *= -1;
                        $item->full_price *= -1;

                        $invoiceItemsData = array(
                            'invoice_Id'    => $invoice_id,
                            'suppliers_Id'  => $invoice_data->supplier_id,
                            'product_Id	'   => $item->product_Id,
                            'item_price'    => $item->item_price,
                            'unit'          => $item->unit,
                            'full_price'    => $item->full_price,
                            'store_id'      => $item->store_id,
                            'invoice_date'  => date("Y-m-d H:i:s", strtotime($date_invoice)),
                            'dateCreation'  => date('Y-m-d H:i:s'),
                            'lastUpdate'    => date('Y-m-d H:i:s')
                        );
                        $item_id = $this->general_model->insertRow('suppliers_invoices_items', $invoiceItemsData);
                        if ($item_id) {
                            echo json_encode(array("result" => true, "item_id" => $item_id));
                        } else {
                            echo json_encode(array("result" => false));
                        }
                    }
                } else {
                    echo json_encode(array("result" => false, "message" => "Invoice has no items connected to it"));
                }
            }
        } else {
            echo json_encode(array("result" => false, "message" => "either the invoice doesn't have data or it has been canceled before"));
        }
    }

    public function createInvSupplier()
    {
        $suppliers      = reindex_by_key($this->db->query("SELECT * FROM `suppliers`")->result(), 'supplier_id');
        $payment_types  = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_payments_type`")->result(), 'type_id');
        $payment_boxes  = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_boxes`")->result(), 'box_id');

        $this->template
            ->set('view', 'admin/invoices/createInvSupplier')
            ->set('suppliers', $suppliers)
            ->set('payment_types', $payment_types)
            ->set('payment_boxes', $payment_boxes)
            ->render();
    }

    public function createInvoiceOnlySupplier()
    {
        $data = (object)$_POST;
        // debug($data);
        $items = (object)$data->items;
        $date_invoice = str_replace("/", "-", $data->invoice_date);
        $finall_total = 0;
        if (!empty($data) && !empty($items)) {
            $invoice_id =  getSupplierNewInvoiceNo();
            for ($i = 0; $i < count($data->items['description']); $i++) {
                $price           =  $items->price[$i];
                $units           =  $items->unit[$i];
                $total_price     =  $price * $units;
                $finall_total   += $total_price;
                $id =  $items->product_id[$i];
                $item_details = getProductDetails($id);
                $finall_quantity = $item_details->quantity + $items->unit[$i];

                $update_data = array(
                    'price'         => $price,
                    'quantity'      => $finall_quantity,
                    'lastUpdate'    => date('Y-m-d H:i:s')
                );
                $update_row =  $this->general_model->updateRowById('products', 'id', $items->product_id[$i], $update_data);


                $invoiceItemsData = array(
                    'invoice_Id'    => $invoice_id,
                    'suppliers_Id'  => $data->invoice_for,
                    'product_Id'    => $id,
                    'item_title'    => $item_details->name,
                    'item_price'    => $items->price[$i],
                    'unit'          => $items->unit[$i],
                    'full_price'    => $total_price,
                    'store_id'      => $data->storage,
                    'invoice_date'  => date("Y-m-d H:i:s", strtotime($date_invoice)),
                    'dateCreation'  => date('Y-m-d H:i:s'),
                    'lastUpdate'    => date('Y-m-d H:i:s')
                );

                $item_id = $this->general_model->insertRow('suppliers_invoices_items', $invoiceItemsData);

                $quantity = getWarehouseQuantity($data->storage, $id);
                // debug($quantity);
                if (!empty($quantity)) {
                    $itemWarehouse = $this->db->query("SELECT `ID` FROM `warehouse_items` WHERE `warehouse_id` = $data->storage AND  `product_id` = $id ")->row();
                    $finall_quantity = $quantity + $items->unit[$i];
                    $warehouseUpdateData = array(
                        'quantity'      => $finall_quantity,
                        'update_date'   => date('Y-m-d H:i:s')
                    );

                    $item_id =  $this->general_model->updateRowById('warehouse_items', 'ID', $itemWarehouse->ID, $warehouseUpdateData);
                } else {
                    $warehouseItemData = array(
                        'product_Id'    => $id,
                        'quantity'      => $items->unit[$i],
                        'warehouse_id'  => $data->storage,
                        'entry_date'    => date('Y-m-d H:i:s'),
                        'update_date'   => date('Y-m-d H:i:s')
                    );

                    $item_id = $this->general_model->insertRow('warehouse_items', $warehouseItemData);
                }
            }


            $MainInvoiceData = array(
                'invoice_total'   => $finall_total,
                'invoice_date'    =>  date("Y-m-d H:i:s", strtotime($date_invoice)),
                'supplier_id'     => $data->invoice_for,
                'invoice_for'     => $data->invoice_for,
                'store_id'        => $data->storage,
                'dateCreation'    => date('Y-m-d H:i:s'),
                'lastUpdate'      => date('Y-m-d H:i:s'),
                'bossComment'     => $data->boss_Comment,
                'custComment'     => $data->custComment,
                'Comment1'        => $data->comment1,
                'Comment2'        => $data->comment2,
            );

            $invoice_id = $this->general_model->insertRow('suppliers_invoices', $MainInvoiceData);


            redirect("admin/invoices/InvSuppliers", 'refresh');
        }
        redirect("admin/invoices/InvSuppliers", 'refresh');
    }


    public function supplierInvoiceAuto()
    {
        $data                   = (object)$_POST;
        $supplier_id = $this->uri->segment(4);
        // debug($supplier_id);
        // $MainInvoiceData = array(
        //     'supplier_id'       => $supplier_id,
        //     'invoice_total'     => $data->invoice_total,
        //     'invoice_for'       => $supplier_id,
        //     'dateCreation'      => date('Y-m-d H:i:s'),
        //     'lastUpdate'        => date('Y-m-d H:i:s')
        // );
        // // debug($MainInvoiceData);
        // $newInvoice = $this->general_model->insertRow('suppliers_invoices', $MainInvoiceData);
        // debug($newInvoice);


        $cronDays = implode(',', $_POST['days']);
        // debug($cronDays);
        $cronJobRow = array(
            'invoice_type'  => "supplier_invoice",
            'supplier_id'    => $supplier_id,
            'days'          => $cronDays,
            'total'         => $data->invoice_total,
            'product_id'    => $data->product_id,
            'counter'       => 0,
            'dateCreation'  => date('Y-m-d H:i:s')
        );
        // debug($cronJobRow);
        $newcronJobRow = $this->general_model->insertRow('cron_job', $cronJobRow);
        redirect("admin/suppliers/view/$supplier_id", 'refresh');
    }



    public function addPayment()
    {
        $data                   = (object)$_POST;
        $items = (object)$data->items;
        // debug($data);
        $invoices = 0;
        if (isset($data->invoice_id) && !empty($data->invoice_id)) {
            $invoices = implode(",", $data->invoice_id);
        } else {
            $invoices = 0;
        }
        $total = 0;
        for ($i = 0; $i < count($data->items['payment_method']); $i++) {
            $invoicePaymentData = array(
                'payment_id'            => $data->payment_code,
                'invoice_id'            => $invoices,
                'customerId'            => $data->payment_for,
                'type'                  => 0,
                'payment_type'          => $items->payment_method[$i],
                'payment_box'           => $items->cashbox[$i],
                'payment_date'          => date('Y-m-d H:i:s', strtotime(str_replace('/', '-', $data->payment_date))),
                'check_date'            => date('Y-m-d H:i:s', strtotime(str_replace('/', '-', $data->payment_date))),
                'bank_visa'             => $items->hidden_bank[$i],
                'branch_digits'         => $items->hidden_branch[$i],
                'account_card'          => $items->invoice_validity[$i],
                'check_number'          => $items->check_number[$i],
                'reference_id'          => $items->reference_id_num[$i],
                'total'                 => $items->sum[$i],
                'is_receipt'            => 1,
                'receipt_number'        => $data->payment_code,
                'dateCreation'          => date('Y-m-d H:i:s'),
                'lastUpdate'            => date('Y-m-d H:i:s')
            );
            $payment_id = $this->general_model->insertRow('customer_invoices_payments_items', $invoicePaymentData);
            $total += $items->sum[$i];
            $logData = array(
                'userId	'     => getUserId(),
                'type'        => "customer_payment_items",
                'type_id'     => $payment_id,
                'action'      => "add_check_customer_payment_item",
                'befor'       => "nothing",
                'after'       => "add customer payment item by check ",
                'action_date' => date('Y-m-d H:i:s'),
            );
            $log_id = $this->general_model->insertRow('activities_log', $logData);
        }
        $invoicePaymentData = array(
            'invoice_id'            => $invoices,
            'customerId'            => $data->payment_for,
            'type'                  => 0,
            'payment_date'          => date('Y-m-d H:i:s', strtotime(str_replace('/', '-', $data->payment_date))),
            'total'                 => $total,
            'payment_for'           => $invoices,
            'boss_comment'          => $data->boss_Comment,
            'cust_comment'           => $data->custComment,
            'comment1'              => $data->comment1,
            'comment2'              => $data->comment2,
            'dateCreation'          => date('Y-m-d H:i:s'),
            'lastUpdate'            => date('Y-m-d H:i:s')
        );
        $payment_id = $this->general_model->insertRow('customer_invoices_payments', $invoicePaymentData);
        $logData = array(
            'userId	'     => getUserId(),
            'type'        => "customer_payment",
            'type_id'     => $payment_id,
            'action'      => "add_check_customer_payment",
            'befor'       => "nothing",
            'after'       => "add customer payment by check ",
            'action_date' => date('Y-m-d H:i:s'),
        );
        $log_id = $this->general_model->insertRow('activities_log', $logData);


        if (!empty($payment_id)) {
            echo json_encode(array("result" => true, "payment" => $payment_id));
        } else {
            echo json_encode(array("result" => false));
        }
    }


    public function addSupplierPayment()
    {
        if (
            isset($_POST['payment_for'])
            && isset($_POST['payment_date'])
            && isset($_POST['total'])
            && !empty($_POST['payment_for'])
            && !empty($_POST['payment_date'])
            && !empty($_POST['total'])
        ) {
            $mainPaymentInfo = array(
                'supplier_id'          => $_POST['payment_for'],
                'status'               => 0,
                'payment_date'         => date('Y-m-d H:i:s', strtotime(str_replace('/', '-', $_POST['payment_date']))),
                'is_cancel'            => 0,
                'cancel_id'            => 0,
                'bossComment'          => $_POST['boss_Comment'],
                'custComment'          => $_POST['custComment'],
                'comment1'             => $_POST['comment1'],
                'comment2'             => $_POST['comment2'],
                'deleteComment'        => '',
                'total'                => $_POST['total'],
                'dateCreation'         => date('Y-m-d H:i:s'),
                'lastUpdate'           => date('Y-m-d H:i:s'),
            );

            $payment_id = $this->general_model->insertRow('suppliers_payments', $mainPaymentInfo);
            $logData = array(
                'userId	'     => getUserId(),
                'type'        => "supplier_payment",
                'type_id'     => $payment_id,
                'action'      => "add_supplier_payment",
                'befor'       => "nothing",
                'after'       => "add supplier payment by check ",
                'action_date' => date('Y-m-d H:i:s'),
            );
            $log_id = $this->general_model->insertRow('activities_log', $logData);

            if (!empty($payment_id)) {
                $items = $_POST['items'];
                for ($i = 0; $i < count($items['payment_method']); $i++) {
                    $payment_items = array(
                        'payment_id'        => $payment_id,
                        'supplier_id'       => $_POST['payment_for'],
                        'payment_method'    => $items['payment_method'][$i],
                        'box'               => $items['cashbox'][$i],
                        'payment_total'     => $items['sum'][$i],
                        'bank_visa'         => $items['hidden_bank'][$i],
                        'Branch_digits'     => $items['hidden_branch'][$i],
                        'account_date'      => $items['invoice_validity'][$i],
                        'check_number'      => $items['check_number'][$i],
                        'reference_number'  => $items['reference_id_num'][$i],
                        'payment_date'      => $items['check_date'][$i],
                        'dateCreation'      => date('Y-m-d H:i:s'),
                        'lastUpdate'        => date('Y-m-d H:i:s'),
                    );
                    $addedItems = $this->general_model->insertRow('supplier_payments_items', $payment_items);
                    // echo json_encode(array("result" => true, "Message" => $addedItems));


                    $logData = array(
                        'userId	'     => getUserId(),
                        'type'        => "supplier_payment_items",
                        'type_id'     => $addedItems,
                        'action'      => "add_check_supplier_payment_item",
                        'befor'       => "nothing",
                        'after'       => "add supplier payment item by check ",
                        'action_date' => date('Y-m-d H:i:s'),
                    );
                    $log_id = $this->general_model->insertRow('activities_log', $logData);

                    if (!empty($items['customer_payment_id'][$i]) && isset($items['customer_payment_id'][$i])) {
                        $item_id = $items['customer_payment_id'][$i];
                        $update_data = array(
                            'check_used'      => 1,
                            'check_used_for'  => $_POST['payment_for'],
                        );
                        $update_row = $this->general_model->updateRowById('customer_invoices_payments_items', 'item_id', $item_id, $update_data);
                        $logData = array(
                            'userId	'     => getUserId(),
                            'type'        => "customer_payment_items",
                            'type_id'     => $addedItems,
                            'action'      => "update_check_customer_payment_item",
                            'befor'       => "status: not_used",
                            'after'       => "status: used ",
                            'action_date' => date('Y-m-d H:i:s'),
                        );
                        $log_id = $this->general_model->insertRow('activities_log', $logData);
                    }
                }

                if (!empty($addedItems)) {
                    echo json_encode(array("result" => true, "Message" => "Added Successfully"));
                }
            } else {
                echo json_encode(array("result" => false, "Message" => "Something wrong with the items inserted"));
            }
        } else {
            echo json_encode(array("result" => false, "Message" => "Some Data is either missing, or invalid"));
        }
    }

    public function deleteCustomerPayment()
    {
        $data  = (object)$_POST;

        $payment_data = $this->db->query("SELECT * FROM `customer_invoices_payments` WHERE `payment_id` = $data->payment_code")->row();

        // debug($payment_data);
        if (!empty($payment_data) && $payment_data->cancel_id == 0) {
            $date_payment = str_replace("/", "-", $payment_data->payment_date);
            $payment_data->total *= -1;
            $MainpaymentData = array(
                'total'           => $payment_data->total,
                'payment_date'    => date("Y-m-d H:i:s", strtotime($date_payment)),
                'customerId'      => $payment_data->customerId,
                'boss_comment'     => $payment_data->boss_comment,
                'cust_comment'     => $payment_data->cust_comment,
                'comment1'        => $payment_data->comment1,
                'comment2'        => $payment_data->comment2,
                'cancel_id'       => $data->payment_code,
                'dateCreation'    => date('Y-m-d H:i:s'),
                'lastUpdate'      => date('Y-m-d H:i:s')
            );

            $payment_id = $this->general_model->insertRow('customer_invoices_payments', $MainpaymentData);
            $this->db->query("UPDATE `customer_invoices_payments` SET `cancel_id` = $payment_id WHERE  `payment_id` = $data->payment_code");

            if (!empty($payment_id)) {
                $items = $this->db->query("SELECT * FROM `customer_invoices_payments_items` WHERE `payment_id` = $data->payment_code")->result();
                if (!empty($items)) {
                    foreach ($items as $item) {
                        $paymentItemsData = array(
                            "payment_id"                => $item->payment_id,
                            "customerId"                => $item->customerId,
                            "type"                      => $item->type,
                            "invoice_id"                => $item->invoice_id,
                            "payment_type"               => $item->payment_type,
                            "payment_box"               => $item->payment_box,
                            "payment_date"              => $item->payment_date,
                            "check_used"                => $item->check_used,
                            "check_return"              => $item->check_return,
                            "bank_visa"                 => $item->bank_visa,
                            "branch_digits"             => $item->branch_digits,
                            "account_card"              => $item->account_card,
                            "check_number"              => $item->check_number,
                            "check_date"                => $item->check_date,
                            "check_used_for"            => $item->check_used_for,
                            "reference_id"              => $item->reference_id,
                            "total"                     => $item->total * -1,
                            "is_canceled"               => 1,
                            "no_need_invoice"           => $item->no_need_invoice,
                            "is_receipt"                => $item->is_receipt,
                            "receipt_number"            => $item->receipt_number,
                            "tranzilla_receipt_id"      => $item->tranzilla_receipt_id,
                            "receipt_key"               => $item->receipt_key,
                            "dateCreation"              => $item->dateCreation,
                            "lastUpdate"                => $item->lastUpdate,
                        );
                        // $paymentItemsData = array(
                        //     'payment_id'    => $payment_id,
                        //     'customerId'    => $payment_data->customerId,
                        //     'product_id	'   => $item->product_id,
                        //     'item_price'    => $item->item_price,
                        //     'unit'          => $item->unit,
                        //     'full_price'    => $item->full_price,
                        //     'store_id'      => $item->store_id,
                        //     'payment_date'  => date("Y-m-d H:i:s", strtotime($date_payment)),
                        //     'dateCreation'  => date('Y-m-d H:i:s'),
                        //     'lastUpdate'    => date('Y-m-d H:i:s')
                        // );
                        $this->general_model->insertRow('customer_invoices_payments_items', $paymentItemsData);
                    }
                    echo json_encode(array("result" => true, "message" => "Added Payment Successfully"));
                } else {
                    echo json_encode(array("result" => false, "message" => "Invoice has no items connected to it"));
                }
            } else {
                echo json_encode(array("result" => false));
            }
        } else {
            echo json_encode(array("result" => false));
        }
        // if (!empty($payment_id)) {
        //     echo json_encode(array("result" => true, "payment" => $payment_id));
        // } else {
        //     echo json_encode(array("result" => false));
        // }
    }


    // Make a new payement 
    // the newly made payment id has to be the cancel_id of the original payment
    // Update the original payment so that the cancel id of the new payment is as the original payment id
    // the original payment's isCanceled must be true == 1
    public function deleteSupplierPayment()
    {
        $data  = (object)$_POST;

        $payment_data = $this->db->query("SELECT * FROM `suppliers_payments` WHERE `id` = $data->payment_code")->row();

        // debug($payment_data);
        if (!empty($payment_data) && $payment_data->cancel_id == 0) {
            $date_payment = str_replace("/", "-", $payment_data->payment_date);
            $total = $payment_data->total * -1;
            $MainpaymentData = array(
                'payment_date'    => date("Y-m-d H:i:s", strtotime($date_payment)),
                'supplier_id'     => $payment_data->supplier_id,
                'bossComment'     => $payment_data->bossComment,
                'custComment'     => $payment_data->custComment,
                'comment1'        => $payment_data->comment1,
                'comment2'        => $payment_data->comment2,
                'cancel_id'       => $data->payment_code,
                'total'           => $total,
                'dateCreation'    => date('Y-m-d H:i:s'),
                'lastUpdate'      => date('Y-m-d H:i:s')
            );


            $new_payment_id = $this->general_model->insertRow('suppliers_payments', $MainpaymentData);

            $oldWhereArray = array(
                "cancel_id" => $new_payment_id
            );

            // debug($new_payment_id);

            $this->db->query("UPDATE `suppliers_payments` SET `cancel_id` = $new_payment_id, `is_cancel` = 1 WHERE  `id` = $data->payment_code");

            if (!empty($new_payment_id)) {
                $items = $this->db->query("SELECT * FROM `supplier_payments_items` WHERE `payment_id` = $data->payment_code")->result();
                if (!empty($items)) {
                    foreach ($items as $item) {
                        $paymentItemsData = array(
                            "payment_id"                => $item->payment_id,
                            "supplier_id"               => $item->supplier_id,
                            "type"                      => $item->type,
                            "invoice_id"                => $item->invoice_id,
                            "payment_type"              => $item->payment_type,
                            "box         "              => $item->box,
                            "payment_date"              => $item->payment_date,
                            "check_used"                => $item->check_used,
                            "check_return"              => $item->check_return,
                            "bank_visa"                 => $item->bank_visa,
                            "Branch_digits"             => $item->Branch_digits,
                            "account_date"              => $item->account_date,
                            "check_number"              => $item->check_number,
                            "check_date"                => $item->check_date,
                            "check_used_for"            => $item->check_used_for,
                            "reference_number"          => $item->reference_number,
                            "payment_total"             => $item->payment_total * -1,
                            "is_canceled"               => 1,
                            "no_need_invoice"           => $item->no_need_invoice,
                            "is_receipt"                => $item->is_receipt,
                            "receipt_number"            => $item->receipt_number,
                            "tranzilla_receipt_id"      => $item->tranzilla_receipt_id,
                            "receipt_key"               => $item->receipt_key,
                            "dateCreation"              => $item->dateCreation,
                            "lastUpdate"                => $item->lastUpdate,
                        );
                        $paymentItemsInserted = $this->general_model->insertRow('supplier_payments_items', $paymentItemsData);
                    }

                    // debug($paymentItemsInserted);

                    if (!empty($paymentItemsInserted)) {
                        echo json_encode(array("result" => true, "message" => "Added Payment Successfully"));
                    }
                } else {
                    echo json_encode(array("result" => false, "message" => "Invoice has no items connected to it"));
                }
            } else {
                echo json_encode(array("result" => false, "message" => "Failed to add new payment"));
            }
        } else {
            echo json_encode(array("result" => false, "message" => "Payment Data is invalid, or has been canceled before"));
        }
    }



    // public function addPaymentSupplier()
    // {
    //     $data                   = (object)$_POST;
    //     debug($data);
    //     // $receipt_Number         = $this->db->query("SELECT `receipt_number` FROM `customer_invoices_payments` ORDER BY `receipt_number` DESC LIMIT 1")->row();
    //     $new_receipt_Number     =  $data->payment_code;
    //     if (isset($data->invoice_id) && !empty($data->invoice_id)) {
    //         $invoices = implode(",", $data->invoice_id);
    //     } else {
    //         $invoices = 0;
    //     }
    //     $invoicePaymentData = array(
    //         'invoice_id'           => 0,
    //         'customerId'            => $data->supplier_id,
    //         'type'                  => 1,
    //         'payment_type'          => $data->payment_type,
    //         'payment_box'           => $data->payment_box,
    //         'payment_date'          => date('Y-m-d H:i:s', strtotime(str_replace('/', '-', $data->payment_date))),
    //         'bank_visa'             => $data->bank_visa,
    //         'branch_digits'         => $data->branch_digits,
    //         'account_card'          => $data->account_card,
    //         'reference_id'          => $data->reference_id,
    //         'total'                 => $data->total_payment * -1,
    //         'is_receipt'            => 1,
    //         'receipt_number'        => $new_receipt_Number,
    //         'payment_for'           => $invoices,
    //         'dateCreation'          => date('Y-m-d H:i:s'),
    //         'lastUpdate'            => date('Y-m-d H:i:s')
    //     );
    //     $payment_id = $this->general_model->insertRow('customer_invoices_payments', $invoicePaymentData);
    //     if (!empty($payment_id)) {
    //         echo json_encode(array("result" => true, "payment" => $payment_id));
    //     } else {
    //         echo json_encode(array("result" => false));
    //     }
    // }

    public function finance()
    {

        $payment_boxes  = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_boxes`")->result(), 'box_id');
        $boxes_category = $this->db->query("SELECT `category` FROM `customer_invoices_boxes` GROUP BY `category`")->result();
        $full_sums      = reindex_by_key($this->db->query("SELECT SUM(`total`) AS `SUMS`, `payment_box` FROM `customer_invoices_payments` GROUP BY `payment_box`")->result(), 'payment_box');
        $sums           = array();
        $payment_types  = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_payments_type`")->result(), 'type_id');
        $customers      = reindex_by_key($this->db->query("SELECT * FROM `customers`")->result(), 'customerId');
        $suppliers      = reindex_by_key($this->db->query("SELECT * FROM `suppliers`")->result(), 'supplier_id');
        $temp_clients   = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_details_temp`")->result(), 'detail_id');

        foreach ($payment_boxes as $box) {
            $sums[$box->box_id]['id']       = $box->box_id;
            $sums[$box->box_id]['name']     = $box->name;
            if (isset($full_sums[$box->box_id]->SUMS)) {
                $sums[$box->box_id]['sum']      = $full_sums[$box->box_id]->SUMS;
            } else {
                $sums[$box->box_id]['sum']      = 0;
            }
        }

        $this->template
            ->set('view', 'admin/invoices/finance')
            ->set('payment_boxes', $payment_boxes)
            ->set('sums', $sums)
            ->set('payment_boxes', $payment_boxes)
            ->set('payment_types', $payment_types)
            ->set('customers', $customers)
            ->set('suppliers', $suppliers)
            ->set('temp_clients', $temp_clients)
            ->set('boxes_category', $boxes_category)
            ->render();
    }

    public function convertPayment()
    {

        $data = (object)$_POST;


        $payment        = $this->general_model->getRowById('customer_invoices_payments', 'payment_id', $data->payment_id);
        $oldBox         = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_boxes` WHERE `box_id` = $payment->payment_box")->row(), 'box_id');
        $newBox         = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_boxes` WHERE `box_id` = $data->new_box")->row(), 'box_id');
        $oldBoxName     = $oldBox->name;
        $newBoxName     = $newBox->name;
        // $convert_date   = date('Y-m-d H:i:s', strtotime(str_replace('/', '-', $data->convert_date)));
        // debug($data);
        $updateConvert  = $this->general_model->updateRowById('customer_invoices_payments', 'payment_id', $data->payment_id, array('is_converted' => '1', 'lastUpdate' => date('Y-m-d H:i:s')));

        $negative_payment_data = array(
            'invoice_id'        => $payment->invoice_id,
            'customerId'       => $payment->customerId,
            'payment_type'      => $payment->payment_type,
            'payment_box'       => $payment->payment_box,
            'payment_date'      => date('Y-m-d H:i:s'),
            'bank_visa'         => $payment->bank_visa,
            'branch_digits'     => $payment->branch_digits,
            'account_card'      => $payment->account_card,
            'reference_id'      => $payment->reference_id,
            'total'             => $payment->total * -1,
            'notes'             => 'העברה אל ' . $newBoxName,
            // 'notes2'            => $data->notes,
            'is_converted'      => 1,
            'dateCreation'      => date('Y-m-d H:i:s'),
            'lastUpdate'        => date('Y-m-d H:i:s')
        );

        $payment_id = $this->general_model->insertRow('customer_invoices_payments', $negative_payment_data);

        $new_payment_data  = array(
            'invoice_id'        => $payment->invoice_id,
            'customerId'       => $payment->customerId,
            'payment_type'      => $data->new_payment,
            'payment_box'       => $data->new_box,
            'payment_date'      => date('Y-m-d H:i:s'),
            'bank_visa'         => $payment->bank_visa,
            'branch_digits'     => $payment->branch_digits,
            'account_card'      => $payment->account_card,
            'reference_id'      => $payment->reference_id,
            'total'             => $payment->total,
            'notes'             => 'העברה מ ' . $oldBoxName,
            // 'notes2'            => $data->notes,
            'is_converted'      => 1,
            'convert_from'      => $payment->payment_box,
            'dateCreation'      => date('Y-m-d H:i:s'),
            'lastUpdate'        => date('Y-m-d H:i:s')
        );

        $payment_id2 = $this->general_model->insertRow('customer_invoices_payments', $new_payment_data);

        echo json_encode(array("result" => true));
    }

    public function supplierconvertPayment()
    {

        $data = (object)$_POST;

        $payment        = $this->general_model->getRowById('customer_invoices_payments', 'payment_id', $data->payment_id);
        $oldBox         = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_boxes` WHERE `box_id` = $payment->payment_box")->row(), 'box_id');
        $newBox         = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_boxes` WHERE `box_id` = $data->new_box")->row(), 'box_id');
        $oldBoxName     = $oldBox->name;
        $newBoxName     = $newBox->name;
        $convert_date   = date('Y-m-d H:i:s', strtotime(str_replace('/', '-', $data->convert_date)));

        $updateConvert  = $this->general_model->updateRowById('customer_invoices_payments', 'payment_id', $data->payment_id, array('is_converted' => '1', 'lastUpdate' => date('Y-m-d H:i:s')));

        $negative_payment_data = array(
            'invoice_id'        => $payment->invoice_id,
            'customerId'       => $payment->customerId,
            'payment_type'      => $payment->payment_type,
            'payment_box'       => $payment->payment_box,
            'payment_date'      => $convert_date,
            'bank_visa'         => $payment->bank_visa,
            'branch_digits'     => $payment->branch_digits,
            'account_card'      => $payment->account_card,
            'reference_id'      => $payment->reference_id,
            'total'             => $payment->total * -1,
            'notes'             => 'העברה אל ' . $newBoxName,
            'notes2'            => $data->notes,
            'is_converted'      => 1,
            'dateCreation'      => date('Y-m-d H:i:s'),
            'lastUpdate'        => date('Y-m-d H:i:s')
        );

        $payment_id = $this->general_model->insertRow('customer_invoices_payments', $negative_payment_data);

        $new_payment_data  = array(
            'invoice_id'        => $payment->invoice_id,
            'customerId'       => $payment->customerId,
            'payment_type'      => $data->new_payment,
            'payment_box'       => $data->new_box,
            'payment_date'      => $convert_date,
            'bank_visa'         => $payment->bank_visa,
            'branch_digits'     => $payment->branch_digits,
            'account_card'      => $payment->account_card,
            'reference_id'      => $payment->reference_id,
            'total'             => $payment->total,
            'notes'             => 'העברה מ ' . $oldBoxName,
            'notes2'            => $data->notes,
            'is_converted'      => 1,
            'convert_from'      => $payment->payment_box,
            'dateCreation'      => date('Y-m-d H:i:s'),
            'lastUpdate'        => date('Y-m-d H:i:s')
        );

        $payment_id2 = $this->general_model->insertRow('customer_invoices_payments', $new_payment_data);

        echo json_encode(array("result" => true));
    }

    public function convertPaymentMulti()
    {

        $data           = (object)$_POST;

        if (!empty($data->payments)) {
            $sPayments      = implode(",", $data->payments);
            $oldBox         = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_boxes` WHERE `box_id` = $data->old_box")->row(), 'box_id');
            $newBox         = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_boxes` WHERE `box_id` = $data->new_box")->row(), 'box_id');
            $oldBoxName     = $oldBox->name;
            $newBoxName     = $newBox->name;
            $convert_date   = date('Y-m-d H:i:s', strtotime(str_replace('/', '-', $data->convert_date)));

            foreach ($data->payments as $p) {
                $updateConvert  = $this->general_model->updateRowById('customer_invoices_payments', 'payment_id', $p, array('is_converted' => '1', 'lastUpdate' => date('Y-m-d H:i:s')));
            }

            $negative_payment_data = array(
                'invoice_id'        => '',
                'customerId'       => '',
                'payment_type'      => '',
                'payment_box'       => $data->old_box,
                'payment_date'      => $convert_date,
                'bank_visa'         => '',
                'branch_digits'     => '',
                'account_card'      => '',
                'reference_id'      => '',
                'total'             => $data->total * -1,
                'notes'             => 'העברה אל ' . $newBoxName,
                'notes2'            => $data->notes,
                'is_converted'      => 1,
                'dateCreation'      => date('Y-m-d H:i:s'),
                'lastUpdate'        => date('Y-m-d H:i:s')
            );

            $payment_id = $this->general_model->insertRow('customer_invoices_payments', $negative_payment_data);

            $new_payment_data  = array(
                'invoice_id'            => '',
                'customerId'           => '',
                'payment_type'          => $data->new_payment,
                'payment_box'           => $data->new_box,
                'payment_date'          => $convert_date,
                'bank_visa'             => '',
                'branch_digits'         => '',
                'account_card'          => '',
                'reference_id'          => '',
                'total'                 => $data->total,
                'notes'                 => 'העברה מ ' . $oldBoxName,
                'notes2'                => $data->notes,
                'is_converted'          => 1,
                'convert_from'          => $data->old_box,
                'converted_multi_ids'   => $sPayments,
                'dateCreation'          => date('Y-m-d H:i:s'),
                'lastUpdate'            => date('Y-m-d H:i:s')
            );

            $payment_id2 = $this->general_model->insertRow('customer_invoices_payments', $new_payment_data);

            echo json_encode(array("result" => true));
        } else {
            echo json_encode(array("result" => false));
        }
    }

    public function makePaymentwithConvert()
    {

        $data           = (object)$_POST;

        if (!empty($data->total)) {

            $oldBox         = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_boxes` WHERE `box_id` = $data->old_box")->row(), 'box_id');
            $newBox         = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_boxes` WHERE `box_id` = $data->new_box")->row(), 'box_id');
            $oldBoxName     = $oldBox->name;
            $newBoxName     = $newBox->name;
            $convert_date   = date('Y-m-d H:i:s', strtotime(str_replace('/', '-', $data->convert_date)));

            $negative_payment_data = array(
                'invoice_id'        => '',
                'customerId'       => '',
                'payment_type'      => '',
                'payment_box'       => $data->old_box,
                'payment_date'      => $convert_date,
                'bank_visa'         => '',
                'branch_digits'     => '',
                'account_card'      => '',
                'reference_id'      => '',
                'total'             => $data->total * -1,
                'notes'             => 'העברה אל ' . $newBoxName,
                'notes2'            => $data->notes,
                'is_converted'      => 1,
                'dateCreation'      => date('Y-m-d H:i:s'),
                'lastUpdate'        => date('Y-m-d H:i:s')
            );

            $payment_id = $this->general_model->insertRow('customer_invoices_payments', $negative_payment_data);

            $new_payment_data  = array(
                'invoice_id'            => '',
                'customerId'           => '',
                'payment_type'          => $data->new_payment,
                'payment_box'           => $data->new_box,
                'payment_date'          => $convert_date,
                'bank_visa'             => '',
                'branch_digits'         => '',
                'account_card'          => '',
                'reference_id'          => '',
                'total'                 => $data->total,
                'notes'                 => 'העברה מ ' . $oldBoxName,
                'notes2'                => $data->notes,
                'is_converted'          => 1,
                'convert_from'          => $data->old_box,
                'dateCreation'          => date('Y-m-d H:i:s'),
                'lastUpdate'            => date('Y-m-d H:i:s')
            );

            $payment_id2 = $this->general_model->insertRow('customer_invoices_payments', $new_payment_data);

            echo json_encode(array("result" => true));
        } else {
            echo json_encode(array("result" => false));
        }
    }

    public function insertSupplierInvoice()
    {

        $data = (object)$_POST;

        $supplierInvoiceData = array(
            'supplier_id'       => $data->supplier_id,
            'invoice_number'    => $data->invoice_number,
            'invoice_date'      => date('Y-m-d 01:00:00', strtotime(str_replace('/', '-', $data->invoice_date))),
            'invoice_for'       => $data->invoice_for,
            'invoice_total'     => $data->invoice_total,
            'dateCreation'      => date('Y-m-d 01:00:00', strtotime(str_replace('/', '-', $data->invoice_date))),
            'lastUpdate'        => date('Y-m-d H:i:s')
        );

        $supplier_invoice_id = $this->general_model->insertRow('suppliers_invoices', $supplierInvoiceData);

        $new_payment_data  = array(
            'invoice_id'            => '',
            'customerId'           => '',
            'supplier_id'           => $data->supplier_id,
            'payment_type'          => $data->payment_type,
            'payment_box'           => $data->payment_box,
            'payment_date'          => date('Y-m-d', strtotime(str_replace('/', '-', $data->invoice_date))),
            'bank_visa'             => '',
            'branch_digits'         => '',
            'account_card'          => '',
            'reference_id'          => '',
            'total'                 => $data->invoice_total * -1,
            'notes'                 => '',
            'notes2'                => $data->invoice_for,
            'is_converted'          => 0,
            'dateCreation'          => date('Y-m-d H:i:s'),
            'lastUpdate'            => date('Y-m-d H:i:s')
        );

        $payment_id2 = $this->general_model->insertRow('customer_invoices_payments', $new_payment_data);

        if (!empty($supplier_invoice_id)) {
            echo json_encode(array("result" => true));
        } else {
            echo json_encode(array("result" => false));
        }
    }

    public function manageBoxes()
    {

        $payment_boxes  = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_boxes`")->result(), 'box_id');
        $boxes_category = $this->db->query("SELECT `category` FROM `customer_invoices_boxes` GROUP BY `category`")->result();

        $this->template
            ->set('view', 'admin/invoices/mangeBoxes')
            ->set('payment_boxes', $payment_boxes)
            ->set('boxes_category', $boxes_category)
            ->render();
    }

    public function addBox()
    {

        $name           = $_POST['name'];
        $convertType    = $_POST['convert_type'];
        $category       = $_POST['category'];

        $box_data = array(
            'name'            => $name,
            'convert_type'    => $convertType,
            'category'        => $category
        );

        $result = $this->general_model->insertRow('customer_invoices_boxes', $box_data);

        redirect('admin/invoices/manageBoxes/', 'refresh');
    }

    public function editBoxDetails()
    {

        $box_id         = $_POST['box_id'];
        $box_name       = $_POST['box_name'];
        $box_category   = $_POST['box_category'];

        $box_data = array(
            'name'      => $box_name,
            'category'  => $box_category
        );

        $updateBox = $this->general_model->updateRowById('customer_invoices_boxes', 'box_id', $box_id, $box_data);

        if (!empty($updateBox)) {
            echo json_encode(array("result" => true));
        } else {
            echo json_encode(array("result" => false));
        }
    }

    public function addCommentToPayment()
    {

        $data = (object)$_POST;
        $updateNote  = $this->general_model->updateRowById('customer_invoices_payments', 'payment_id', $data->payment_id, array('notes2' => $data->comment, 'lastUpdate' => date('Y-m-d H:i:s')));

        if (!empty($updateNote)) {
            echo json_encode(array("result" => true));
        } else {
            echo json_encode(array("result" => false));
        }
    }

    public function markasNoInvoice()
    {

        $data = (object)$_POST;
        $updateNoNeedInvoice  = $this->general_model->updateRowById('customer_invoices_payments', 'payment_id', $data->payment_id, array('no_need_invoice' => 1, 'lastUpdate' => date('Y-m-d H:i:s')));

        if (!empty($updateNoNeedInvoice)) {
            echo json_encode(array("result" => true));
        } else {
            echo json_encode(array("result" => false));
        }
    }

    public function makeInvoiceForPayment()
    {

        $data = (object)$_POST;

        $payment = $this->general_model->getRowById('customer_invoices_payments', 'payment_id', $data->payment_id);

        $MainInvoiceData = array(
            'invoice_type'    => 1,
            'total'           => $payment->total,
            'invoice_date'    => date('Y-m-d H:i:s'),
            'customerId'      => $payment->customerId,
            'dateCreation'    => date('Y-m-d H:i:s'),
            'lastUpdate'      => date('Y-m-d H:i:s')
        );

        $invoice_id = $this->general_model->insertRow('customer_invoices', $MainInvoiceData);

        if (!empty($invoice_id)) {

            $item_price = $payment->total / 1.17;

            $invoiceItemsData = array(
                'invoice_id'      => $invoice_id,
                'item_title'      => 'עבור שירותי תקשורת',
                'item_price'      => $item_price,
                'customerId'     => $payment->customerId,
                'dateCreation'    => date('Y-m-d H:i:s'),
                'lastUpdate'      => date('Y-m-d H:i:s')
            );

            $item_id = $this->general_model->insertRow('customer_invoice_items', $invoiceItemsData);

            $updatePayment = $this->general_model->updateRowById('customer_invoices_payments', 'payment_id', $data->payment_id, array('invoice_id' => $invoice_id, 'lastUpdate' => date('Y-m-d H:i:s')));

            if (!empty($updatePayment)) {
                echo json_encode(array("result" => true));
            } else {
                echo json_encode(array("result" => false));
            }
        }
    }

    public function getOpenInvoices()
    {

        $data = (object)$_POST;

        if ($data->rel == 'customer') {
            $open_invoices = $this->db->query("SELECT * FROM `customer_invoices` WHERE `customerId` = '$data->customerId' AND `invoice_type` = 2 ")->result();
            foreach ($open_invoices as $open_invoice) {
                $payed = $this->db->query("SELECT SUM(total) AS total FROM `customer_invoices_payments_connect` WHERE `invoice_id` = '$open_invoice->invoice_id' ")->row();
                if (isset($payed->total) && !empty($payed->total) && $payed->total > 0) {
                    $open_invoice->payed = $payed->total;
                    $open_invoice->balance = $payed->total - $open_invoice->total;
                } else {
                    $open_invoice->payed = 0;
                    $open_invoice->balance = $open_invoice->total;
                }
            }
        }

        if ($data->rel == 'temp_customer') {
            $open_invoices = $this->db->query("SELECT * FROM `customer_invoices` WHERE `detail_id` = '$data->customerId' AND `invoice_type` = 2")->result();
            foreach ($open_invoices as $open_invoice) {
                $payed = $this->db->query("SELECT SUM(total) AS total FROM `customer_invoices_payments_connect` WHERE `invoice_id` = '$open_invoice->invoice_id' ")->row();
                if (isset($payed->total) && !empty($payed->total) && $payed->total > 0) {
                    $open_invoice->payed = $payed->total;
                    $open_invoice->balance = $payed->total - $open_invoice->total;
                } else {
                    $open_invoice->payed = 0;
                    $open_invoice->balance = $open_invoice->total;
                }
            }
        }

        if (!empty($open_invoices)) {
            echo json_encode(array("result" => true, "data" => $open_invoices));
        } else {
            echo json_encode(array("result" => false));
        }
    }

    public function ConnectInvoiceAndPayment()
    {

        $data       = (object)$_POST;
        $payment    = $this->general_model->getRowById('customer_invoices_payments', 'payment_id', $data->payment_id);
        $invoice    = $this->general_model->getRowById('customer_invoices', 'invoice_id', $data->invoice_id);

        if (!empty($payment->payment_for)) {
            $payment_for    = explode(",", $payment->payment_for);
            $payment_for[]  = $data->invoice_id;
            $payment_fors   = implode(",", $payment_for);
        } else {
            $payment_fors   = $data->invoice_id;
        }

        if (!empty($invoice->payments_id)) {
            $payments_id    = explode(",", $payment->payments_id);
            $payments_id[]  = $data->payment_id;
            $payments_ids   = implode(",", $payments_id);
        } else {
            $payments_ids   = $data->payment_id;
        }

        $connect_data = array(
            'invoice_id'      => $data->invoice_id,
            'payment_id'      => $data->payment_id,
            'total'           => $data->total,
            'dateCreation'    => date('Y-m-d H:i:s')
        );

        $connect_id = $this->general_model->insertRow('customer_invoices_payments_connect', $connect_data);

        $update_invoice = $this->general_model->updateRowById('customer_invoices', 'invoice_id', $data->invoice_id, array('payments_id' => $payments_ids, 'lastUpdate' => date('Y-m-d H:i:s')));
        $update_payment = $this->general_model->updateRowById('customer_invoices_payments', 'payment_id', $data->payment_id, array('payment_for' => $payment_fors, 'lastUpdate' => date('Y-m-d H:i:s')));

        if (!empty($connect_id)) {
            echo json_encode(array("result" => true));
        } else {
            echo json_encode(array("result" => false));
        }
    }

    // public function CancelInvoiceDocument()
    // {
    //     $data = (object)$_POST;
    //     //debug($data);
    //     $invoice = $this->general_model->getRowById('customer_invoices', 'invoice_id', $data->invoice_id);
    //     $invoice_total = ($invoice->total) * -1;
    //     $customer = $this->general_model->getRowById('customers', 'customerId', $invoice->customerId);
    //     $MainInvoiceData = array(
    //         'invoice_type'    => $invoice_type,
    //         'total'           => $invoice_total,
    //         'invoice_date'    => date('Y-m-d H:i:s'),
    //         'customerId'      => $invoice->customerId,
    //         'cancel_id'       => $tranzilla_invoice_id,
    //         'dateCreation'    => date('Y-m-d H:i:s'),
    //         'lastUpdate'      => date('Y-m-d H:i:s')
    //     );
    //     $invoice_id = $this->general_model->insertRow('customer_invoices', $MainInvoiceData);
    //     if (!empty($invoice_id)) {
    //        $items      = $this->db->query("SELECT * FROM `customer_invoice_items` WHERE `invoice_id` = '$data->invoice_id'")->result();
    //         foreach ($items as $item) {
    //             $invoiceItemsData = array(
    //                 'invoice_id'      => $invoice_id,
    //                 'item_title'      => $item->item_title,
    //                 'item_price'      => ($item->item_price) * -1,
    //                 'customerId'     => $customer->customerId,
    //                 'dateCreation'    => date('Y-m-d H:i:s'),
    //                 'lastUpdate'      => date('Y-m-d H:i:s')
    //             );

    //             $item_id = $this->general_model->insertRow('customer_invoice_items', $invoiceItemsData);

    //             $apiItems[] = array(
    //                 "code"          => "1",
    //                 "name"          => $item->item_title,
    //                 "type"          => "I",
    //                 "units_number"  => 1,
    //                 "unit_type"     => 1,
    //                 "unit_price"    => $item->item_price,
    //                 "price_type"    => "N",
    //                 "amount"        => $item->item_price
    //             );
    //         }
    //         if ($invoice_type == 4) {
    //             $payments   = $this->db->query("SELECT * FROM `customer_invoices_payments` WHERE `invoice_id` = '$data->invoice_id'")->result();
    //             foreach ($payments as $payment) {
    //                 $invoicePaymentData = array(
    //                     'invoice_id'        => $invoice_id,
    //                     'customerId'       => $invoice->customerId,
    //                     'payment_type'      => $payment->payment_type,
    //                     'payment_box'       => $payment->payment_box,
    //                     'payment_date'      => date('Y-m-d', strtotime(str_replace('/', '-', $payment->payment_date))),
    //                     'bank_visa'         => $payment->bank_visa,
    //                     'branch_digits'     => $payment->branch_digits,
    //                     'account_card'      => $payment->account_card,
    //                     'reference_id'      => $payment->reference_id,
    //                     'total'             => ($payment->total) * -1,
    //                     'dateCreation'      => date('Y-m-d H:i:s'),
    //                     'lastUpdate'        => date('Y-m-d H:i:s')
    //                 );

    //                 $payment_id = $this->general_model->insertRow('customer_invoices_payments', $invoicePaymentData);
    //             }
    //         }
    //         echo json_encode(array("result" => true));
    //     } else {
    //         echo json_encode(array("result" => false));
    //     }
    // }

    public function getCustomerDetailsforInvoice()
    {
        if (!empty($_POST) && isset($_POST['customerId'])) {
            $customerId         = $_POST['customerId'];
            $customer           = $this->db->query("SELECT `customerId`, `phoneNumber`, `address`, `email`, `invID`, `credits` FROM `customers` WHERE `customerId` = '$customerId' ")->row();
            $open_invoices      = $this->db->query("SELECT `invoice_id`, `total` FROM `customer_invoices` WHERE `customerId` = '$customerId' AND `tranzilla_invoice_id` = 0 AND `payments_id` = '' ")->result();
            if (!empty($customer)) {
                $customer->result   = true;
                $customer->credits = number_format($customer->credits, 2);
                $customer->invoices = $open_invoices;
                echo json_encode($customer);
            } else {
                echo json_encode(array("result" => false));
            }
        } else {
            echo json_encode(array("result" => false));
        }
    }

    public function getSupplierDetailsforInvoice()
    {
        if (!empty($_POST) && isset($_POST['supplier_id'])) {
            $supplier_id        = $_POST['supplier_id'];
            $supplier           = $this->db->query("SELECT `supplier_id`, `name`, `type`, `domain`, `vat_number`, `email`, `phone_number`, `address`, `main_contact`, `program_name`,`credit` FROM `suppliers` WHERE `supplier_id` = '$supplier_id' ")->row();
            if (!empty($supplier)) {
                $supplier->result   = true;
                echo json_encode($supplier);
            } else {
                echo json_encode(array("result" => false));
            }
        } else {
            echo json_encode(array("result" => false));
        }
    }

    public function cancelPaymentBox()
    {
        $payment_id     = $_POST['payment_id'];
        $org_payment    = $this->general_model->getRowById('customer_invoices_payments', 'payment_id', $payment_id);
        $cancel_text    = ' ביטול תשלום מספר: ';
        if ($org_payment->is_converted == 0) {
            if ($org_payment->convert_from != 0) {
                $paymentData = array(
                    'invoice_id'            => $org_payment->invoice_id,
                    'customerId'           => $org_payment->customerId,
                    'payment_type'          => $org_payment->payment_type,
                    'payment_box'           => $org_payment->convert_from,
                    'payment_date'          => $org_payment->payment_date,
                    'bank_visa'             => $org_payment->bank_visa,
                    'branch_digits'         => $org_payment->branch_digits,
                    'account_card'          => $org_payment->account_card,
                    'reference_id'          => $org_payment->reference_id,
                    'total'                 => $org_payment->total,
                    'notes2'                => $cancel_text . $payment_id,
                    'is_receipt'            => $org_payment->is_receipt,
                    'receipt_number'        => $org_payment->receipt_number,
                    'payment_for'           => $org_payment->payment_for,
                    'dateCreation'          => date('Y-m-d H:i:s'),
                    'lastUpdate'            => date('Y-m-d H:i:s')
                );
                $addPaymentOldBox = $this->general_model->insertRow('customer_invoices_payments', $paymentData);
            }

            $invoicePaymentData = array(
                'invoice_id'            => $org_payment->invoice_id,
                'customerId'           => $org_payment->customerId,
                'payment_type'          => $org_payment->payment_type,
                'payment_box'           => $org_payment->payment_box,
                'payment_date'          => $org_payment->payment_date,
                'bank_visa'             => $org_payment->bank_visa,
                'branch_digits'         => $org_payment->branch_digits,
                'account_card'          => $org_payment->account_card,
                'reference_id'          => $org_payment->reference_id,
                'total'                 => $org_payment->total * -1,
                'notes2'                => $cancel_text . $payment_id,
                'is_receipt'            => $org_payment->is_receipt,
                'receipt_number'        => $org_payment->receipt_number,
                'payment_for'           => $org_payment->payment_for,
                'dateCreation'          => date('Y-m-d H:i:s'),
                'lastUpdate'            => date('Y-m-d H:i:s')
            );
            $addPayment = $this->general_model->insertRow('customer_invoices_payments', $invoicePaymentData);
            if (!empty($addPayment)) {
                echo json_encode(array("result" => true));
            } else {
                echo json_encode(array("result" => false));
            }
        } else {
            echo json_encode(array("result" => false));
        }
    }

    public function getItems()
    {
        // debug($_GET);
        if (isset($_GET['term']) && !empty($_GET['term'])) {
            $term = $_GET['term'];
            $result = array();
            $product = $this->db->query("SELECT `id`, `name`, `code` as `text`, `price` 
                                         FROM `products` 
                                         WHERE `code` LIKE '%$term%'  
                                         OR `name` LIKE '%$term%'")->result();
            if (!empty($product)) {
                foreach ($product as $prod) {
                    $prod->text .= " - $prod->name";
                }
                $result['results'] = $product;
                echo json_encode($result);
            }
        } else {
            $result = array();
            $latest_products = $this->db->query("SELECT `product_id` FROM `customer_invoice_items` GROUP BY `product_id` ORDER BY item_id DESC LIMIT 5 ")->result();
            if(!empty($latest_products)){
                foreach( $latest_products as $current_product ){
                    $product = $this->db->query("SELECT `id`, `name`, `code` as `text`, `price` 
                                                 FROM `products` 
                                                 WHERE `id` = '$current_product->product_id' ")->row();
                    if (!empty($product)) {
                        $product->text .= " - $product->name";
                        $result['results'][] = $product;
                    }
                }
                echo json_encode($result);
            }else{
                $data = array();
                $data['results'] = array();
            }
        }
    }
    public function getbankDetails()
    {
        $data = array();
        $id = $_POST['id'];
        if (is_numeric($id)) {
            $bank_name = $this->db->query("SELECT `bank_name` as name FROM `banks_codes` WHERE `bank_code` = $id ")->row();
            if (!empty($bank_name)) {
                $data["name"] = $bank_name->name;
                $data["result"] = true;
                echo json_encode($data);
            } else {
                $data["result"] = false;
                echo json_encode($data);
            }
        } else {
            $data["result"] = false;
            echo json_encode($data);
        }
    }
    public function getbranchDetails()
    {
        $data = array();
        $id = $_POST['id'];
        $bank_id = $_POST['bank_id'];
        if (is_numeric($id) && is_numeric($bank_id)) {
            $branch_name = $this->db->query("SELECT `branch_name` as name FROM `branch_codes` WHERE `bank_code` = $bank_id AND `branch_code` = $id")->row();
            if (!empty($branch_name)) {
                $data["name"] = $branch_name->name;
                $data["result"] = true;

                echo json_encode($data);
            } else {
                $data["result"] = false;
                echo json_encode($data);
            }
        } else {
            $data["result"] = false;
            echo json_encode($data);
        }
    }

    public function getCustomersAjax()
    {
        if (isset($_GET['term']) && !empty($_GET['term'])) {
            $term = $_GET['term'];
            $result = array();
            $customer = $this->db->query("SELECT `customerId` as id, `customerName` as `text`
                                         FROM `customers` 
                                         WHERE `customerName` LIKE '%$term%'
                                         OR `customerId` LIKE '%$term%'
                                         OR `phoneNumber` LIKE '%$term%'                                       
                                          ")->result();
            if (!empty($customer)) {
                $result['results'] = $customer;
                echo json_encode($result);
            }
        } else {
            $data = array();
            $data['results'] = array();
        }
    }

    public function getInvoicesAjax()
    {
        if (isset($_GET['term']) && !empty($_GET['term'])) {
            $term = $_GET['term'];
            $result = array();
            $invoice = $this->db->query("SELECT `invoice_id` as id
                                         FROM `customer_invoices` 
                                         WHERE `invoice_id` LIKE '%$term%'                                  
                                          ")->result();
            if (!empty($invoice)) {
                $result['results'] = $invoice;
                echo json_encode($result);
            }
        } else {
            $data = array();
            $data['results'] = array();
        }
    }

    public function getItemPrice()
    {
        $data = array();
        if (isset($_POST['id']) && !empty($_POST['id'])) {
            $id = $_POST['id'];
            $this->db->select('id, name as text, price, code');
            $this->db->from('products');
            $this->db->where('id', $id);
            $query = $this->db->get()->row();
            // debug($query);
            if (!empty($query)) {
                $data['price'] = $query->price;
                $data['product_id'] = $query->id;
                $data['name'] = $query->text;
                $data['code'] = $query->code;
            } else {
                $data['price'] = 0;
            }
        } else {
            $data = array();
            $data['price'] = 0;
        }
        echo json_encode($data);
    }
}
