<?php

class OrderDisplay {

    /**
     * @var array Holds an array of data
     */
    protected $info = array();

    /**
     * @var bool Will be used to check whether the organization is added or not. TRUE when the organization is
     *      successfully created. Default value is FALSE
     */
    private $orgAdded = false;

    /**
     * @var obj Holds the database adapter object
     */
    public $db;
    private $year_id;
    private $year_id_actual;
    public $stop_transaction_start_end = false;
    public $permissions;

    /**
     * The constructor will create an instant of the chosen database adapter (MySQL, MySQLi, etc)
     * and saves it in a private variable $db as an object to be used throughout the class.
     *
     * @author  Taha Sayyad <info@trustotech.com>
     * @uses DBConnectorFactory::loadDriver() to load the database adapter
     */
    public function __construct() {
        $this->db = DBConnectorFactory::loadDriver();
    }
    public function setdata(array $data) {
        $this->info = $data;
        return $this;
    }

    public function get_orders_to_display($printer_ids) {
        $printer_ids_arr = empty($printer_ids) ? array() : explode(",", $printer_ids);
        $data = array();
        $invoice_type_arr = [1 => 'Invoice', 2 => 'Delivery', 3 => 'Park', 4 => 'Table', 5 => 'Order', 6 => 'Takeaway'];
        $invoice_ids = array();
        $query_main = $this->db->query('select inv.date_created,
                                               inv.invoice_type,
                                               users.User_Full_Name,
                                               tab.table_name,
                                               concat_ws("",inv.invoice_prefix,inv.Invoice_ID) as inv_nb,
                                               inv.Delivery_Time,
                                               inv.Invoice_ID_Auto
                                    from tbl_invoices inv 
                                        inner join tbl_common_users users on users.User_ID = inv.created_logged_id
                                        left join tbl_table tab on tab.table_id =  inv.table_id 
                                    where inv.order_kitchen_status = 0 and is_pos = 1
                                    order by inv.date_created desc limit 50
                                    ');
        while ($row = $this->db->assoc($query_main)) {
            $row['invoice_type_name'] = $invoice_type_arr[$row['invoice_type']];
            $row['current_time_ago'] = self::timeago($row['date_created']);
            $row['details'] = array();
            $data[$row['Invoice_ID_Auto']] = $row;
            $invoice_ids[] = $row['Invoice_ID_Auto'];
        }
        if (!empty($invoice_ids)) {
            $entry_ids_array = array();
            $query_details = $this->db->query('select prod.Product_Name,
                                                  details.Entery_ID,
                                                  details.Product_Quantity,
                                                  details.product_description,
                                                  details.Item_Quantity_Current,
                                                  details.Invoice_ID_Auto,
                                                  details.details_kitchen_status,
                                                  prod.printer_id,
                                                  uom.UOM_Name,
                                                  ((details.Product_Quantity- details.done_qty)/conv.conversion_amount) as not_done_qty
                                           from tbl_invoice_products_details details
                                           inner join tbl_stock_products prod on prod.Product_ID = details.Product_ID
                                           inner join tbl_stock_uom uom on uom.UOM_ID = details.UOM_ID
                                           inner join tbl_uom_conversions conv on conv.Product_ID = details.Product_ID and  conv.uom_from =  details.UOM_ID
                                           where Invoice_ID_Auto in (' . implode(",", $invoice_ids) . ')
                                           and details.details_kitchen_status = 0
                                       ');
            while ($row = $this->db->assoc($query_details)) {
                $current_printers = explode(",", $row['printer_id']);
                $row['not_done_qty'] = round($row['not_done_qty'], 2);
                $row['criteria'] = array();
                $intersection = array_intersect($printer_ids_arr, $current_printers);
                if (empty($printer_ids_arr) || !empty($intersection)) {
                    $data[$row['Invoice_ID_Auto']]['details'][$row['Entery_ID']] = $row;
                    $entry_ids_array[] = $row['Entery_ID'];
                }
            }
            if (!empty($entry_ids_array)) {
                $entry_ids_str = implode(',', $entry_ids_array);
                $criteria_details_query = $this->db->query('select  inv_details.Entery_ID,
                                                            crit_details.criteria_detail_id,
                                                            crit_details.criteria_detail_name, 
                                                            inv_details.criteria_price, 
                                                            inv_details.criteria_note,
                                                            crit_details.criteria_id,
                                                            details.Invoice_ID_Auto
                                                    from tbl_invoice_product_criteria inv_details
                                                    inner join tbl_invoice_products_details details
                                                    on details.Entery_ID = inv_details.Entery_ID
                                                    inner join tbl_product_criteria_detail crit_details
                                                    using(criteria_detail_id)
                                                    where inv_details.Entery_ID IN (' . $entry_ids_str . ')
                                                    ');
                while ($row = $this->db->assoc($criteria_details_query)) {
                    $data[$row['Invoice_ID_Auto']]['details'][$row['Entery_ID']]['criteria'][] = $row['criteria_detail_name'];
                }
            }
        }
        //        echo '<pre>';
        //        print_r($data);
        $current_data = array();
        foreach ($data as $key => $row) {
            if (!empty($row['details']))
                $current_data[$key] = $row;
        }
        return $current_data;
    }


    public function timeago($date) {
        $timestamp = strtotime($date);

        $strTime = array("sec", "min", "hr", "day", "month", "year");
        $length = array("60", "60", "24", "30", "12", "10");

        $currentTime = time();
        if ($currentTime >= $timestamp) {
            $diff = time() - $timestamp;
            for ($i = 0; $diff >= $length[$i] && $i < count($length) - 1; $i++) {
                $diff = $diff / $length[$i];
            }

            $diff = round($diff);
            return $diff . " " . $strTime[$i] . ($diff == 1 ? '' : 's') . " ago ";
        }
    }

    public function approve_order() {
        $this->db->query('START TRANSACTION');
        $this->db->prepare_Stmt('update tbl_invoices set order_kitchen_status = 1 where Invoice_ID_Auto=?', [&$this->info['Invoice_ID_Auto']]);
        $this->db->prepare_Stmt('update tbl_invoice_products_details set details_kitchen_status = 1,done_qty = Product_Quantity where Invoice_ID_Auto=?', [&$this->info['Invoice_ID_Auto']]);
        $error = $this->db->error();
        if (empty($error)) {
            $this->db->query("COMMIT");
        } else {
            $this->db->query("ROLLBACK");
        }
        return array_unique($error);
    }

    public function approve_details() {
        $this->db->query('START TRANSACTION');
        $this->db->prepare_Stmt('update tbl_invoice_products_details set details_kitchen_status = 1,done_qty = Product_Quantity  where Entery_ID=?', [&$this->info['Entery_ID']]);
        //check if all details are done then mark whole invoice as done
        $query_details = $this->db->query('select Entery_ID from tbl_invoice_products_details where details_kitchen_status = 0 and Invoice_ID_Auto = ? limit 1', [&$this->info['Invoice_ID_Auto']]);
        $rows_count = $this->db->rowsno($query_details);
        $is_removed = 0;
        if ($rows_count == 0) {
            $this->db->prepare_Stmt('update tbl_invoices set order_kitchen_status = 1 where Invoice_ID_Auto=?', [&$this->info['Invoice_ID_Auto']]);
            $is_removed = 1;
        }
        $error = $this->db->error();
        if (empty($error)) {
            $this->db->query("COMMIT");
        } else {
            $this->db->query("ROLLBACK");
        }
        return [array_unique($error), $is_removed];
    }

}
