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

class Shipping extends Admin_Controller
{

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

    public function index()
    {   
        $shipping  = reindex_by_key($this->db->query("SELECT * FROM `customer_shipping`")->result(), 'shipping_id');
        $customers = reindex_by_key($this->db->query("SELECT * FROM `customers`")->result(), 'customerId');
        $warehouse = reindex_by_key($this->db->query("SELECT * FROM `warehouse`")->result(), 'ID');
        $shippingId = $this->db->query("SELECT MAX(shipping_id) AS LastID FROM `customer_shipping`")->row();
        // $shippingId = if(!empty($invoiceId->LastID )): $invoiceId->LastID  + 1 ? 1;


        $this->template
            ->set('view', 'admin/shipping/index')
            ->set('shipping', $shipping)
            ->set('customers', $customers)
            ->set('warehouse', $warehouse)
            // ->set('invoiceId', $invoiceId)
            ->render();
    }

    public function view()
	{
		$id = intval($this->uri->segment(4));
		$shipping = $this->db->query("SELECT * FROM `customer_shipping` WHERE shipping_id = $id")->row();
		$customerId = $shipping->customerId;
		$customer = $this->db->query("SELECT * FROM `customers` WHERE customerId = $customerId")->row();
		$shipping_items  = $this->db->query("SELECT * FROM `customer_shipping_items` WHERE shipping_id = $id")->result();


		$this->template
			->set('view', 'admin/shipping/view')
			->set('shipping_items', $shipping_items)
			->set('shipping', $shipping)
			->set('customer', $customer)
			->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 createShippingOnly()
    {
        $data = (object)$_POST;
        $items     = (object)$data->items;
        $date_invoice = str_replace("/", "-", $data->invoice_date);
        $finall_total = 0;
        if (!empty($items) && isset($items)) {
            $shipping_id =   getCustomerNewShippingNo();
            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(
                    'shipping_id'   => $shipping_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],
                    'shipping_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_shipping_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(
                'shipping_type'   => 2,
                'total'           => $data->total,
                'shipping_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_shipping', $MainInvoiceData);




            redirect("admin/shipping", 'refresh');
        }
        redirect("admin/shipping", 'refresh');
    }

    // ajax functions 
    public function getShippingData()
    {
        $id = $_POST['id'];
        if (isset($id) && !empty($id)) {
            $shipping_data['shipping_info'] = $this->db->query("SELECT * FROM `customer_shipping` WHERE `shipping_id` = $id")->row();
            $customerName = getCustomerName($shipping_data['shipping_info']->customerId);
            $warehouseName = getWarehouseById($shipping_data['shipping_info']->warehouse_id);
            $shipping_data['shipping_info']->customerName = $customerName;
            $shipping_data['shipping_info']->warehouseName = $warehouseName;
            $customerId = $shipping_data['shipping_info']->customerId;

            $shipping_data['shipping_info']->invoice_date = date("d/m/Y", strtotime($shipping_data['shipping_info']->shipping_date));
            $customerCredit           = $this->db->query("SELECT `credits` FROM `customers` WHERE `customerId` = '$customerId'")->row();
            if (!empty($customerCredit)) {
                $shipping_data['shipping_info']->customerCredit = $customerCredit->credits;
            }
            $shipping_items = $this->db->query("SELECT * FROM `customer_shipping_items` WHERE `shipping_id` = $id")->result();
            // debug($shipping_items);
            $shipping_data['items'] = $shipping_items;

            foreach ($shipping_items as $item) {
                $item->item_title = getItemNameById($item->product_id);
                $item->code = $item->product_id;
                $item->item_instock = getWarehouseQuantity($shipping_data['shipping_info']->warehouse_id, $item->product_id);
            }


            // debug($invoice_items);

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

    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));
        // }
    }

    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 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 {
            $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);
    }
}
