<?php
use Mtc\Shop\Order;

global $orders_per_page;

//Shop orders
$orders = Order::query()
               ->with('items')
               ->where('paid', 1)
               ->where(function ($query) use ($member) {
                   $query->where('member', $member->id)
                         ->orWhereHas('info', function ($query) use ($member) {
                             $query->where('email', $member->email);
                         });
               })
               ->orderBy('id', 'desc')
               ->get()
               ->filter(function ($order) {

                   $order->num_items = $order->items->sum('quantity');
                   $order->status = Order::$statuses[$order->status];
                   $order->date_long = \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $order->date)->format('j F Y');
                   $order->date = \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $order->date)->format('d/m/Y');

                   $non_prescription_items = $order->items->filter(function ($item){
                       return $item->item->id;
                   });
                   $order->can_reorder = false;

                   /*
                    * Order categories
                    */
                   $has_online_doctor_items = false;
                   $has_shop_items = false;

                   $items = $order->items->toArray();

                   foreach($items as $item) {

                       if(!empty($item['assessment_id'])) {
                           $has_online_doctor_items = true;
                       } else {
                           $has_shop_items = true;
                       }
                   }

                   $order->has_shop_items = $has_shop_items;
                   $order->has_online_doctor_items = $has_online_doctor_items;

                   /*
                    * Get order postcode
                    */
                   $addresses = $order->address->toArray();
                   $shipping_postcode = false;
                   $billing_postcode = false;

                   foreach($addresses as $address) {

                       if(!empty($address['type'])) {

                           if($address['type'] == 'shipping') {

                               $shipping_postcode = $address['postcode'];

                           }elseif($address['type'] == 'billing') {

                               $billing_postcode = $address['postcode'];
                           }

                       }

                   }

                   if(!empty($shipping_postcode)) {
                       $order->order_postcode = $shipping_postcode;
                   }elseif(!empty($billing_postcode)) {
                       $order->order_postcode = $billing_postcode;
                   }

                   /*
                    * Order image
                    */
                   $first_item = $order->items[0];
                   $order->item_image = THEME_URL . '/images/placeholders/no-image.jpg';
                   $order->has_image = false;

                   if(!empty($first_item->item_id)) {

                       $temp_item = new Item();
                       $temp_item->Get_Item($first_item->item_id, true);
                       $item_images = collect($temp_item->images);

                       $item_image = $item_images->filter(function($image) {
                           if(!empty($image['default'])) {
                               return $image;
                           }
                       })->first();

                       if(!empty($item_image['name'])) {
                           $order->item_image = $item_image['name'];
                       }

                       if(!empty($item_image)) {
                           $order->has_image = true;
                       }
                   }

                   if($order->num_items > 0) {
                       return $order;
                   }
               });


/*
 * Tab navigation
 */
$order_tabs = [
    'All' => [
        'data' => []
    ],
    'Online clinic' => [
        'data' => []
    ],
    'Shop' => [
        'data' => []
    ],
];


/*
 * Build tab content
 */
$orderArr = $orders->toArray();

foreach($orderArr as $order) {

    $order['template'] = 'shop';

    $order_tabs['All']['data'][] = $order;

    if ($order['has_shop_items']) {
        $order_tabs['Shop']['data'][] = $order;
    }

    if ($order['has_online_doctor_items']) {
        $order_tabs['Online clinic']['data'][] = $order;
    }

}


//Order by timestamp
if(!empty($order_tabs['All']['data'])) {
   $stamp = array_column($order_tabs['All']['data'], 'timestamp');
   array_multisort($stamp, SORT_DESC, $order_tabs['All']['data']);
}

/*
 * Mark pages the items appear on
 */
foreach($order_tabs as $key => $orders) {

    if(!empty($orders_per_page)) {
        $per_page = $orders_per_page;
    }else{
        $per_page = 24;
    }


    $count = 0;
    $page = 1;
    $total = 0;

    foreach($orders['data'] as $k => $order) {

        $order_tabs[$key]['data'][$k]['page'] = $page;

        $count++;
        $total++;

        if($count >= $per_page && $total < count($orders['data'])) {
            $page++;
            $count = 0;
        }
    }

    $order_tabs[$key]['pagination']['total_pages'] = $page;


}


//Set a currently active tab
if( !empty($_REQUEST['tab']) ) {

    $active_tab = $_REQUEST['tab']; //'NHS prescriptions';
    $active_tab = str_replace('_', ' ', $active_tab);
    $valid_tab = false;

    //Validate tab
    foreach( $order_tabs as $tab => $tab_data ) {


        if( trim($active_tab) == trim($tab) ) {
            $valid_tab = true;
        }

    }

    if( !$valid_tab ) {
        $active_tab = false;
    }

}

