<?php
defined('_JEXEC') or die('Restricted access');
/**
* @package OS CCK
* @copyright 2020 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
*/


class AdminViewOrders{

    static function orders($orders, $search, &$pageNav, $entity_list, $order_entity_array, $order_prices){
        global $user, $app, $doc, $db, $entityFieldLists;

        $db = new os_cckDb();

        $html = "<div class='os_cck_caption' ><img src='./components/com_os_cck/images/os_cck_logo.png' alt ='Config' />".cck_lang_text('COM_OS_CCK_SHOW_ORDERS')."</div>";
        $app->JComponentTitle = $html;
        $countOrders = count($orders);
        $app = JFactory::getApplication();
        $input = $app->input;
        $option = $input->get('option', '', 'STRING');
        $order = $input->get('order', 'ASC', '');
        $order_sring = ($order == 'ASC') ? '&order=DESC' : '&order=ASC';
        
        $optionStatus[] = JHTML::_('select.option','Pending', "Pending");
        $optionStatus[] = JHTML::_('select.option','Completed', 'Completed');
        $optionStatus[] = JHTML::_('select.option','Chargeback', 'Chargeback');
        $optionStatus[] = JHTML::_('select.option','Cancel', 'Cancel');
        $optionStatus[] = JHTML::_('select.option','Refund', 'Refund');

        $form_name = 'adminForm';
        $form_id = 'adminForm' ;
        $table = new os_cckViewTable($form_name, $form_id, 'cck-orders-main', 'index.php?option=com_os_cck&task=orders', 'orders');

        $what_check = 'instance' ;
        $table->create_button( cck_lang_text("COM_OS_CCK_BUTTON_DELETE_ORDER"), 'deleteOrder', 
            JURI::root() . 'components/com_os_cck/images/btn_d.png', 'fa-close','',$what_check);
        $table->create_button(cck_lang_text("COM_OS_CCK_LABEL_BUTTON_MARK_AS_VIEWED"), 'is_readed_orders', 
            JURI::root() . 'components/com_os_cck/images/btn_s.png', 'fa-check','',$what_check);
        

        $table->create_filters('<div class="search_block">
        <input type="text" placeholder="' . cck_lang_text('COM_OS_CCK_SHOW_SEARCH') .'" name="search" value="'. $search .'" class="inputbox" onChange="document.'.$form_name.'.submit();"/>
        <button type="submit" class="cck_search_button" title="" data-original-title="Search"><span class="icon-search"></span></button>
        </div>');
        $table->create_filters('<div>' . $entity_list .'</div>');
        $table->limitbox = '<div class="btn-group pull-right hidden-phone">
        <label for="limit" class="element-invisible">'. cck_lang_text('OS_LIB_SEARCH_SEARCHLIMIT_DESC') .'</label>'. $pageNav->getLimitBox() .'</div>';

        $table->create_first_row_collumn('<input type="checkbox" nal;me="toggle" value="" onClick="Joomla.checkAll(this);" />', '', 'admin-order-standart-fields-checkbox');
        $table->create_first_row_collumn('<a href="index.php?option=com_os_cck&task=orders&orderby=id'. $order_sring .'">'. cck_lang_text("COM_OS_CCK_ORDERS_ID") .'</a>', '', 'admin-order-standart-fields-id');
        $table->create_first_row_collumn('<a href="index.php?option=com_os_cck&task=orders&orderby=email'. $order_sring .'">'. cck_lang_text("COM_OS_CCKORDERS_EMAIL") .'</a>', '', 'admin-order-standart-fields-email');
        $table->create_first_row_collumn('<a href="index.php?option=com_os_cck&task=orders&orderby=order_date'. $order_sring .'">'. cck_lang_text("COM_OS_CCK_ORDERS_DATE") .'</a>', '', 'admin-order-standart-fields-date');
        $table->create_first_row_collumn('<a href="index.php?option=com_os_cck&task=orders&orderby=status'. $order_sring .'">'. cck_lang_text("COM_OS_CCK_ORDERS_STATUS") .'</a>', '', 'admin-order-standart-fields-status');
        $table->create_first_row_collumn(cck_lang_text("COM_OS_CCK_ORDERS_PRICE"), '', 'admin-order-standart-fields-price');
        $table->create_first_row_collumn(cck_lang_text("COM_OS_CCK_ORDERS_PAID"), '', 'admin-order-standart-fields-paid');
        $table->create_first_row_collumn(cck_lang_text("COM_OS_CCK_ORDERS_DOWNLOADS"), '', 'admin-order-standart-fields-downloads');
        $table->create_first_row_collumn(cck_lang_text("COM_OS_CCK_ORDERS_DETAILS"), '', 'admin-order-standart-fields-details');
        $table->create_first_row_collumn(cck_lang_text("COM_OS_CCK_ORDERS_REQUEST"), '', 'admin-order-standart-fields-request');

        foreach($orders as $order){
            $order_instancies = $order_entity_array[$order->id];

            foreach ($order_instancies as $cart_item => $inst){
                $orderInstance = new os_cckEntityInstance($db->_db);
                $orderInstance->load($inst);
                $show_in_orders_fields = array();
                if(!$orderInstance->eiid) continue;
                $fields = $entityFieldLists[$orderInstance->fk_eid];
                foreach($fields as $field){
                    $params = new JRegistry;
                    $params->loadString($field->params);
                    if($params->get('show_in_orders', '') == 'yes'){
                        $show_in_orders_fields[] = $field;
                    }
                }
            }

            $table->create_second_row_collumn('Title');
            $table->create_second_row_collumn('Price');
            // var_dump($show_in_orders_fields);
            if(isset($show_in_orders_fields)){
                foreach($show_in_orders_fields as $order_fields){
                    $table->create_second_row_collumn($order_fields->field_name);
                }
            }
            break;


        }


        $data_first_row = array();
        $data_second_row = array();

        for($i = 0; $i < $countOrders; $i++) { 
            $order_data = array();
            $data_first_row[$i] = array();
            $data_second_row[$i] = array();
            if($orders[$i]->instance_type == "Rent"){
                $task = "edit_rent_request_instance";
            }else{
                $task = "edit_buy_request_instance";
            }
            $order_instancies = $order_entity_array[$orders[$i]->id];

            $order_data[] = JHTML::_('grid.id', $i,$orders[$i]->id, false, 'cb');
            $order_data[] = $orders[$i]->id;
            $order_data[] = $orders[$i]->user_email;
            $order_data[] = $orders[$i]->order_date;

            $status = $orders[$i]->status;

            if($status == 'Completed' || $status == 'Success'){
                $status = 'Completed';
            }
            $attr = 'class="inputbox input-medium" size="1"
                onchange="return listItemTask(\'cb'.$i.'\',\'changeOrderStatus\',\''.$form_name.'\')"';
                
            $order_data[] = JHTML::_('select.genericlist',$optionStatus, 'order_status['.
                $orders[$i]->id.']', $attr, 'value', 'text', $status);

            $order_data[] = $orders[$i]->order_price." ".$orders[$i]->order_currency;
            $order_data[] = $orders[$i]->paid_price." ".$orders[$i]->paid_currency;
            $order_data[] = $orders[$i]->number_of_downloads;
            $order_data[] = '<a href="index.php?option=com_os_cck&task=order_details&order_id='.$orders[$i]->id .'">' . cck_lang_text("COM_OS_CCK_ORDERS_DETAILS") . '</a>';
            $order_data[] = '<a href="index.php?option=com_os_cck&task='.$task.'&eiid=' . $orders[$i]->fk_request_id .'">'. cck_lang_text("COM_OS_CCK_ORDERS_REQUEST") .'</a>';

            $order_class = 'row' . ($i % 2) . ' ';
//            var_dump($orders[$i]->notreaded);
            if($orders[$i]->notreaded === 1){
                $order_class .= ' admin-order-not-readed';
            }
//            $order_class .= ' ' . $orders[$i]->notreaded?'admin-order-not-readed':'';
            $table->create_first_row_data($order_data, $order_class);

            $requestIstance = new os_cckEntityInstance($db->_db);
            $requestIstance->load($orders[$i]->fk_request_id);

            

            foreach ($order_instancies as $cart_item => $inst){
                $data_second_row[$i][$cart_item] = array();
                // echo '<div class="admin-order-single-product">';
                $orderInstance = new os_cckEntityInstance($db->_db);
                $orderInstance->load($inst);
                if(!$orderInstance->eiid) continue;
                $show_in_orders_fields = array();
//                var_dump($orderInstance);
                $fields = $entityFieldLists[$orderInstance->fk_eid];
                foreach($fields as $field){
                    $params = new JRegistry;
                    $params->loadString($field->params);
                    if($params->get('show_in_orders', '') == 'yes'){
                        $show_in_orders_fields[] = $field;
                    }
                }
                // var_dump($show_in_orders_fields);
                $calculated_price = 0;
                $quantity = 1;
                $not_calc_price = '';
                $coupon = false;
//                        var_dump($order_prices);
                foreach ($order_prices[$orders[$i]->id] as $key => $single_field){
//                            var_dump($single_field);
                    if($single_field->price_ordering == -1){
                        $field = new os_cckEntityField($db->_db);
                        $field->load($single_field->fk_fid);

                        unset($order_prices[$orders[$i]->id][$key]);
                    }
                }
                
                
                foreach ($order_prices[$orders[$i]->id] as $single_field){
                    if($single_field->сart_item == $cart_item){
                        $field = new os_cckEntityField($db->_db);
                        $field->load($single_field->fk_fid); 

                        if($single_field->price_type == 'base_price'){
                              if($single_field->quantity == 0) $single_field->quantity =1;
                              if($single_field->quantity>1) {$quantity = $single_field->quantity;}
                              $calculated_price = $calculated_price + ($single_field->price_value * $single_field->quantity);
                        }elseif($single_field->price_type == 'val+' && $single_field->price_value != '0.00'){
                              $calculated_price = $calculated_price + ($single_field->price_value * $quantity);
                          }else if($single_field->price_type == 'val-' && $single_field->price_value != '0.00'){
                              $calculated_price = $calculated_price - ($single_field->price_value * $quantity);
                          }else if($single_field->price_type == 'percent+' && $single_field->price_value != '0.00'){
                              $calculated_price = $calculated_price + (round($calculated_price/100 * $single_field->price_value, 2));
                          }else if($single_field->price_type == 'percent-' && $single_field->price_value != '0.00'){
                              $calculated_price = $calculated_price - (round($calculated_price/100 * $single_field->price_value, 2));
                          }
                    }

                    //var_dump($single_field);
                }
                
                $calculated_price = calculatedCurrency($orderInstance, $calculated_price)[0];
                // $table->create_second_row_data($orderInstance->title);
                // $table->create_second_row_data($orderInstance->title);
                $data_second_row[$i][$cart_item][] = $orderInstance->title;
                $data_second_row[$i][$cart_item][] = $calculated_price;

//                        var_dump($show_in_orders_fields);
                foreach ($show_in_orders_fields as $field){
                    $value = $orderInstance->getFieldValue($field);
                    if($field->field_name == 'Title' && isset($value[0]) && is_object($value[0]) && property_exists($value[0], 'data') && $value[0]->data == $orderInstance->title ){ //andrew added for remove duplicate title
                        continue;
                    }
                    // if(isset($value[0]) && is_object($value[0]) && property_exists($value[0], 'data') && $value[0]->data == ''){
                    //     continue;
                    // }elseif($field->field_type == 'datetime_popup' && isset($value[0]) && is_object($value[0]) && property_exists($value[0], 'data') && $value[0]->data == '0000-00-00 00:00:00'){
                    //     continue;
                    // }
                    $print_value = '';
                    if($field->field_type == 'text_select_list'){
                        $value = (isset($value[0]->data))?$value[0]->data : '';
                        $value = json_decode($value);
                        $params = new JRegistry;
                        $params->loadString($field->params);
                        $allowed_values = $params->get("allowed_value");
                        $allowed_values = explode('\sprt', $allowed_values);
                        $tmp_val = array();

                        if(is_array($value)){

                            foreach($value as $val){

                                if(isset($allowed_values[$val])){
                                    $tmp_val[] = cck_lang_text($allowed_values[$val]);
                                }
                            }
                        }

                        $print_value = implode(', ', $tmp_val);
                        
//                                $temp_val = json_decode($value[0]->data);
//                                if(is_array($temp_val)){
//                                    $temp_val = implode(', ', $temp_val);
//                                    $print_value = $temp_val;
//                                }
//                                var_dump(json_decode($value[0]->data));
                    }elseif(stripos($field->field_type, 'pricefield') !== false){
                        
                        continue;
                    }elseif(isset($value[0]) && is_object($value[0]) && property_exists($value[0], 'data')){
                        $print_value = $value[0]->data;
                    }
                    $data_second_row[$i][$cart_item][] = $print_value;
                    
//                            var_dump($value);
                }
                

            }
            // var_dump($data_second_row[$i]);
            $table->create_second_row_data($data_second_row[$i]);

            ?>
            
        
        <?php }


//        $table->paginator = $pageNav->getListFooter();
        $table->pageNav = $pageNav;

        // $buttons = new adminHeaderButton();
        
        echo $table->viewTable();
    }

    static function order_details($orders, $search, &$pageNav){
        global $user, $app, $doc, $app;
        $html = "<div class='os_cck_caption' ><img src='./components/com_os_cck/images/os_cck_logo.png' alt ='Config' />".cck_lang_text('COM_OS_CCK_SHOW_ORDERS')."</div>";
        $app->JComponentTitle = $html;
        $countOrders = count($orders);
        $orderId = protectInjectionWithoutQuote('order_id');
        $optionStatus[] = JHTML::_('select.option','Pending', "Pending");
        $optionStatus[] = JHTML::_('select.option','Completed', 'Completed');
        
        $form_name = 'adminForm';
        $form_id = 'adminForm' ;
        $table = new os_cckViewTable($form_name, $form_id, 'cck-orders-details-main', 
            'index.php?option=com_os_cck&task=orders', 'order_details');
        
        $table->create_button('Cancel', 'orders', JURI::root() . 'components/com_os_cck/images/btn_d.png', 'fa-close');
        
        $table->create_filters('<div class="search_block">
        <input type="text" placeholder="' . cck_lang_text('COM_OS_CCK_SHOW_SEARCH') .'" name="search" value="'. $search .'" class="inputbox" onChange="document.'.$form_name.'.submit();"/>
        <button type="submit" class="cck_search_button" title="" data-original-title="Search"><span class="icon-search"></span></button>
        </div>');
        
        $table->create_first_row_collumn('<a href="index.php?option=com_os_cck&task=order_details&orderby=user&order_id='.$orderId.'">User</a>', 'width:8%', '');
        $table->create_first_row_collumn('Username', 'width:8%', '');
        $table->create_first_row_collumn(cck_lang_text("COM_OS_CCKORDERS_EMAIL"), 'width:10%', '');
        $table->create_first_row_collumn('<a href="index.php?option=com_os_cck&task=order_details&orderby=email&order_id='.$orderId.'">'.cck_lang_text("COM_OS_CCK_ORDERS_DATE").'</a>', 'width:8%', '');
        $table->create_first_row_collumn('<a href="index.php?option=com_os_cck&task=order_details&orderby=status&order_id='.$orderId.'">'.cck_lang_text("COM_OS_CCK_ORDERS_STATUS").'</a>', 'width:8%', '');
        $table->create_first_row_collumn(cck_lang_text("COM_OS_CCK_ORDERS_TITLE"), 'width:8%', '');
        $table->create_first_row_collumn(cck_lang_text("COM_OS_CCK_ORDERS_PRICE"), 'width:4%', '');
        $table->create_first_row_collumn(cck_lang_text("COM_OS_CCK_ORDERS_PAID"), 'width:4%', '');
        $table->create_first_row_collumn(cck_lang_text("COM_OS_CCK_ORDERS_DETAILS"), 'width:7%', '');
        $table->create_first_row_collumn(cck_lang_text("COM_OS_CCK_LABEL_INPUT_COMMENT"), 'width:12%', '');
        for($i = 0; $i < $countOrders; $i++) {
            $details_data = array();
            if($orders[$i]->instance_type == "Rent"){
                $task = "edit_rent_request_instance";
            }else{
                $task = "edit_buy_request_instance";
            }
            
            $payment_details = unserialize($orders[$i]->payment_details);
            $details_text='';
            if($orders[$i]->txn_type)
                $details_text = cck_lang_text("COM_OS_CCK_ORDERS_DET_ACCEPT").$orders[$i]->txn_type;
            if(!empty($payment_details)){
                if(isset($payment_details['view']))
                    $details_text .= '<br>'.cck_lang_text("COM_OS_CCK_ORDERS_DET_SYSTEM").$payment_details['view'];
                if(isset($payment_details['payer_email']))
                    $details_text .= '<br>'.cck_lang_text("COM_OS_CCK_ORDERS_DET_EMAIL").'<br>'.$payment_details['payer_email'];
                if(isset($payment_details['pending_reason']))
                    $details_text .= '<br>'.cck_lang_text("COM_OS_CCK_ORDERS_DET_REASON").'<br>'.$payment_details['pending_reason'];
            }

            if(!isset($orders[$i]->user_name) && $orders[$i]->user_name == '') {
                $details_data[] = cck_lang_text("COM_OS_CCK_LABEL_ANONYMOUS");
                // echo cck_lang_text("COM_OS_CCK_LABEL_ANONYMOUS");
            } else {
                
                $details_data[] = $orders[$i]->user_name;
            }

            if(!isset($orders[$i]->username) && $orders[$i]->username == '' ) {
                $details_data[] = cck_lang_text("COM_OS_CCK_LABEL_ANONYMOUS");
            } else {
                $details_data[] = $orders[$i]->username;
            }

            $details_data[] = $orders[$i]->user_email;
            $details_data[] = $orders[$i]->order_date;
            $details_data[] = $orders[$i]->status;
            $details_data[] = '<a href="index.php?option=com_os_cck&task='.$task.'&eiid=' . $orders[$i]->fk_request_id.'">'.$orders[$i]->instance_title.'</a>';
            $details_data[] = $orders[$i]->i_price." ".$orders[$i]->i_unit;
            $details_data[] = $orders[$i]->order_price." ".$orders[$i]->order_currency;
            $details_data[] = $details_text;
            $details_data[] = $orders[$i]->comment;
            $table->create_first_row_data($details_data);

        }

//        $table->paginator = $pageNav->getListFooter();
        $table->pageNav = $pageNav;

       
        
        echo $table->viewTable();
        
    }
    
    static function changeOrderStatus($orderId, $status){
        global $app;

        $html = "<div class='os_cck_caption' ><img src='./components/com_os_cck/images/os_cck_logo.png' alt ='Config' />".cck_lang_text('COM_OS_CCK_SHOW_ORDERS')."</div>";
        $app->JComponentTitle = $html;

        $form_name = 'adminForm';
        $form_id = 'adminForm' ;
        $table = new os_cckViewTable($form_name, $form_id, 'cck-orders-details-main', 'index.php?option=com_os_cck&task=orders');

        $what_check = 'fields' ;
        $table->create_button('Change status', 'updateOrderStatus', 
            JURI::root() . 'components/com_os_cck/images/btn_d.png', 'fa-check','',$what_check);
        $table->create_button('Cancel', 'orders', JURI::root() . 'components/com_os_cck/images/btn_d.png', 'fa-close');

        ob_start();
?>
        <br>
        <h2><?php echo cck_lang_text("COM_OS_CCK_LABEL_INPUT_ORDER_DETAILS"); ?>:</h2>
        <br>
        <h3><?php echo cck_lang_text("COM_OS_CCK_LABEL_INPUT_COMMENT"); ?>*</h3>
        <textarea class="order_comment required" type="text" name="comment" rows="5" style="width: 350px;"></textarea>
        <input type="hidden" name="option" value="com_os_cck" />
        <input type="hidden" name="task" value="updateOrderStatus" />
        <input type="hidden" name="orderId" value="<?php echo $orderId;?>" />
        <input type="hidden" name="status" value="<?php echo $status;?>" />
        <br>
    <?php 
        $custom_html_text = ob_get_contents();
        ob_end_clean();
        $table->set_custom_html($custom_html_text);

        echo $table->viewTable();
       
    }
}
