<?php

namespace Mtc\Plugins\NHS\Classes;

use Carbon\Carbon;
use Mtc\Shop\Category;
use Mtc\Shop\Item;

$path = '../../../';
require_once $path . 'core/includes/header.inc.php';
$basket = new \Basket();
$basket->Go_Basket();

if (!$basket->hasOnlyNHSItems()) {
    header('Location: /members/nhs/prescriptions/?error=items_in_basket');
    exit;
}

// Fresh baskets
$_SESSION['basket_id'] = null;

if (empty($_POST['add_to_basket_order']) || !is_array($_POST['add_to_basket_order'])) {
    header('Location: /members/nhs/prescriptions/');
    exit;
}

$price = $member->nhs_member->is_pay_for_prescriptions ? NHS_PRESCRIPTION_PRICE : 0;
$member->nhs_member->prescriptions->each(function($prescription) use ($basket, $price, $member) {
    if (!in_array($prescription->id, $_POST['add_to_basket_order'])) {
        return;
    }
    // Create a temporary item for this prescription

    $prescription_name = $prescription->name . " - {$prescription->quantity_per_dose}x {$prescription->dosage->name}";

    /** @var Item $item */
    $item = Item::query()
        ->firstOrCreate([
            'name' => $prescription_name,
            'price' => $price,
            'price_exvat' => $price,
            'hidden' => 1,
            'product_type' => 'prescription',
        ]);

    $nhs_category = Category::query()->where('name', 'NHS')->first();
    $item->categories()->syncWithoutDetaching([$nhs_category->id]);

    // Create a 'size' which makes a prescription's quantity
    $size = $item->sizes()->firstOrCreate([
        'size' => $prescription->quantity,
        'price' => $price,
        'price_exvat' => $price,
        'strength' => $prescription->dosage ? $prescription->dosage->id : '',
    ]);

    $size->stock = 999;
    $size->save();

    if (!empty($_REQUEST['new_prescription_date'])) {
        // One refill date for all selected items
        $start_date = Carbon::createFromFormat('d/m/Y', $_REQUEST['new_prescription_date']);
        $refill_date = $start_date->addDays(Prescription::daysMedicationLasts($prescription->toArray()))->format('Y-m-d');
    } else {
        // Refill date based on previous prescription
        $refill_date = (new Carbon(Prescription::getRefillDate($prescription, $member)))->format('Y-m-d');
    }

    $prescription->refill_date_new = $refill_date;
    $prescription->one_off_prescription = in_array($prescription->id, (array)$_REQUEST['one_off_prescription']);
    $prescription->save();

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

$basket->set_expiry_time();
header('Location: /shop/checkout/basket.php');
exit;