<?php
/**
 * @author: Uldis Zvirbulis <uldis.zvirbulis@mtcmedia.co.uk>
 * @version: 5/2/2018
 */

use Mtc\Core\Permissions;
use Mtc\Core\Admin\User as AdminUserModel;
use Mtc\Modules\Members\Models\Member;
use Mtc\Modules\Members\Models\MemberNote;
use Mtc\Plugins\MembersMessaging\Classes\Templates;
use Mtc\Shop\Category;
use Mtc\Shop\Coupon;

chdir(__DIR__);
$path = '../../';
require_once $path . 'core/includes/header.inc.php';
$admin = \Mtc\Core\Admin\User::query()->find($adminuser->user['id']);


if ($_REQUEST['action'] === 'load_order_filter_categories') {
    header('Content-Type: application/json');

    $allowedCategories = AdminUserModel::getAllowedCategories();
    $items = [];

    if ($allowedCategories instanceof \Illuminate\Support\Collection && $allowedCategories->isNotEmpty()) {
        $categories = Category::query()
            ->whereIn('id', $allowedCategories->all())
            ->orderBy('name')
            ->get(['id', 'name']);

        foreach ($categories as $category) {
            $items[] = [
                'value' => (int)$category->id,
                'label' => $category->name,
            ];
        }
    } else {
        $tree = Category::getCompleteFlatTree();
        foreach ($tree as $category) {
            $items[] = [
                'value' => (int)$category->id,
                'label' => $category->intended_name ?? $category->name,
            ];
        }
    }

    echo json_encode(['items' => $items]);
    exit;
}

if ($_REQUEST['action'] === 'load_order_filter_coupons') {
    header('Content-Type: application/json');

    if (!defined('COUPON_ENABLED') || !COUPON_ENABLED) {
        echo json_encode(['items' => []]);
        exit;
    }

    $coupons = Coupon::query()->orderBy('id', 'DESC')->get(['code', 'name']);
    $items = [];

    foreach ($coupons as $coupon) {
        $label = trim($coupon->name . ' - ' . $coupon->code, ' -');
        if ($label === '') {
            $label = $coupon->code;
        }
        $items[] = [
            'value' => $coupon->code,
            'label' => $label,
        ];
    }

    echo json_encode(['items' => $items]);
    exit;
}


if (in_array($_REQUEST['action'], ['approve', 'reject', 'clinic_check', 'approve_reject_item'])) {
    $response = [
        'error' => '',
        'order_item_id' => (int)$_REQUEST['order_item_id'],
    ];
    $order = new Order($_REQUEST['order_id']);
    $approve = \Mtc\Shop\Order\Item::ORDER_ITEM_AWAITING;
    if ($order_item = \Mtc\Shop\Order\Item::query()->find($_REQUEST['order_item_id'])) {
        $item = Mtc\Shop\Item::query()
            ->with('custom')
            ->find($order_item->item_id);
        if (
            (
                $order->hasNHSItems() &&
                Permissions::can(Permissions::REVIEW_NHS_ORDERS)
            ) ||
            (
                !empty($item) &&
                \Mtc\Shop\Order\Item::orderItemCanBeApproved($order_item)
            )
        ) {
            if (!empty($_REQUEST['approve'])) {
                $order->approveItem($order_item->id, $admin);
            }
            if (!empty($_REQUEST['reject'])) {
                $order->rejectItem($order_item->id, $admin);
            }
            if (!empty($_REQUEST['clinic_check'])) {
                $order->clinicallyCheckItem($order_item->id, $admin);
            }
        } else {
            $response['error'] = 'Insufficient rights to approve / reject order item!';
        }
    } else {
        $response['error'] = 'Cannot find order item!';
    }
    $order = $order->eloquent();
    if (!empty($_REQUEST['note'])) {
        /** @var Member $member */
        $member = Member::query()
            ->find($order->member);
        $member->logPatientNotes([
            'note' => $_REQUEST['note'],
            'orderID' => $order->id
        ]);
    }
    if (!$order->hasNHSItems()) {
        // Find all order items that are next (ordering by ID)
        $order_items = $order->items()
            ->where('id', '>', $_REQUEST['order_item_id'])
            ->orderBy('id')
            ->get();
        $next_order_item_id = null;
        foreach ($order_items as $order_item) {
            if (!\Mtc\Shop\Order\Item::orderItemCanBeApproved($order_item)) {
                continue;
            }
            if ((int)$order_item->approved === 1) {
                if (Permissions::can(Permissions::PHARMACIST_ORDER_VIEW)) {
                    $next_order_item_id = $order_item->id;
                    break;
                }
                continue;
            }

            if ((int)$order_item->approved !== 0) {
                continue;
            }
            $next_order_item_id = $order_item->id;
            break;
        }

        if (empty($response['error'])) {
            if (!empty($next_order_item_id)) {
                $response['next_order_item_id'] = $next_order_item_id;
            } else {
                $response['next_order'] = 1;
            }
            $response['approve'] = $approve;
            $response['success'] = 1;
        }
    } else {
        $response['approve'] = $approve;
        $response['success'] = 1;
    }

    echo json_encode($response);
    exit;
}

if ($_REQUEST['action'] === 'get_next_item') {
    $admin = \Mtc\Core\Admin\User::query()->find($adminuser->user['id']);
    $order = \Mtc\Shop\Order::query()->find($_REQUEST['order_id']);
    if (!empty($_REQUEST['note'])) {
        $order->doctor_note .= $_REQUEST['note'];
        $order->save();
    }
    $order_items = $order->items()->where('id', '>', $_REQUEST['order_item_id'])->orderBy('id')->get();
    $response['success'] = 1;
    foreach ($order_items as $order_item) {
        if (
            $order_item->id > $_REQUEST['order_item_id'] &&
            \Mtc\Shop\Order\Item::orderItemCanBeApproved($order_item)
        ) {
            $response['next_order_item_id'] = $order_item->id;
            break;
        }
    }
    echo json_encode($response);
}

if ($_REQUEST['action'] === 'get_doctor_item') {
    $order_id = $_REQUEST['order_id'];

    if (empty($order_id)) {
        exit;
    }
    $adminUser = \Mtc\Core\Admin\User::find($adminuser->user['id']);
    /** @var \Mtc\Shop\Order $order */
    $order = \Mtc\Shop\Order::query()->find($order_id);
    if (! empty($_REQUEST['order_item_id'])) {
        $order_items = $order
            ->items()
            ->where('id', '>=', $_REQUEST['order_item_id'])
            ->orderBy('id')
            ->get()
        ;
    } else {
        $order_items = $order
            ->items()
            ->orderBy('id')
            ->get()
        ;
    }

    $item_list = [];

    foreach ($order_items as $order_item) {
        if (\Mtc\Shop\Order\Item::orderItemCanBeApproved($order_item)) {
            $assessment_id = $order_item->assessment_id;

            ob_start();
            include './orders/templates/order.assessment.view.php';
            $assessment_html = ob_get_contents();
            ob_end_clean();

            $item_list[] = [
                'html' => $twig->render('shop/admin/products/doctor_item.twig', [
                    'order_item' => $order_item,
                    'item' => $order_item->item,
                    'assessment_html' => $assessment_html,
                    'gp_templates' => Templates::query()
                        ->where('category', 'contact_gp')
                        ->get(),
                    'can_clinically_check' => Permissions::can(Permissions::CLINICALLY_CHECK_ORDER),
                ]),
                'order_item_id' => $order_item->id,
            ];
        }
    }

    echo json_encode($item_list);
    exit;
}

if ($_REQUEST['action'] === 'update_pharmacy_label_text' && !empty($_REQUEST['order_item_id'])) {
    $r = \Mtc\Shop\Order\Item::query()
        ->where('id', $_REQUEST['order_item_id'])
        ->update([
            'pharmacy_label_text' => $_REQUEST['pharmacy_label_text']
        ]);

    echo json_encode([
        'success' => (int)$r,
    ]);
    exit;
}

if ($_REQUEST['action'] === 'update_patient_notes') {
    $order = \Mtc\Shop\Order::query()->find($_REQUEST['order_id']);
    if (
        !empty($order) &&
        !empty($_REQUEST['note'])
    ) {
        /** @var Member $member */
        $member = Member::query()
            ->find($order->member);
        $member->logPatientNotes([
            'note' => $_REQUEST['note'],
            'orderID' => $order->id
        ]);

        echo json_encode([
            'success' => '1',
            'notes' => MemberNote::getOrderNotesHTML($_REQUEST['order_id']),
        ]);
    }
    exit;
}

if ($_REQUEST['action'] === 'update_doctor_note') {
    if (!empty($_REQUEST['order_id'])) {
        \Mtc\Shop\Order::query()
            ->where('id', $_REQUEST['order_id'])
            ->update([
                'doctor_note' => $_REQUEST['note'],
            ]);
    }
    exit;
}

if ($_REQUEST['action'] === 'update_pharmacist_note') {
    if (!empty($_REQUEST['order_id'])) {
        \Mtc\Shop\Order::query()
            ->where('id', $_REQUEST['order_id'])
            ->update([
                'pharmacist_note' => $_REQUEST['note'],
            ]);
    }
    exit;
}

if ($_REQUEST['action'] === 'get_item_sizes_options') {
    if (empty($_REQUEST['item_id'])) {
        echo json_encode([
            'error' => 'Empty Item ID!',
        ]);
        exit;
    }
    $sizes = \Mtc\Shop\Item\Size::query()->where('item_id', filter_input(INPUT_GET, 'item_id', FILTER_VALIDATE_INT))->get();
    if ($sizes->count() > 0) {
        $order_item = \Mtc\Shop\Order\Item::query()->find($_REQUEST['order_item_id']);
        $html = '';
        foreach ($sizes as $size) {
            $selected = $size->id === $order_item->sizeid ? 'selected' : '';
            $html .= "<option value='{$size->id}' {$selected}>{$size->size}</option>\n";
        }
        echo json_encode([
            'success' => '1',
            'html' => $html,
        ]);
        exit;
    }

    echo json_encode([
        'success' => '1',
        'html' => '<option value="0">One size</option>',
    ]);
    exit;
}

if ($_REQUEST['action'] === 'get_size_data') {
    // If size data empty, provide item data
    if (!empty($_REQUEST['size_id'])) {
        if (!$size = \Mtc\Shop\Item\Size::query()->find($_REQUEST['size_id'])) {
            echo json_encode([
                'error' => 'Size not found',
            ]);
            exit;
        }
        $size->display_price = $size->sale_price ?: $size->price;
        $size->display_price_exvat = $size->sale_price_exvat ?: $size->price_exvat;
        $size->vat_deductable = $size->item->vat_deductable;
        echo json_encode([
            'success' => '1',
            'data' => $size,
        ]);
    } else {
        if (!$item = \Mtc\Shop\Item::query()->find($_REQUEST['item_id'])) {
            echo json_encode([
                'error' => 'Item not found',
            ]);
            exit;
        }
        $item->display_price = $item->sale_price ?: $item->price;
        $item->display_price_exvat = $item->sale_price_exvat ?: $item->price_exvat;
        $item->PLU = $item->epos_code;
        echo json_encode([
            'success' => '1',
            'data' => $item,
        ]);
        exit;
    }
}

if ($_REQUEST['action'] === 'update_item_vat_rate') {
    if (!empty($_REQUEST['item_id'])) {
        \Mtc\Shop\Item::query()
            ->where('id', $_REQUEST['item_id'])
            ->update([
                'vat_rate' => $_REQUEST['vat_rate'],
            ]);
        echo json_encode([
            'success' => '1',
        ]);
    }
    exit;
}

if ($_REQUEST['action'] === 'update_item_product_type') {
    if (!empty($_REQUEST['item_id'])) {
        \Mtc\Shop\Item::query()
            ->where('id', $_REQUEST['item_id'])
            ->update([
                'product_type' => $_REQUEST['product_type'],
            ]);
        echo json_encode([
            'success' => '1',
        ]);
    }
    exit;
}

if ($_REQUEST['action'] === 'update_item_assessment_form') {
    if (!empty($_REQUEST['item_id'])) {
        \Mtc\Shop\Item::query()
            ->where('id', $_REQUEST['item_id'])
            ->update([
                'form_id' => $_REQUEST['form_id'],
            ]);
        echo json_encode([
            'success' => '1',
        ]);
    }
    exit;
}
