<?php

namespace App\Http\Controllers;

use App\Classes\Constant;
use App\Models\Appointment;
use App\Models\Cart;
use App\Models\LabKit;
use App\Models\LabkitOrderItem;
use App\Models\Patient;
use App\Models\Subscription;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Contracts\Routing\UrlGenerator;
use Illuminate\Support\Facades\Storage;

class ProfileController 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 profileDetails()
    {
        $patient = Auth::guard('patient')->user();
        $patient->profile_picture = $this->url->to("storage/profile_pictures/" . $patient->profile_picture);
        // $patient->profile_picture = Storage::path("profile_pictures/" . $patient->profile_picture);

        return response()
            ->json([
                'profile' => $patient
            ]);
    }
    public function UpdateProfile(Request $request)
    {
        $patient = Patient::find($this->user_id);
        $patient->address = $request->get('address');
        $patient->city = $request->get('city');
        $patient->state = $request->get('state');
        $patient->zip_code = $request->get('zip_code');
        $patient->first_name = $request->get('first_name');
        $patient->last_name = $request->get('last_name');
        $patient->phone_no = $request->get('phone_no');
        $patient->gender = $request->get('gender');
        $patient->save();
        return response()
            ->json([
                'message' => 'Profile updated!'
            ]);
    }
    public function resetPassword(Request $request)
    {
        $oldPassword = $request->get('old_password');
        $newPassword = $request->get('new_password');

        $user = Patient::find($this->user_id);
        if (Hash::check($oldPassword, $user->password)) {
            $user->password = bcrypt($newPassword);
            $user->save();
            return response()->json([
                'msg' => "Password updated"
            ]);
        } else {
            return response()->json([
                'msg' => "Password does not match",
                'status' => 'error'
            ]);
        }
    }
    public function changeProfileImage(Request $request)
    {
        $patient = Patient::find($this->user_id);
        $image = $request->get('image');
        $fileName = 'profile-' . time();

        $logo = base64_decode($image);
        $ext = (explode('/', finfo_buffer(finfo_open(), $logo, FILEINFO_MIME_TYPE))[1]);

        $imageName =  $fileName . '.' . $ext;
        Storage::disk('local')->put("public/profile_pictures/" . $imageName, $logo);
        $patient->profile_picture = $imageName;
        $patient->save();
        return response()->json([
            'msg' => "File Uploaded",
            'status' => 'success'
        ]);
    }
    public function getStats()
    {
        $upcomingAppointments = Appointment::where('patient_id', $this->user_id)
            ->whereNull('start_time')
            ->count();
        $TotalCounts = Appointment::where('patient_id', $this->user_id)
            ->whereNotNull('start_time')
            ->whereNotNull('end_time')
            ->count();
        $orders = Cart::where('patient_id', $this->user_id)->count();
        $subscriptions = Subscription::where('patient_id', $this->user_id)->count();
        return response()->json([
            'upcoming_meetings' => $upcomingAppointments,
            'total_meetings'    => $TotalCounts,
            'total_orders'      => $orders,
            'total_subscription' => $subscriptions
        ]);
    }
    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,
        ]);
    }
}
