<?php

namespace App\Http\Controllers\Admin\Api;

use Agence104\LiveKit\VideoGrant;
use App\Classes\Constant;
use App\Events\AppointmentBooked;
use App\Events\PaymentProcessed;
use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\Appointment;
use App\Models\Cart;
use App\Models\Item;
use App\Models\ItemHistory;
use App\Models\Lab;
use App\Models\LabKit;
use App\Models\LabkitOrderItem;
use App\Models\LicenseNumberModel;
use App\Models\MedicalHistoryAnswer;
use App\Models\Patient;
use App\Models\PatientNote;
use App\Models\PatientPlan;
use App\Models\PatientPrescription;
use App\Models\PatientRegActivity;
use App\Models\Plan;
use App\Models\PlanV1;
use App\Models\Prescription;
use App\Models\ProfileAnswer;
use App\Models\ProfileCategory;
use App\Models\QuestionBuilder;
use App\Models\Setting;
use App\Models\Subscription;
use App\Models\Telemedpro;
use Carbon\Carbon;
use Carbon\CarbonTimeZone;
use DateTime;
use DateTimeZone;
use Error;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Routing\UrlGenerator;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Yajra\DataTables\DataTables;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;
use Agence104\LiveKit\AccessToken;
use Agence104\LiveKit\AccessTokenOptions;
use Agence104\LiveKit\RoomCreateOptions;
use Agence104\LiveKit\RoomServiceClient;
use Illuminate\Auth\Access\AuthorizationException;

class HomeController extends Controller
{
    protected $url;
    protected $user;
    public function __construct(UrlGenerator $url)
    {
        $this->url = $url;
        $this->user = Auth::guard('admin')->user();
    }
    public function updateAdminProfile(Admin $admin, Request $request)
    {
        try {
            $this->authorizeForUser($this->user, 'edit', new Admin);
            $admin->update($request->all());
            return response()->json([
                'message' => 'Admin updated successfully',
                'telemed' => $admin
            ]);
        } catch (AuthorizationException $e) {
            return  $e->getMessage();
        }
    }



    public function product(PlanV1 $product)
    {
        return response()->json([
            'product' => $product

        ]);
    }






    public function labsList()
    {
        $labs = Lab::all();
        return response()->json([
            'patients' => $labs
        ]);
    }
    public function labs(Lab $lab)
    {
        return response()->json([
            'patient' => $lab
        ]);
    }
    public function labsDelete(Lab $lab)
    {
        $lab->delete();
        return response()->json([
            'message' => "Deleted Successfully"
        ]);
    }
    public function labsUpdate(Lab $lab, Request $request)
    {
        $lab->update($request->all());

        return response()->json([
            'message' => 'Lab updated successfully',
            'telemed' => $lab
        ]);
    }

    public function getQuestionBuilderStore(Patient $patient, Request $request)
    {

        $questionBuilder = QuestionBuilder::select('key', 'value')->where("customer_id", $patient->id)->get();
        $jsonData = $questionBuilder->mapWithKeys(function ($item) {
            return [$item->key => $item->value];
        });
        // Store data
        return response()->json([
            'message' => 'Data Sent',
            'data' => $jsonData
        ], 200);
    }
    public function getProducts()
    {
        return response()->json([
            'data' => PlanV1::select('plans_v1.*')->get()
        ], 200);
    }
    public function storeOrderData(LabKit $labkit, Patient $patient, Request $request)
    {
        $user = $patient;
        $cart = new Cart();
        $cart->lab_kit_id = $labkit->id;
        $cart->first_name = $request->first_name;
        $cart->last_name = $request->last_name;
        /* $cart->appointment_id = $request->appointment_id; */
        $cart->email = $request->email;
        $cart->phone = $request->phone;
        $cart->status = "pending";
        $cart->prescription_status = "pending";



        $cart->date_of_birth = $request->date_of_birth ?? null;

        $cart->patient_id = $user->id;

        $cart->shipping_address1 = $request->shipping_address1;
        $cart->shipping_address2 = $request->shipping_address2;
        $cart->shipping_city = $request->shipping_city;
        $cart->shipping_state = $request->shipping_state;
        $cart->shipping_zipcode = $request->shipping_zipcode;
        $cart->shipping_country = $request->shipping_country;

        $cart->billing_address1 = $request->billing_address1;
        $cart->billing_address2 = $request->billing_address2;
        $cart->billing_city = $request->billing_city;
        $cart->billing_state = $request->billing_state;
        $cart->billing_zipcode = $request->billing_zipcode;
        $cart->billing_country = $request->billing_country;
        $cart->short_description = "Your order has been placed successfully";
        $cart->shipping_amount = $request->shipping_amount;
        $cart->total_amount = $request->total_amount;

        $cart->save();

        if ($request->has('items')) {
            foreach ($request->items as $itemData) {
                $item = new Item();
                $item->plans_id = $itemData['plans_id'];
                $item->quantity = $itemData['quantity'];


                $item->status = "pending";
                $item->labkit_delivery_status = "pending";
                $item->cart_id = $cart->id;
                $item->save();

                $itemHistory = new ItemHistory();
                $itemHistory->note = "Order was placed (Order ID: #" . $cart->id . ")";
                $itemHistory->short_description = "Your order has been placed successfully";
                $itemHistory->cart_id = $cart->id;
                $itemHistory->status = "pending";
                $itemHistory->item_id = $item->id;
                if (isset($itemData['subscription']) && $itemData['subscription'] == true && $itemData['onetime'] == false) {
                    $subscription = new Subscription();
                    $subscription->subscription_start_date = Carbon::now();
                    $subscription->subscription_renewal_date = Carbon::now()->addDays(30);
                    $subscription->subscription_status = "Active";
                    $subscription->cart_id = $cart->id;
                    /* $subscription->status = "active"; */

                    $subscription->item_id = $item->id;
                    $subscription->patient_id = $user->id;

                    $subscription->save();
                }

                $itemHistory->save();

                $plan = PlanV1::find($itemData['plans_id']);
                if ($plan->is_prescription_required == true)
                    $labkitOrderItem = LabkitOrderItem::create([
                        'cart_id' => $cart->id,
                        'item_id' =>  $item->id,
                        'lab_kit_id' => 1,
                        /* 'result' => $request['result'], */
                        'status' => "Ordered",
                    ]);
            }
        }
        return response()->json(['status' => 'Success', 'cart' => $cart], 200);
    }
    public function editOrderData(Cart $cart, Request $request)
    {
        // Validate the request data
        $validatedData = $request->validate([
            'first_name' => 'sometimes|string|max:255',
            'last_name' => 'sometimes|string|max:255',
            'email' => 'sometimes|email|max:255',
            'phone' => 'sometimes|string|max:20',
            'date_of_birth' => 'sometimes|date|nullable',
            'shipping_address1' => 'sometimes|string|max:255',
            'shipping_address2' => 'sometimes|string|max:255|nullable',
            'shipping_city' => 'sometimes|string|max:255',
            'shipping_state' => 'sometimes|string|max:255',
            'shipping_zipcode' => 'sometimes|string|max:20',
            'shipping_country' => 'sometimes|string|max:255',
            'patient_id' => 'sometimes',
            /* 'billing_address1' => 'sometimes|string|max:255',
            'billing_address2' => 'sometimes|string|max:255|nullable',
            'billing_city' => 'sometimes|string|max:255',
            'billing_state' => 'sometimes|string|max:255',
            'billing_zipcode' => 'sometimes|string|max:20',
            'billing_country' => 'sometimes|string|max:255', */
            'shipping_amount' => 'sometimes|numeric',
            'total_amount' => 'sometimes|numeric',
            'items' => 'sometimes|array',
            /* 'items.*.plans_id' => 'required_with:items|exists:plans,id',
            'items.*.quantity' => 'required_with:items|integer|min:1',
            'items.*.subscription' => 'sometimes|boolean',
            'items.*.onetime' => 'sometimes|boolean', */
        ]);

        // Update the cart with validated data
        $cart->fill($validatedData);
        $cart->save();

        // Update or create items
        if ($request->has('items')) {
            foreach ($request->items as $itemData) {
                $item = Item::updateOrCreate(
                    ['cart_id' => $cart->id, 'plans_id' => $itemData['plans_id']],
                    [
                        'quantity' => $itemData['quantity'],
                        'status' => 'pending',
                        'labkit_delivery_status' => 'pending',
                    ]
                );

                // Update or create subscription
                if (isset($itemData['subscription']) && $itemData['subscription'] == true && $itemData['onetime'] == false) {
                    Subscription::updateOrCreate(
                        ['cart_id' => $cart->id, 'item_id' => $item->id],
                        [
                            'subscription_start_date' => $item->created_at,
                            'subscription_renewal_date' => $item->created_at->addDays(30),
                            'subscription_status' => 'Active',
                            'patient_id' => $cart->patient_id,
                        ]
                    );
                } else {
                    // Remove subscription if it exists and is no longer needed
                    Subscription::where('cart_id', $cart->id)
                        ->where('item_id', $item->id)
                        ->delete();
                }

                // Update or create LabkitOrderItem
                $plan = PlanV1::find($itemData['plans_id']);
                if ($plan->is_prescription_required) {
                    LabkitOrderItem::updateOrCreate(
                        ['cart_id' => $cart->id, 'item_id' => $item->id],
                        [
                            'lab_kit_id' => 1,
                            'status' => 'Ordered',
                        ]
                    );
                }
            }
        }

        // Remove items that are no longer in the request
        /* if ($request->has('items')) {
            $currentItemIds = collect($request->items)->pluck('plans_id')->toArray();
            ItemHistory::where('cart_id', $cart->id)
                //->whereNotIn('plans_id', $currentItemIds)
                ->delete();
            Item::where('cart_id', $cart->id)
                ->whereNotIn('plans_id', $currentItemIds)
                ->delete();
        } */

        // Refresh the cart to get the updated data
        $cart->refresh();

        return response()->json(['status' => 'Success', 'cart' => $cart], 200);
    }


    public function getPrescription()
    {
        $prescriptions = Prescription::query();

        return DataTables::of($prescriptions)->make(true);
    }
    public function processPayment(Patient $patient, Request $request)
    {
        //event(new PaymentProcessed($patient));
        return response()->json(['status' => 'Success'], 200);
    }


    public function questionBuilderStore(Patient $patient, $category, Request $request)
    {
        $data = $request->all();

        $questionBuilderData = [];
        $category = ProfileCategory::where("category_link", $category)->first();
        if (!$category)
            return response()->json([
                'message' => 'Invalid Category Link',
                'data' => ''
            ], 200);

        foreach ($data as $key => $value) {
            if (is_array($value)) {
                $value = serialize($value);
            }
            if (!empty($value)) {
                $questionBuilderData[] = [
                    'key' => $key,
                    'value' => $value,
                    'profile_category_id' => $category->id,
                    'customer_id' => $patient->id
                ];
            }
        }
        // dd($questionBuilderData);
        $questionBuilder = QuestionBuilder::insert($questionBuilderData);

        $questionBuilder = QuestionBuilder::select('key', 'value')->get();

        // Convert the data to a key-value JSON format
        $jsonData = $questionBuilder->mapWithKeys(function ($item) {
            return [$item->key => $item->value];
        });
        // Store data+
        return response()->json([
            'message' => 'Data Inserted',
            'data' => $jsonData
        ], 200);
    }
    public function getMedicalHistoryQuestion(Patient $patient, Request $request)
    {
        $answers = MedicalHistoryAnswer::where('patient_id', $patient->id)->get();

        return response()->json([
            'status' => 'Success',
            'answers' => $answers
        ], 200);
    }
    public function postMedicalHistoryQuestion(Patient $patient, Request $request)
    {

        foreach ($request->answers as $answer) {
            $existing = MedicalHistoryAnswer::where("patient_id", $patient->id)->where('question_key', $answer['question_key'])->first();

            if ($existing) {
                $existing->answer = $answer['answer'];
                $existing->patient_id = $patient->id;
                $existing->type = $answer['type'];
                $existing->save();
            } else {
                $newAnswer = new MedicalHistoryAnswer();
                $newAnswer->question_key = $answer['question_key'];
                $newAnswer->patient_id = $patient->id;
                $newAnswer->answer = $answer['answer'];
                $newAnswer->type = $answer['type'];
                $newAnswer->save();
            }
        }

        PatientRegActivity::create([
            'patient_id' => $patient->id,
            'activity' => 'patient_medical_question_entered'
        ]);

        return response()->json(['status' => 'Success'], 200);
    }
}
