<?php
defined('_JEXEC') or die('Restricted access');

/**
* @package OS CCK
* @copyright OrdaSoft.
* @author Andrey Kvasnevskiy(akbet@mail.ru),Roman Akoev (akoevroman@gmail.com)
* @link http://ordasoft.com/cck-content-construction-kit-for-joomla.html
* @description OrdaSoft Content Construction Kit
*/
use OrdaSoft\os_lib\os_libMain;
use OrdaSoft\os_lib\os_libPagination;

// if( !class_exists("os_libMain") ){
//     try{
//         $ss = new os_libMain();
//     }catch( Exception $e ){
//         die("Please reinstall OrdaSoft Joomla CCK Package!");
//     }
// }
class AdminOrders{

    static function showOrders(){
        global $db, $user, $option, $doc, $jConf, $app, $input;
        $db = new os_cckDb();
        if(!JFactory::getUser()->authorise('access_to_orders', 'com_os_cck')){
            $app->enqueueMessage("Access denied", 'error');
            return;
        }
        $search = '';
        $order = 'ORDER BY o.notreaded desc,o.id  DESC';
        
        $entity_id = $app->getUserStateFromRequest("entity_id{$option}", 'entity_id', '');
        $entities = array();
        $entities[] = array('value' => '', 'text' => cck_lang_text('COM_OS_CCK_OPTION_ALL_ENTITIES'));
        $query = "SELECT eid AS value, name AS text FROM #__os_cck_entity ORDER BY name ";
        $db->setQuery($query);
        $ent = $db->loadObjectList("value");
        if( count($ent) > 1 ){
          $entities = array_merge($entities, (array)$ent) ;
        } else{
          //$entities = $entities;
          //set $entity_id == "" - when we haven 1 entity, and yet one - old was war selected we removed, 
          //for clear old values from $entity_list filter and from $where array
          $entity_id = "";
        }
        $entity_list = JHTML::_('select.genericlist',$entities, 'entity_id', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $entity_id);
        
        $where = '';
        if(isset($_REQUEST['search']) || ($entity_id != '' && isset($ent[$entity_id]))){
            
            if(isset($_REQUEST['search'])) {
                $search = $_REQUEST['search'];
                $where = "WHERE o.user_email LIKE '%{$search}%' OR o.user_name LIKE '%{$search}%' OR o.id LIKE '%{$search}%'";
            }
            if ($entity_id != '' && isset($ent[$entity_id])) {
                if(stripos($where, 'WHERE')){
                    $where .= " AND eii.fk_eid ='{$entity_id}'";
                } else {
                    $where = "WHERE eii.fk_eid ='{$entity_id}'";
                }
            }
        }
        //var_dump($where); exit;
        $orderby = $input->get('order', 'ASC', '');
        if(isset($_GET['orderby']) && $_GET['orderby'] == 'user') {
            $order = 'ORDER BY o.user_name ' . $orderby;
        }elseif(isset($_GET['orderby']) && $_GET['orderby'] == 'email') {
            $order = 'ORDER BY o.user_email ' . $orderby;
        }elseif(isset($_GET['orderby']) && $_GET['orderby'] == 'status') {
            $order = "ORDER BY o.status " . $orderby;
        }elseif(isset($_GET['orderby']) && $_GET['orderby'] == 'order_date') {
            $order = "ORDER BY o.order_date " . $orderby;
        }elseif(isset($_GET['orderby']) && $_GET['orderby'] == 'id') {
            $order = "ORDER BY o.id " . $orderby;
        }elseif(isset($_GET['orderby']) && $_GET['orderby'] == 'title') {
            $order = "ORDER BY o.instance_title " . $orderby;
        }

        $limit = $app->getUserStateFromRequest("viewlistlimit", 'limit', $jConf->get("list_limit",10));
        $limitstart = $app->getUserStateFromRequest("view{$option}limitstart", 'limitstart', 0);

        $sql = "SELECT count(*)  ".
                " FROM #__os_cck_orders AS o ".
                " LEFT JOIN #__users AS u ".
                " ON o.fk_user_id = u.id ".
                " LEFT JOIN #__os_cck_entity_instance AS eii ".
               " ON o.fk_instance_id = eii.eiid ". $where ." ".$order;
        $db->setQuery($sql);
        $total = $db->loadResult();
        $limit = intval($limit);
        $pageNav = new os_libPagination($total, $limitstart, $limit);

        $sql = "SELECT u.id as userId, u.username, ".
           " o.* ".
           " FROM #__os_cck_orders AS o ".
           " LEFT JOIN #__users AS u ".
           " ON o.fk_user_id = u.id ".
           " LEFT JOIN #__os_cck_entity_instance AS eii ".
           " ON o.fk_instance_id = eii.eiid ". $where.
            $order. " LIMIT " . $pageNav->limitstart." , ". $pageNav->limit;
        $db->setQuery($sql);
        $orders = $db->loadobjectList();
        
        $order_entity_array = array();
        $order_prices = array();
        foreach($orders as $key => $order){
            $query = "SELECT fk_eiid, сart_item FROM #__os_cck_orders_price WHERE fk_order_id = ".$order->id." GROUP BY сart_item";
            $db->setQuery($query);
            $eiids = $db->loadAssocList('сart_item', 'fk_eiid');


            $order_entity_array[$order->id] = $eiids;
            
            //set to fid_parent - all product connected to order
            $orders[$key]->fid_parent = implode(',',$eiids) ;

            // $query = "SELECT op.*, o.fk_request_id FROM #__os_cck_orders_price as op "
            //         . " LEFT JOIN #__os_cck_orders as o ON o.id=op.fk_order_id "
            //         . " WHERE op.fk_order_id = ".$order->id." ";
            // $db->setQuery($query);
            // $order_price = $db->loadObjectList();
            
            // $order_prices[$order->id] = $order_price;
            
        }

        AdminViewOrders::orders($orders, $search, $pageNav, $entity_list, $order_entity_array, $order_prices);
    }

    static function showOrderDetails(){
        global $db, $user, $option, $doc, $jConf, $app, $input;

        $db = new os_cckDb();
        if(!JFactory::getUser()->authorise('access_to_orders', 'com_os_cck')){
            $app->enqueueMessage("Access denied", 'error');
            return;
        }

        $search = '';
        $order = 'ORDER BY o.id  DESC';
        
        $entity_id = $app->getUserStateFromRequest("entity_id{$option}", 'entity_id', '');

        $entities[] = array('value' => '', 'text' => cck_lang_text('COM_OS_CCK_OPTION_ALL_ENTITIES'));
        // $query = "SELECT ent.eid AS value, ent.name AS text FROM #__os_cck_entity as ent"
        //           ."\n LEFT JOIN #__os_cck_layout as lay ON lay.fk_eid = ent.eid WHERE lay.type = 'add_instance' GROUP BY ent.eid";
        $query = "SELECT eid AS value, name AS text FROM #__os_cck_entity ORDER BY name ";

        $db->setQuery($query);
        $ent = $db->loadObjectList("value");

        $entities = (count($ent) > 1) ? array_merge($entities, (array)$ent) : $entities;
        $entity_list = JHTML::_('select.genericlist',$entities, 'entity_id', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $entity_id);

    
        $where = '';
        if(isset($_REQUEST['search']) || ($entity_id != '' && isset($ent[$entity_id]))){
            
            if(isset($_REQUEST['search'])) {
                $search = $_REQUEST['search'];
                $where = "WHERE o.user_email LIKE '%{$search}%' OR o.user_name LIKE '%{$search}%' OR o.id LIKE '%{$search}%'";
            }
            if ($entity_id != '' && isset($ent[$entity_id])) {
                if(stripos($where, 'WHERE')){
                    $where .= " AND eii.fk_eid ='{$entity_id}'";
                } else {
                    $where = "WHERE eii.fk_eid ='{$entity_id}'";
                }
            }
        }

        if($where)
            $where = "WHERE o.user_email LIKE '%{$search}%' OR o.user_name LIKE '%{$search}%' 
                        AND fk_order_id = ".$_REQUEST['order_id']."";
        else
            $where = "WHERE fk_order_id = ".$_REQUEST['order_id']."";

        $limit = $app->getUserStateFromRequest("viewlistlimit", 'limit', $jConf->get("list_limit",10));
        $limitstart = $app->getUserStateFromRequest("view{$option}limitstart", 'limitstart', 0);

        $sql = "SELECT count(*)  ".
                " FROM #__os_cck_orders_details AS o ".
                " LEFT JOIN #__users AS u ".
                " ON o.fk_user_id = u.id ".
                " LEFT JOIN #__os_cck_entity_instance AS eii ".
                " ON o.fk_instance_id = eii.eiid ".
                " LEFT JOIN #__os_cck_orders AS ccko ".
                " ON ccko.id = o.fk_order_id ".
                $where." ".$order ;
        $db->setQuery($sql);
        $total = $db->loadResult();
        $limit = intval($limit);
        $pageNav = new os_libPagination($total, $limitstart, $limit);
        $sql = "SELECT u.username, ".
                       "o.*, ".
                       "ccko.fk_request_id,ccko.order_price as i_price, ccko.order_currency as i_unit, ccko.instance_type ".
               " FROM #__os_cck_orders_details AS o ".
               " LEFT JOIN #__users AS u ".
               " ON o.fk_user_id = u.id ".
               " LEFT JOIN #__os_cck_entity_instance AS eii ".
               " ON o.fk_instance_id = eii.eiid ".
               " LEFT JOIN #__os_cck_orders AS ccko ".
               " ON ccko.id = o.fk_order_id ".
                $where . " " . $order . " LIMIT " . $pageNav->limitstart." , ". $pageNav->limit;
        $db->setQuery($sql);
        $orders = $db->loadobjectList();

        $query = "UPDATE #__os_cck_orders SET notreaded=0 WHERE id=".$_REQUEST['order_id'];
        $db->setQuery($query);
        $db->execute();

        AdminViewOrders::order_details($orders, $search, $pageNav, $entity_list);
    
    }

    static function updateOrderStatus() {
        global $db, $option,$app, $os_cck_state, $entityFieldLists;
        $db = new os_cckDb();
        if(!cck_checkReferer()){
            $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
            return;
        }
        $input = JFactory::getApplication()->input;
        $orderId = $input->get('orderId', 0, 'INT');
        $status = $input->get('status', 'Completed', 'STRING');
        $comment = $input->get('comment', '', 'STRING');
        $option = $input->get('option', 'com_os_cck', 'STRING');
        
        cckUpdateOrderStatus($orderId, $status, $comment, $option);
//        var_dump($_REQUEST); exit;
        
        
        
        $app->redirect("index.php?option=$option&task=orders");
    }


    static function deleteOrder($cb, $option)
    {

        global $db, $app;
        $db = new os_cckDb();
        if(!cck_checkReferer()){
            $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
            return;
        }
        foreach($cb as $key=>$orderId){
            $sql = "DELETE FROM #__os_cck_orders WHERE id = ".$orderId." ";
            $db->setQuery($sql);
            $db->execute();

            $sql = "DELETE FROM #__os_cck_orders_details WHERE fk_order_id = ".$orderId." ";
            $db->setQuery($sql);
            $db->execute();

            $sql = "DELETE FROM #__os_cck_orders_price WHERE fk_order_id = ".$orderId." ";
            $db->setQuery($sql);
            $db->execute();
        }

        $app->redirect("index.php?option=$option&task=orders");

    }
    
    static function changeOrderStatus(){
        global $app;
        
        if(!cck_checkReferer()){
            $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
            return;
        }
        $input = JFactory::getApplication()->input;
        
        $orderId = $input->get('cb', 0 , 'INT');
        $orderId = $orderId[0];
        $status = $input->get('order_status', array(), 'ARRAY');
        $status = $status[$orderId];
        
        
       AdminViewOrders::changeOrderStatus($orderId, $status);
        
    }

    

}
