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

class Suppliers extends Admin_Controller
{

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

    public function index()
    {

        $suppliers      = $this->db->query("SELECT * FROM `suppliers`")->result();
        $suppliers_tags = $this->db->query("SELECT * FROM `suppliers_tags`")->result();
 
        foreach ($suppliers as $supplier) {
            $types = explode(",", $supplier->type);
            $supplier->type = $types;
        }

        $this->template
            ->set('view', 'admin/suppliers/index')
            ->set('suppliers', $suppliers)
            ->set('suppliers_tags', $suppliers_tags)
            ->render();
    }

    public function addSupplier()
    {

        $data   = (object)$_POST;
        $types  = (!empty($data->type)) ? implode(",", $data->type) : '';
        // $cronDays = implode(',', $_POST['days']);

        $supplier_data = array(
            'name'          => $data->name,
            'type'          => $types,
            'domain'        => $data->domain,
            'vat_number'    => $data->vat_number,
            'email'         => $data->email,
            'phone_number'  => $data->phone_number,
            'address'       => $data->address,
            'main_contact'  => $data->main_contact,
            'program_name'  => $data->program_name
            // 'cron_days'     => $cronDays
        );

        $result = $this->general_model->insertRow('suppliers', $supplier_data);

        $get_tags = $this->db->query("SELECT * FROM `suppliers_tags` WHERE `name` LIKE '$data->domain' ")->row();
        if (empty($get_tags)) {
            $suppliers_tags_data = array(
                'name'  => $data->domain
            );
            $result = $this->general_model->insertRow('suppliers_tags', $suppliers_tags_data);
        }

        redirect('admin/suppliers/', 'refresh');
    }

    public function suppliersPrice($customerId)
    {

        $whereInvoice = $wherePayment = $join = $limit = "";
        $customerId = intval($this->uri->segment(4));
        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'));
        }
        $whereInvoice = " AND `invoice_date` BETWEEN '$date_from' AND '$date_to'";
        $wherePayment = " AND `payment_date` BETWEEN '$date_from' AND '$date_to'";

        $invoices = $this->db->query("SELECT `invoice_id` as `id`, `total`, `invoice_date` as `date`, `customerId`, `dateCreation` , `reference_id`
                                        FROM `customer_invoices`
                                        WHERE `customerId`= '$customerId'
                                        $whereInvoice
                                        ORDER BY `invoice_date` DESC")->result();
        $payments = $this->db->query("SELECT `payment_id` as `id`, `total`, `payment_date` as `date`, `customerId`, `dateCreation` , `reference_id`
                                        FROM `customer_invoices_payments`
                                        WHERE `customerId` = '$customerId'
                                        $wherePayment
                                        ORDER BY `payment_date` DESC")->result();

        $data = array();
        foreach ($invoices as $invoice) {
            $invoice->type = 'invoice';

            $data[] = $invoice;
        }
        foreach ($payments as $payment) {
            $payment->type = 'payment';
            $data[] = $payment;
        }

        function sortFunction($a, $b)
        {
            return strtotime($a->date) - strtotime($b->date);
        }
        usort($data, "sortFunction");
        $date_from_balance  = date('1970-01-01 00:00:00');
        $date_to_balance    = date('Y-m-d 23:59:59', strtotime('-1 day' . $date_from));
        $whereInvoice_balance = " AND `invoice_date` BETWEEN '$date_from_balance' AND '$date_to_balance'";
        $wherePayment_balance = " AND `payment_date` BETWEEN '$date_from_balance' AND '$date_to_balance'";

        $invoices_sum = $this->db->query("SELECT SUM(total) as total
                                        FROM `customer_invoices`
                                        WHERE `customerId`= '$customerId'
                                        $whereInvoice_balance
                                        ORDER BY `invoice_date` DESC")->row();
        $payments_sum = $this->db->query("SELECT SUM(total) as total
                                        FROM `customer_invoices_payments`
                                        WHERE `customerId` = '$customerId'
                                        $wherePayment_balance
                                        ORDER BY `payment_date` DESC")->row();
        $sum = 0;
        if (!empty($invoices_sum) && isset($invoices_sum->total)) {
            $sum -= $invoices_sum->total;
        }
        if (!empty($payments_sum) && isset($payments_sum->total)) {
            $sum += $payments_sum->total;
        }

        $this->template
            ->set('view', 'admin/suppliers/suppliersPrice')
            ->set("data", $data)
            ->set('date_from', $date_from)
            ->set('date_to', $date_to)
            ->set('sum', $sum)
            ->render();
    }

    public function view()
    {

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

        if (empty($supplier_id) || $supplier_id == FALSE) {
            redirect('admin/suppliers/', 'refresh');
        } else {
            $supplier           = $this->db->query("SELECT * FROM `suppliers` WHERE `supplier_id` = '$supplier_id'")->row();
            $suppliers_tags     = $this->db->query("SELECT * FROM `suppliers_tags`")->result();
        }
        $products = $this->db->query("SELECT * FROM `products` WHERE `type` = 2")->result();
        $cron_job = $this->db->query("SELECT * FROM `cron_job` WHERE `supplier_id` = '$supplier_id' AND `is_deleted` =0")->result();
        // debug($cron_job);
        $this->template
            ->set('view', 'admin/suppliers/view')
            ->set('supplier', $supplier)
            ->set('products', $products)
            ->set('cron_job', $cron_job)
            ->set('suppliers_tags', $suppliers_tags)

            ->render();
    }

    public function payments()
    {

        $supplier_id    = $this->uri->segment(4);
        $payments_type  = $this->uri->segment(5);

        if (empty($supplier_id) || $supplier_id == FALSE || empty($payments_type) || $payments_type == FALSE) {
            redirect('admin/suppliers/', 'refresh');
        } else {

            if (isset($_POST['from']) && $_POST['from'] != '') {
                $from           = date('Y-m-d', strtotime(str_replace('/', '-', $_POST['from']))) . ' 00:00:00';
                $fromBalance    = date('Y-m-d 23:59:59', strtotime("-1 day", strtotime("$from")));
            } else {
                $from           = date('Y-m-d 23:59:59', strtotime("-2 day"));
                $fromBalance    = date('Y-m-d 23:59:59', strtotime("-2 day"));
            }
            if (isset($_POST['to']) && $_POST['to'] != '') {
                $to     = date('Y-m-d', strtotime(str_replace('/', '-', $_POST['to']))) . ' 23:59:59';
            } else {
                $to     = date('Y-m-d 23:59:59', strtotime('now'));
            }

            $balance            = 0;
            $to_sum_before      = "01/01/1950";
            $to_sum_beforeQ     = str_replace('/', '-', $to_sum_before);
            $balance_from_date  = date('Y-m-d 00:00:00', strtotime($to_sum_beforeQ));

            $supplier           = $this->db->query("SELECT * FROM `suppliers` WHERE `supplier_id` = $supplier_id")->row();
            $supplier_invoices  = $this->db->query("SELECT * FROM `suppliers_invoices` WHERE `supplier_id` = $supplier_id AND `dateCreation` BETWEEN '$from' AND '$to'")->result();
            $suppliers_tags     = $this->db->query("SELECT * FROM `suppliers_tags`")->result();

            if (!empty($supplier->program_name)) {

                $supplier_name      = strtolower($supplier->program_name);

                if ($payments_type == 2) {
                    $supplier_used_details  = $this->db->query("SELECT 	`company_suppliers_records`.`id`,
    	                                                                `company_suppliers_records`.`order_date`,
    	                                                                `company_suppliers_records`.`phone`,
    	                                                                `company_suppliers_records`.`price_after`,
                                                                        `company_suppliers_records`.`company`,
                                                                        `company_suppliers_records`.`order_id`,
                                                                        `prepaid_orders`.`api_result`
                                                                FROM `company_suppliers_records`
                                                                LEFT JOIN `prepaid_orders`
                                                                ON `prepaid_orders`.`order_id` = `company_suppliers_records`.`order_id`
                                                                WHERE `supplier` = '$supplier_name'
                                                                AND `order_date` BETWEEN '$from' AND '$to' ORDER BY `order_id` ASC ")->result();

                    $companies_count  = reindex_by_key($this->db->query("SELECT COUNT(*) AS Count, `company`, SUM(`price_after`) AS total
                                                                FROM `company_suppliers_records`
                                                                WHERE `supplier` = '$supplier_name'
                                                                AND `order_date` BETWEEN '$from' AND '$to'
                                                                GROUP BY `company` ")->result(), 'company');

                    $balance_supplier_records  = $this->db->query("SELECT SUM(`price_after`) AS `Total_Lines`
                                                                    FROM `company_suppliers_records`
                                                                    WHERE `supplier` = '$supplier_name'
                                                                    AND `order_date` BETWEEN '$balance_from_date' AND '$fromBalance'")->row();

                    $supplier_invoices_balance  = $this->db->query("SELECT SUM(`invoice_total`) AS `Invoice_Total`
                                                                    FROM `suppliers_invoices`
                                                                    WHERE `supplier_id` = $supplier_id
                                                                    AND `invoice_date` BETWEEN '$balance_from_date' AND '$fromBalance'")->row();

                    foreach ($supplier_invoices as $invoice) {
                        $supplier_used_details[]  = (object)array(
                            'id'             => $invoice->invoice_id,
                            'order_date'     => $invoice->invoice_date,
                            'invoice'        => $invoice->invoice_total,
                            'price_after'    => 0,
                            'order_id'       => '',
                            'phone'          => '',
                            'company'        => 'Invoice',
                            'api_result'     => ''
                        );
                    }

                    function compareDates($date1, $date2)
                    {
                        return strtotime($date1->order_date) - strtotime($date2->order_date);
                    }

                    usort($supplier_used_details, 'compareDates');

                    $balance = $supplier_invoices_balance->Invoice_Total - $balance_supplier_records->Total_Lines;
                }

                if ($payments_type == 4) {

                    $balance_to_date  = date('Y-m-d 00:00:00', strtotime('2018-01-01'));

                    $supplier_used_details  = $this->db->query("SELECT *, `payment_date` AS `order_date`,
    	                                                        `payment_id` AS `order_id`,
    	                                                        NULL as `phone`,
    	                                                        NULL as `company`,
    	                                                        NULL as `api_result`,
    	                                                        `total` as `price_after`,
    	                                                        NULL as `id`
    	                                                        FROM `customer_invoices_payments`
                                                                WHERE `payment_date` BETWEEN '$from' AND '$to'
                                                                AND `payment_box` = '18'
                                                                AND `main_type` = 3
                                                                AND `customer_id` != 0
                                                                AND `customer_id` != ''
                                                                ORDER BY `payment_id` ASC ")->result();

                    $companies_count  = array();

                    $balance_supplier_records  = $this->db->query("SELECT SUM(`total`) AS `Total_Lines`
                                                                    FROM `customer_invoices_payments`
                                                                    WHERE `payment_box` = '18'
                                                                    AND `main_type` = 3
                                                                    AND `customer_id` != 0
                                                                    AND `customer_id` != ''
                                                                    AND `payment_date` BETWEEN '$balance_from_date' AND '$fromBalance' ")->row();

                    $supplier_invoices_balance  = $this->db->query("SELECT SUM(`invoice_total`) AS `Invoice_Total`
                                                                    FROM `suppliers_invoices`
                                                                    WHERE `supplier_id` = '$supplier_id'
                                                                    AND `invoice_date` BETWEEN '$balance_from_date' AND '$fromBalance'")->row();

                    foreach ($supplier_invoices as $invoice) {
                        $supplier_used_details[]  = (object)array(
                            'id'             => $invoice->invoice_id,
                            'order_date'     => $invoice->invoice_date,
                            'invoice'        => $invoice->invoice_total,
                            'price_after'    => 0,
                            'order_id'       => '',
                            'phone'          => '',
                            'company'        => 'Invoice',
                            'api_result'     => ''
                        );
                    }

                    function compareDates($date1, $date2)
                    {
                        return strtotime($date1->order_date) - strtotime($date2->order_date);
                    }

                    usort($supplier_used_details, 'compareDates');

                    $balance = $supplier_invoices_balance->Invoice_Total - $balance_supplier_records->Total_Lines;
                }
            } else {
                redirect('admin/suppliers/', 'refresh');
            }
        }

        $this->template
            ->set('view', 'admin/suppliers/payments')
            ->set('supplier', $supplier)
            ->set('suppliers_tags', $suppliers_tags)
            ->set('supplier_used_details', $supplier_used_details)
            ->set('companies_count', $companies_count)
            ->set('from', $from)
            ->set('to', $to)
            ->set('supplier_invoices', $supplier_invoices)
            ->set('balance', $balance)
            ->set('balance_supplier_records', $balance_supplier_records)
            ->set('supplier_invoices_balance', $supplier_invoices_balance)
            ->render();
    }

    public function EditSupplier()
    {

        $data   = (object)$_POST;
        $types  = implode(",", $data->type);
        $cronDays = implode(',', $_POST['days']);

        $supplier_data = array(
            'name'          => $data->name,
            'type'          => $types,
            'domain'        => $data->domain,
            'vat_number'    => $data->vat_number,
            'email'         => $data->email,
            'phone_number'  => $data->phone_number,
            'address'       => $data->address,
            'main_contact'  => $data->main_contact,
            'cron_days'     => $cronDays
        );

        $tempBlock = $this->general_model->updateRowById('suppliers', 'supplier_id', $data->supplier_id, $supplier_data);

        redirect("admin/suppliers/view/$data->supplier_id", 'refresh');
    }

    public function updatePayment()
    {

        $data = (object)$_POST;

        if ($data->type == 'payment') {
            $update_data = $this->general_model->updateRowById('company_suppliers_records', 'id', $data->id, array('price_after' => $data->amount));
        }

        if ($data->type == 'payment') {
            $update_data = $this->general_model->updateRowById('suppliers_invoices', 'invoice_id', $data->id, array('invoice_total' => $data->amount));
        }

        if (!empty($update_data)) {
            echo json_encode(array("result" => true));
        } else {
            echo json_encode(array("result" => false));
        }
    }
    public function updateInvoice()
    {
        $data   = (object)$_POST;
        $supplier_id = intval($this->uri->segment(4));
        $id = $data->id;
        $cron_job = $this->db->query("SELECT * FROM `cron_job` WHERE `supplier_id` = $supplier_id AND `id` = $id AND `is_deleted` =0")->row();
        // debug($cron_job);
        $cron = implode(',', $_POST['days']);
        $update_data = array(
            // 'id'            => $id, 
            'product_id'    => $data->product_id,
            'days'          => $cron,
            'total'         => $data->total,
            'lastUpdate'    => date('Y-m-d H:i:s')
        );
        // debug($cron_job);
        $tempBlock = $this->general_model->updateRowById('cron_job', 'id', $id, $update_data);
        // debug($update_data);
        redirect("admin/suppliers/view/$supplier_id", 'refresh');
    }
    public function deleteRow()
    {
        $data   = (object)$_POST;
        $supplier_id = intval($this->uri->segment(4));
        $id = $data->id;
        // $cron_job = $this->db->query("SELECT * FROM `cron_job` WHERE `supplier_id` = $supplier_id AND `id` = $id AND `is_deleted` =0")->row();
        $delete_data = array(
            'is_deleted' => 1,
            'lastUpdate' =>date('Y-m-d H:i:s')
        );
        $delete = $this->general_model->updateRowById('cron_job', 'id', $id, $delete_data);
        redirect("admin/suppliers/view/$supplier_id", 'refresh');

    }

}
