<?php

use Mtc\Core\Admin\User;
use Mtc\Core\Permissions;

$path = '../../../';
set_time_limit(180);
require_once $path . 'core/includes/header.inc.php';
$admin = User::find($adminuser->user['id']);
if (!Permissions::can(Permissions::EXPORT_ELECTRONIC_PRIVATE_REGISTER)) {
    exit;
}
$items = \Mtc\Shop\Order\Item::query()
    ->orderBy('id', 'desc')
    ->with([
        'order.shippingAddress',
        'approval.admin'
    ])
    ->whereHas('order', function($query) {
        if (!empty($_REQUEST['start_date'])) {
            $query->where('date', '>=', filter_input(INPUT_POST, 'start_date') ?: \Carbon\Carbon::now()->subYear()->format('Y-m-d H:i:s'));
        }

        if (!empty($_REQUEST['end_date'])) {
            $query->where('date', '<=', $_REQUEST['end_date']);
        }

    })
    ->whereHas('approval')
    ->whereHas('item', function($query) {
        return $query->whereProductType('doctor');
    })
    ->get()
    ->map(function($item) {
        $address = $item->order->shippingAddress;

        if (!empty($item->size)) {
            $item->item_name .= " ({$item->size})";
        }

        $doctor = '';
        if ($item->approval && $item->approval->admin) {
            $doctor = $item->approval->admin->name;
        }

        $full_address = collect([
            $address->address1,
            $address->address2,
            $address->city,
            $address->state,
            $address->country,
            $address->postcode
        ])->reject(function($item) {
            return empty(trim($item));
        })->implode(', ');

        return [
            $item->order->date,
            "{$address->firstname} {$address->lastname}",
            $full_address,
            $item->item_name,
            $item->quantity,
            $doctor,
            $item->price_paid,
        ];
    });

Util::force_download('doctor_export.csv');

$fp = fopen('php://output', 'w');
fputcsv($fp, [
    'Date',
    'Patient Name',
    'Patient Address',
    'Medication Prescribed',
    'Medication Dosage',
    'Prescribing Doctor',
    'Amount Charged',
]);

$items->each(function($item) use ($fp) {
    fputcsv($fp, $item);
});