<?php

namespace App\Http\Controllers\Agent;

use Agence104\LiveKit\AccessToken;
use Agence104\LiveKit\AccessTokenOptions;
use Agence104\LiveKit\EgressServiceClient;
use Agence104\LiveKit\RoomCreateOptions;
use Agence104\LiveKit\RoomServiceClient;
use Agence104\LiveKit\VideoGrant;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Classes\JassJWT;
use App\Events\AppointmentCallEnded;
use App\Events\AppointmentCreated;
use App\Events\DeviceCurrentStatus;
use App\Models\Appointment;
use App\Models\Cart;
use App\Models\Doctor;
use App\Models\DoctorAppointment;
use App\Models\Item;
use App\Models\ItemHistory;
use App\Models\Lab;
use App\Models\LabKit;
use App\Models\LabkitOrderItem;
use App\Models\Patient;
use App\Models\PatientNote;
use App\Models\PatientPrescription;
use App\Models\Telemedpro;
use Carbon\Carbon;
use DateTime;
use Error;
use Exception;
use Illuminate\Support\Facades\Auth;
use Livekit\EncodedFileOutput;
use Livekit\EncodedFileType;
use Illuminate\Support\Facades\Http;
use Illuminate\Contracts\Routing\UrlGenerator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class PatientProfileController extends Controller
{
    protected $user_id;
    protected $url;
    public function __construct(UrlGenerator $url)
    {
        $this->middleware('auth');
        $this->user_id =  Auth::guard('agent')->user()->id;
        $this->url = $url;
    }
    public function index($id)
    {
        $patient = Patient::where('id', $id)->first();
        if ($patient->profile_picture)
            $patient->profile_picture = $this->url->to("storage/profile_pictures/", $patient->profile_picture);
        else
            $patient->profile_picture = asset('img/avatars/1.png');;

        $notes = PatientNote::select(
            'patient_notes.note',
            'telemed_pros.name as provider_name',
            'patient_notes.appointment_id',
            'patient_notes.created_at as note_date'
        )
            ->leftJoin('telemed_pros', 'telemed_pros.id', 'patient_notes.telemed_pros_id')
            ->where('patient_id', $id)->get();
        $prescriptions = PatientPrescription::select(
            'appointments.appointment_date',
            'appointments.appointment_time',
            'appointments.timezone',
            'appointments.start_time',
            'patient_prescription.direction_quantity',
            'patient_prescription.refill_quantity',
            'patient_prescription.dosage',
            'patient_prescription.status',
            'patient_prescription.direction_one',
            'patient_prescription.direction_two',
            'patient_prescription.dont_substitute',
            'patient_prescription.comments',
            'patient_prescription.brand',
            'patient_prescription.from',
            'patient_prescription.quantity',
            'patient_prescription.created_at as prescription_date',
            'telemed_pros.name',
            'telemed_pros.email as provider_email',
            'telemed_pros.gender as provider_gender',
            'telemed_pros.specialty as provider_specialty',
            'telemed_pros.years_of_experience',
            'prescriptions.name as prescription_name',
            'carts.id as order_id',
            // 'prescriptions.price as prescription_price',
            // 'prescriptions.shipping_cost as prescription_shipping_cost',
            'patient_prescription.prescription_id'
        )
            ->leftJoin('appointments', 'appointments.id', 'patient_prescription.appointment_id')
            ->leftJoin('carts', 'carts.appointment_id', '=', 'appointments.id')
            ->leftJoin('telemed_pros', 'appointments.telemed_pros_id', 'telemed_pros.id')
            ->leftJoin('prescriptions', 'prescriptions.id', 'patient_prescription.prescription_id')
            ->where('patient_prescription.patient_id', $id)->get();
        return response()->json(
            [
                'notes_history' => $notes,
                'prescriptions' => $prescriptions,
                'patient_details' => $patient
            ],
            200
        );
    }
    public function labkitOrderItemStore(Request $request)
    {
        // Validate the request data
        $validator = Validator::make($request->all(), [
            'cart_id' => 'required|exists:carts,id',
            'item_id' => 'required|exists:items,id',
            'lab_kit_id' => 'required|exists:lab_kit,id',

            /* 'result' => 'nullable|string', */
        ]);

        if ($validator->fails()) {
            return response()->json([
                'errors' => $validator->errors(),
            ], 422);
        }

        // Create a new LabkitOrderItem
        $labkitOrderItem = LabkitOrderItem::create([
            'cart_id' => $request['cart_id'],
            'item_id' => $request['item_id'],
            'lab_kit_id' => $request['lab_kit_id'],
            /* 'result' => $request['result'], */
            'status' => "Ordered",
        ]);

        return response()->json([
            'message' => 'Order detail stored successfully',
            'data' => $labkitOrderItem,
        ], 201);
    }
    public function labkitOrderItemGet(Request $request)
    {
        $labkitOrderItems = LabkitOrderItem::where('labkit_order_items.cart_id', $request->input('cart_id'))
            ->leftJoin(
                'lab_kit',
                'labkit_order_items.lab_kit_id',
                '=',
                'lab_kit.id'
            )
            ->leftJoin(
                'items',
                'items.id',
                'labkit_order_items.item_id'
            )
            ->leftJoin(
                'plans_v1',
                'plans_v1.id',
                'items.plans_id'
            )
            ->select(
                'labkit_order_items.id',
                'labkit_order_items.status',
                'labkit_order_items.result',
                'lab_kit.name as lab_kit_name',
                'plans_v1.title as item_name'
            )
            ->get();
        foreach ($labkitOrderItems as $labKit) {

            if ($labKit->result != "")
                $labKit->result = $this->url->to('storage/lab_results/' . $labKit->result);
        }

        return response()->json([
            'data' => $labkitOrderItems,
        ]);
    }
    public function getLabKit(Cart $cart, Request $request)
    {
        $kit = LabKit::all();
        return response()->json(['kit' => $kit], 200);
    }
}
