<?php

namespace App\Http\Controllers;

use App\Classes\Constant;
use App\Models\Appointment;
use App\Models\Cart;
use App\Models\Item;
use App\Models\ItemHistory;
use App\Models\PatientNote;
use App\Models\PatientPrescription;
use App\Models\Payment;
use App\Models\Prescription;
use Carbon\Carbon;
use Illuminate\Contracts\Routing\UrlGenerator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use PhpParser\Node\Stmt\Const_;

class OrderController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    protected $user_id;
    protected $url;
    public function __construct(UrlGenerator $url)
    {
        $this->middleware('auth');
        $this->user_id =  Auth::guard('patient')->user()->id;
        $this->url = $url;
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        return view('home');
    }
    public function orderList(Request $request)
    {

        $fromDate = $request->get('from_date');
        $toDate = $request->get('to_date');
        $orderList = Cart::where('carts.patient_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) {
            $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();
            //$order->appointment_status = Appointment::where('id', $order->appointment_id)->first()->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;
            }

            $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',
            'carts.total_amount',
            'carts.shipping_amount'
        )
            ->leftJoin('telemed_pros', 'telemed_pros.id', 'appointments.telemed_pros_id')
            ->leftJoin('carts', 'carts.appointment_id', 'appointments.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();
        if ($appointments)
            $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 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;
    }
    public function getPatientShippingActivity()
    {
        $orderDetails = Cart::where('patient_id', $this->user_id)->orderBy('id', 'Desc')->first();

        $itemsHistory =  ItemHistory::select('items_history.*', 'plans_v1.title as item_name')
            ->where('items_history.cart_id', $orderDetails->id)
            ->leftJoin('items', 'items.id', 'items_history.item_id')
            ->leftJoin('plans_v1', 'plans_v1.id', 'items.plans_id')
            ->get();

        return response()
            ->json([
                'item_history' => $itemsHistory

            ]);
    }
    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 subscriptionList()
    {

        $orderDetails = Cart::leftJoin('items', 'carts.id', 'items.cart_id')
            ->leftJoin('plans_v1', 'items.plans_id', 'plans_v1.id')
            ->where('patient_id', $this->user_id)
            ->where('plans_v1.is_prescription_required', '1')
            ->get();
        foreach ($orderDetails as $details) {
            $details->image_url = $this->url->to("product/" . $details->image_url);
        }

        return response()
            ->json([
                'subscriptions' => $orderDetails
            ]);
    }
    public function getSubscriptionDetails($id)
    {
        $orderDetails = Cart::find($id);

        $items = Item::leftJoin('plans_v1', 'items.plans_id', 'plans_v1.id')
            ->where('plans_v1.is_prescription_required', '1')
            ->get();
        $appointments = Appointment::find($orderDetails->appointment_id);

        $patient = $orderDetails->patient;

        $patient->profile_picture = $this->url->to("storage/profile_pictures/" . $patient->profile_picture);

        return response()
            ->json([
                'order_details' => $orderDetails,
                'order_items' => $items,
                'patient_details' => $patient,
                'appointment_details' => $appointments

            ]);
    }
}
