<?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_nhs_items = false;
                   $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;
                       }

                       if(!empty($item['nhs_prescription'])) {
                           $has_nhs_items = true;
                       }

                       if(empty($item['assessment_id']) && empty($item['nhs_prescription'])) {
                           $has_shop_items = true;
                       }
                   }

                   $order->has_shop_items = $has_shop_items;
                   $order->has_nhs_items = $has_nhs_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;
                   }
               });


//NHS Orders
if (! $member->nhs_member) {
    $member->create_nhs_member();
}

$own_nhs_prescriptions = $member->nhs_member->prescriptions()->with('items')->latest()->get();
$own_active_orders = false;



foreach($own_nhs_prescriptions as $k => $prescription) {
    $own_nhs_prescriptions[$k]['template'] = 'nhs';
    $own_nhs_prescriptions[$k]['timestamp'] = $prescription['created_at'];
    if($prescription->is_editable()) {
        $own_active_orders = true;
    }
}

$referred_prescriptions = [];
$referred_active_orders = false;

foreach($member->referred_members as $key => $referred_member) {


    $referred_member_prescriptions = $referred_member->nhs_member->prescriptions()->with('items')->latest()->get();

    foreach($referred_member_prescriptions as $k => $prescription) {

        $referred_prescriptions[$key . $k] = $prescription;
        $referred_prescriptions[$key . $k]['template'] = 'nhs_referred';
        $referred_prescriptions[$key . $k]['timestamp'] = $prescription['created_at'];
        $referred_prescriptions[$key . $k]['member_display_id'] = $referred_member->nhs_member->get_member_ref();
        $referred_prescriptions[$key . $k]['patient_full_name'] = $referred_member->nhs_member->get_full_name();

        if($prescription->is_editable()) {
            $referred_active_orders = true;
        }

    }

}




/*
 * Tab navigation
 */
$order_tabs = [
    'All' => [
        'data' => []
    ],
    'NHS prescriptions' => [
        'data' => $own_nhs_prescriptions,
        'active_nhs_orders' => $own_active_orders
    ],
    'NHS patients' => [
        'data' => $referred_prescriptions,
        'active_nhs_orders' => $referred_active_orders
    ],
    'Online clinic' => [
        'data' => []
    ],
    'Shop' => [
        'data' => []
    ],
];

if ($member->nhs_member->is_patient) {
    //Remove PATIENT items if the user is a patient
    unset($order_tabs['NHS patients']);
} else {
    //Remove OWN items if the user is a referrer
    unset($order_tabs['NHS prescriptions']);
}


/*
 * 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;
    }

}


//Merge all orders
foreach($own_nhs_prescriptions as $k => $prescription) {
    $order_tabs['All']['data'][] = clone $prescription;
}

if(empty((int) $member->nhs_member->is_patient)) {
    foreach ($referred_prescriptions as $k => $prescription) {
        $order_tabs['All']['data'][] = clone $prescription;
    }
}

//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;
    }

}

