<?php

namespace Mtc\Plugins\NHS\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Mtc\Modules\Members\Classes\Auth;
use Mtc\Plugins\NHS\Classes\Prescription;
use Mtc\Shop\Order;


class CheckoutController extends BaseController
{

    private $logged_in_member = null;

    public function __construct()
    {
        $this->logged_in_member = Auth::getLoggedInMember();

        if (! $this->logged_in_member->id) {
            redirect()->route('nhs-prescriptions-welcome')->send();
        }
    }


    /* ======= */


    public function confirm(Request $request)
    {
        $referrer = $this->logged_in_member->nhs_member->is_referrer();

        if(!empty($referrer)) {
            $member_type = 'referrer';
        }else{
            $member_type = 'patient';
        }

        return template('NHS/pages/prescription_confirm.twig', [
            'member_type' => $member_type
        ]);
    }


    public function data_pending_prescriptions()
    {
        $pending_prescriptions = collect([]);

        if ($this->logged_in_member->nhs_member->is_referrer()) {

            foreach ($this->logged_in_member->referred_members as $referred_member) {
                $p = $referred_member->nhs_member->get_pending_prescriptions();
                $pending_prescriptions = $pending_prescriptions->merge($p);
            }

        } else {
            $p = $this->logged_in_member->nhs_member->get_pending_prescriptions();
            $pending_prescriptions = $pending_prescriptions->merge($p);
        }


        // Decorate with additional properties.

        foreach ($pending_prescriptions as $prescription) {
            $prescription->load('items');
            $prescription->load('nhs_member');
            $prescription->edit_url = route('nhs-prescriptions-edit', [ 'uuid' => $prescription->uuid ]);
            $prescription->delivery_method = $prescription->get_delivery_method();
            $prescription->payment_totals = $prescription->get_payment_totals();

            foreach ($prescription->items as &$prescription_item) {
                $prescription_item->price = [
                    'original' => $prescription_item->get_price(),
                    'payable' => $prescription_item->get_payable_price(),
                ];
            }
        }

        return [
            'prescriptions' => $pending_prescriptions,
        ];
    }


    public function checkout(Request $request)
    {
        $output = [
            'order_ids' => [],
            'redirect' => null,
        ];

        $prescription_uuids = $request->input('prescriptions');

        $prescriptions = Prescription::query()->whereIn('uuid', $prescription_uuids)->get();

        foreach ($prescriptions as $prescription) {
            $temp_output = $this->checkout_single($prescription->uuid);
            if ($temp_output['order_id']) {
                $output['order_ids'][] = $temp_output['order_id'];
            } elseif ($temp_output['redirect']) {
                $output['redirect'] = $temp_output['redirect'];
                break;
            }
        }

        return $output;
    }


    private function checkout_single($uuid)
    {
        $output = [
            'redirect' => null,
            'order_id' => null,
        ];

        $prescription = Prescription::get_by_uuid($uuid);

        $logged_in_member = Auth::getLoggedInMember();
        $prescription->authorise_access_by($this->logged_in_member);

        if (! $prescription->is_ready_for_checkout()) {
            \App\FlashMessage::set('This prescription is not ready for checkout.');
            return;
        }

        $total_to_pay = $prescription->get_payment_totals()['payable'];

        if ($prescription->nhs_member->is_pay_for_prescriptions && $total_to_pay > 0) {
            $basket = $prescription->create_basket();
            $basket->updateSession();

            $output['redirect'] = '/shop/checkout/basket.php';

        } else {
            $basket = $prescription->create_basket();

            Order::newOrder($basket);
            $order = Order::find($basket->order_id);
            $order->legacy()->updateStatus(Order::STATUS_PROCESSING);

            $prescription->save_status(Prescription::STATUS_COMPLETE);

            \App\FlashMessage::set('Completed successfully.');

            $output['order_id'] = $order->id;
        }

        return $output;
    }

}
