<?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\Classes\Constant;
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\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;

class OrderController 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 orderList(Request $request)
    {

        $fromDate = $request->get('from_date');
        $toDate = $request->get('to_date');
        $orderList = Cart::select("appointments.*", 'appointments.id as appointment_id', 'carts.*', 'carts.id as order_id')->leftJoin('appointments', 'appointments.id', 'carts.appointment_id')
            ->where('appointments.telemed_pros_id', $this->user_id);
        if ($fromDate != "") {
            $from_date = Carbon::createFromFormat('m-d-Y', $fromDate)->format('Y-m-d');
            $orderList->where('created_at', ">=", $from_date . " 00:00:00");
        }
        if ($toDate != "") {
            $to_date = Carbon::createFromFormat('m-d-Y', $toDate)->format('Y-m-d');
            $orderList->where('created_at', "<=", $to_date . " 23:59:59");
        }

        $orderListData = $orderList->get();
        $totalPrice = 0;
        $totalShippingCost = 0;
        foreach ($orderListData as $order) {
            $order->order_id = $order->id;
            $totalPrice = 0;
            $total_products = 0;
            $quantity = [];
            $totalShippingCost = 0;
            $order->order_total_amount = $totalPrice;
            $order->order_total_shipping = $totalShippingCost;
            $items = Item::leftJoin('plans_v1', 'items.plans_id', 'plans_v1.id')
                ->where('cart_id', $order->id)
                ->get();
            $appointment =     Appointment::where('id', $order->appointment_id)->first();

            $order->appointment_status = $appointment->status;



            $orderItems = [];
            foreach ($items as $item) {
                array_push($orderItems, $item->plansV1);
                $totalShippingCost += $item->shipping_cost;
                $item->total_price = $item->quantity * $item->price;
                $totalPrice += $item->total_price;
                $order->order_total_amount = $totalPrice;
                $order->order_total_shipping = $totalShippingCost;
                $item->plansV1->qty = $item->quantity;
                $item->plansV1->status = $item->status;
            }

            $order->total_items = $total_products;
            $order->order_items = $orderItems;
        }
        return response()
            ->json([
                'order_data' => $orderListData
            ]);
    }
    public function orderDetails($id)
    {
        $orderItems = $this->getOrderItems($id);

        $orderDetails = Cart::find($id);
        $items = Item::where('cart_id', $orderDetails->id)->get();


        $appointments = Appointment::select(
            'appointments.*',
            'telemed_pros.name as provider_name',
            'telemed_pros.email as provider_email',
            'telemed_pros.phone_number as provider_phone'
        )
            ->leftJoin('telemed_pros', 'telemed_pros.id', 'appointments.telemed_pros_id')
            ->where('appointments.id', $orderDetails->appointment_id)
            ->first();
        $prescription = PatientPrescription::select(
            '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',
            'prescriptions.name as prescription_name',
            'patient_prescription.prescription_id',
            'telemed_pros.name as provide_name',
            'telemed_pros.id as provider_id'
        )
            ->where("appointment_id", $orderDetails->appointment_id)
            ->leftJoin('appointments', 'appointments.id', 'patient_prescription.appointment_id')
            ->leftJoin('prescriptions', 'prescriptions.id', 'patient_prescription.prescription_id')
            ->leftJoin('telemed_pros', 'appointments.telemed_pros_id', 'telemed_pros.id')
            ->get();
        $patientNotes = PatientNote::where("appointment_id", $orderDetails->appointment_id)->get();
        $appointments->provider_id = $appointments->telemed_pros_id;
        $patient = $orderDetails->patient;
        $patient->profile_picture = $this->url->to("storage/profile_pictures/" . $patient->profile_picture);

        return response()
            ->json([
                'order_details' => $orderDetails,
                'order_items' => $orderItems,
                'patient_details' => $patient,
                'appointment_details' => $appointments,
                'items_activity' => $this->getShippingActivity($id),
                'appointment_notes' => $patientNotes,
                'prescription' => $prescription
            ]);
    }
    public function getOrderItems($id)
    {
        $items = Item::leftJoin('plans_v1', 'items.plans_id', 'plans_v1.id')
            ->where('cart_id', $id)
            ->get();
        $totalPrice = 0;
        $totalShippingCost = 0;
        $total_products = 0;
        foreach ($items as $item) {

            $totalShippingCost += $item->shipping_cost;
            $item->total_price = $item->quantity * $item->price;
            $totalPrice += $item->total_price;
            $total_products += $item->quantity;
            $item->image_url = $this->url->to("product/" . $item->image_url);
        }

        return [
            'items' => $items,
            'total_amount' => $totalPrice,
            'total_shipping_cost' => $totalShippingCost,
            'total_products' => $total_products,
            'total' => $totalPrice + $totalShippingCost
        ];
    }
    public function getShippingActivity($id)
    {
        $itemsHistory =  ItemHistory::select('items_history.*', 'plans_v1.title as item_name')
            ->where('items_history.cart_id', $id)
            ->leftJoin('items', 'items.id', 'items_history.item_id')
            ->leftJoin('plans_v1', 'plans_v1.id', 'items.plans_id')
            ->get();
        return $itemsHistory;
    }
}
