<?php

use App\Admin\OrdersHelper;
use Carbon\Carbon;
use Mtc\Core\Permissions;

$path = '../../../';
require_once $path . 'core/includes/header.inc.php';

if (!Permissions::can(Permissions::DO_BULK_ORDER_ACTIONS)) {
    die('Unauthorized!');
}

// For testing. Set to false to see output as table
$fileMode = true;

if ($fileMode) {
    header('Content-type: text/x-csv');
    header('Content-Disposition: attachment; filename="orders_'.time().'.csv"');
}

$orderbyfield = 'order.id';
$orderbydir = 'DESC';

$orderByQuery = $orderbyfield === 'item' ?
    '`order_items`.`item_name` ' . $orderbydir . ', `order`.`id` DESC' :
    $orderbyfield . ' ' . $orderbydir . ', `order`.`id` DESC';

$orderHelper = new OrdersHelper($_REQUEST);
$orders = $orderHelper->getOrdersBuilderQuery(filter_input(INPUT_POST, 'order_type'))
    ->with('items.item')
    ->with('billingAddress')
    ->with('info')
    ->orderByRaw($orderByQuery)
    ->get();

if (empty($_REQUEST['anonymised'])) {
    $columns = [
        'Order ID',
        'Name',
        'Email',
        'Item',
        'SKU',
        'Total Value',
    ];
} else {
    $columns = [
        'User Identifier',
        'Order Identifier',
        'Date of purchase',
        'Item',
        'SKU',
        'Total Value',
    ];
}

$columns[] = 'Item Value';
$columns[] = 'Qty';
$columns[] = 'Variation';
$columns[] = 'Billing Country';

if ($fileMode) {
    $fp = tmpfile();
    fputcsv($fp, $columns);
} else {
    $rows = [];
    $rows[] = $columns;
}
$prev_order_id = null;


foreach ($orders as $order) {
    foreach ($order->items as $orderItem) {
        if (empty($_REQUEST['anonymised'])) {
            $row = [
                'order_ref' => '',
                'name' => '',
                'email' => '',
                'item' => $orderItem->item_name,
                'sku' => $orderItem->PLU,
                'total_value' => '',
            ];
            if ($order->id !== $prev_order_id) {
                $row['order_ref'] = $order->order_ref ?: $order->id;
                $row['name'] = $order->billingAddress->firstname . ' ' . $order->billingAddress->lastname;
                $row['email'] = $order->info->email;
                $row['total_value'] = $order->cost_total;
            } else {
                $row['order_ref'] = '';
                $row['name'] = '';
                $row['email'] = '';
                $row['total_value'] = '';
            }

        } else {
            $row = [
                'user_id' => '',
                'order_id' => '',
                'created_at' => '',
                'item' => $orderItem->item_name,
                'sku' => $orderItem->PLU,
                'total_value' => '',
            ];
            if ($order->id !== $prev_order_id) {
                $row['user_id'] = md5($order->info->email);
                $row['order_id'] = md5($order->id);
                $row['created_at'] = Carbon::parse($order->date)->format('d/m/Y H:i:s');
                $row['total_value'] = $order->cost_total;
            } else {
                $row['user_id'] = '';
                $row['order_id'] = '';
                $row['created_at'] = '';
                $row['total_value'] = '';
            }

        }
        $row['item_value'] = $orderItem->item_price;
        $row['quantity'] = $orderItem->quantity;
        $row['variation'] = $orderItem->size;
        $row['country'] = $order->billingAddress->country;

        if ($order->id !== $prev_order_id) {
            $prev_order_id = $order->id;
        }

        foreach ($row as $key => $value) {
            $row[$key] = clean_page($value);
        }

        if ($fileMode) {
            fputcsv($fp, $row);
        } else {
            $rows[] = $row;
        }
    }
}

if ($fileMode) {
    fseek($fp, 0);
    fpassthru($fp);
    fclose($fp);
} else {
    echo '<table>';
    foreach ($rows as $key => $row) {
        echo '<tr>';
        foreach ($row as $value) {
            echo $key ? '<td>' : '<th>';
            echo $value;
            echo $key ? '</td>' : '</th>';
        }
        echo '</tr>';
    }
    echo '</table>';
}