<?php

namespace Mtc\Plugins\NHS\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Mtc\Modules\DoctorSurgery\Classes\DoctorSurgery;
use Mtc\Modules\Members\Classes\Auth;
use Mtc\Plugins\NHS\Classes\NHSUnilexiconProduct;
use Mtc\Plugins\NHS\Classes\NHSMember;
use Mtc\Plugins\NHS\Classes\Prescription;
use Mtc\Plugins\NHS\Classes\MedicalCategory;
use Mtc\Core\UkPostcode;


class DataController extends BaseController
{

    private $logged_in_member = null;

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


    /* ======= */


    public function data_member($prescription_uuid, Request $request)
    {
        // TODO: authorise -- only logged in members can do it.

        $nhs_member = null;

        $nhs_member_id = trim($request->input('nhs_member_id'));

        if ($nhs_member_id) {

            $nhs_member = NHSMember::query()
                ->with('member.addressShipping')
                ->with('member.addressBilling')
                ->with('doctor_surgery')
                ->where('member_id', $nhs_member_id)
                ->first()
            ;

            if (! $nhs_member) {
                abort(404);
            }

        } else {
            $prescription = $this->data_prescription($prescription_uuid);
            $nhs_member = $prescription->nhs_member;
        }

        if ($nhs_member) $nhs_member->load('medical_categories');


        return $nhs_member;
    }


    public function data_prescription($prescription_uuid)
    {
        $prescription = Prescription::query()
            ->with('items')
            ->with('nhs_member.member.addressShipping')
            ->with('nhs_member.member.addressBilling')
            ->with('nhs_member.doctor_surgery')
            ->where('uuid', $prescription_uuid)
            ->first()
        ;

        if (! $prescription) {
            abort(404);
        }

        foreach ($prescription->items as $item) {
            $item->errors = [];
        }

        return $prescription;
    }


    /* ======= */


    public function getAvailableDoctorSurgeries(Request $request)
    {
        $postcode = $request->input('postcode');

        $results_limit = 100;
        $distance_miles = 6;

        $coordinates = UkPostcode::retrievePostcodeCoordinates($postcode);
        if ($coordinates) {
            $surgeries = DoctorSurgery::getByDistanceFromLatLong(
                $coordinates['latitude'] ?? 0,
                $coordinates['longitude'] ?? 0,
                $distance_miles,
                $results_limit
            );

        } else {
            $surgeries = DoctorSurgery::query()
                ->where('city', 'LIKE', "%{$postcode}%")
                ->limit($results_limit)
                ->get()
            ;
        }

        if (! $surgeries) {
            return [
                'errors' => "Coudn't determine location from the provided location."
            ];
        }

        $surgeries = $surgeries
            ->map(function ($doctor_surgery) {
                $doctor_surgery->title = $doctor_surgery->practice_name;
                $doctor_surgery->coords = $doctor_surgery->latitude . ',' . $doctor_surgery->longitude;
                $doctor_surgery->description = ucwords(strtolower($doctor_surgery->address_1)) . '<br />' . ucwords(strtolower($doctor_surgery->address_2)) . '<br />' . $doctor_surgery->postcode;
                $doctor_surgery->status = $doctor_surgery->status;

                return $doctor_surgery;
            })
        ;

        return [
            'doctor_surgeries' => $surgeries,
        ];
    }


    public function getPrescriptionMedications(Request $request)
    {
        $medications = [];

        $term = $request->input('search_term');

        if ($term) {
            $medications = NHSUnilexiconProduct::searchByTerm($term, 50);
        }

        return [
            'medications' => $medications,
        ];
    }


    public function getAvailableExemptionReasons(Request $request)
    {
        return [
            'exemption_reasons' => [
                'A | Is 60 years of age or over or is under 16 years of age',
                'B | Is 16 17 or 18 and in full time education',
                'D | Maternity exemption certificate',
                'E | Medical exemption certificate',

                'F | Prescription prepayment Certificate (PPC)',
                'G | Prescription exemption certificate issued by Ministry of Defence',
                'L | HC2 (full help) certificate',
                'H | Income Support (IS) or Income-related Employment and Support Allowance (ESA)',

                'K| Income-based Jobseeker’s Allowance (JSA)',
                'M | Tax Credit exemption certificate',
                'S | Pension Credit Guarantee Credit (including partners)',
                'U | Universal Credit and meets the criteria. Find out more at <a href="http://www.nhsbsa.nhs.uk/UC" target="_blank">www.nhsbsa.nhs.uk/UC</a>',
            ],
        ];
    }


    public function getAvailableMedicalCategories(Request $request)
    {
        return [
            'options' => MedicalCategory::all(),
        ];
    }


    public function checkMedicationNameIsValid(Request $request)
    {
        $medication_name = $request->input('search_term');

        $found_medications = NHSUnilexiconProduct::query()
            ->where('mtc__display_name', '=', "{$medication_name}")
            ->count()
        ;

        return [
            'is_valid' => (bool)$found_medications,
        ];
    }
}
