<?php

namespace Mtc\Plugins\Prescriptions\Classes;

use Mtc\Core\Response;
use Mtc\Modules\Members\Models\Member;
use Mtc\Shop\Basket\Info;
use Mtc\Shop\Item;

$path = '../../';
require_once $path . 'core/includes/header.inc.php';
/** @var Member $member current member (if logged in) */
/** @var \Basket $basket users basket */
$basket = new \Basket();
$basket->Go_Basket();

$errors = [];

header('Content-type: application/json');

if (!empty($_POST['search'])) {
    echo json_encode(
        Medication::query()
            ->where('name', 'LIKE', $_POST['search'] . '%')
            ->limit(15)
            ->get()
            ->map(function ($entry) {
                $entry->name = trim($entry->name);
                return $entry;
            })
    );
    exit;
}

if (filter_input(INPUT_POST, 'action') === 'save') {
    if (empty($_POST['send_hard_copy'])) {
        Response::outputJson('failed', [], [
            'Please confirm you understand you will need to send a hard copy of your original prescription to our pharmacy before your medication is dispatched.'
        ]);
        exit;
    }
    try {
        $items = collect($_POST['prescriptions'])
            ->map(function ($prescription) {

                if ((int)$prescription['quantity'] < 1) {
                    throw new \Exception('Quantities must be set for prescription items');
                }

                $medication = Medication::query()
                    ->where('name', $prescription['name'])
                    ->first();

                $prescription['price'] = $medication->price;

                // Create a temporary item for this prescription
                $item = Item::query()
                    ->firstOrCreate([
                        'name' => $prescription['name'] . (!empty($prescription['pack_size']) ? 'x' . $prescription['pack_size'] : ''),
                        'price' => $prescription['price'],
                        'price_exvat' => $prescription['price'],
                        'hidden' => 1,
                        'stock' => $prescription['quantity'],
                        'product_type' => 'private_prescription',
                    ]);

                return [
                    'quantity' => $prescription['quantity'],
                    'id' => $item->id,
                ];
            });
    } catch (\Exception $e) {
        Response::outputJson('failed', [], [
            $e->getMessage()
        ]);
        exit;
    }

    collect($items)
        ->each(function ($item) use ($basket) {

            $basket->Add_Item([
                'id' => $item['id'],
                'quantity' => $item['quantity'],
                'PLU' => 'private_prescription',
                'size' => '',
                'size_id' => 0
            ]);
        });

    Info::query()
        ->updateOrCreate([
            'basket_id' => $basket->id
        ], [
            'message' =>  'Is EU Prescription - ' . (filter_input(INPUT_POST, 'eu_prescription') ?  'Yes ' : 'No ')
                . "\nQuote match - " . (filter_input(INPUT_POST, 'quote_match') ?  'Yes ' : 'No ')
                . "\n" . filter_input(INPUT_POST, 'quote_match_text')
        ]);

    Response::outputJson('ok');
    exit;

}

$dosages = Dosage::query()
    ->orderBy('quantity_per_day', 'desc')
    ->get();

echo json_encode([
    'dosages' => $dosages,
    'prescriptions' => []
]);
