<?php

namespace App\Http\Controllers\Agent;

use App\Classes\Constant;
use App\Http\Controllers\Controller;
use App\Models\Appointment;
use App\Models\DoctorAppointment;
use App\Models\Telemedpro;
use App\Models\LicenseNumberModel;
use Carbon\Carbon;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use App\Models\Setting;
use Illuminate\Support\Facades\Auth;
use Illuminate\Contracts\Routing\UrlGenerator;

class DashboardController extends Controller
{
    protected $user_id;
    protected $url;
    public function __construct(UrlGenerator $url)
    {
        // $this->middleware('auth');
        // if (isset(Auth::guard('agent')->user()->id))
        // $this->user_id =  Auth::guard('agent')->user()->id;
        $this->url = $url;
    }
    public function index()
    {
        return view('agent.dashboard');
    }
    public function register(Request $request)
    {
        // Validate the request data
        $validator = Validator::make($request->all(), [
            'first_name' => ['required', 'string', 'max:255'],
            'last_name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8'],
        ]);

        if ($validator->fails()) {
            return response()->json([
                'errors' => $validator->errors()
            ], 422);
        }
        $first_name = $request->input('first_name');
        $last_name = $request->input('last_name');
        $email = $request->input('email');
        $digits = 4;
        $code = rand(pow(10, $digits - 1), pow(10, $digits) - 1);
        // Create the new user
        $setting = Setting::find(1);
        Mail::send('emails.providerVerificationEmail', ['name' => $first_name . " " . $last_name, "code" => $code, 'setting' => $setting], function ($message) use ($first_name, $last_name, $email) {
            $message->to($email, $first_name . " " . $last_name)
                ->subject('Verify Your Email ');
        });
        $user = Telemedpro::create([
            'name' => $first_name . " " . $last_name,
            'first_name' => $request->input('first_name'),
            'last_name' => $request->input('last_name'),
            'email' => $request->input('email'),
            'password' => Hash::make($request->input('password')),
            'status' => 0,
            "email_verification" => $code
        ]);
        $token = $user->createToken('auth_token')->plainTextToken;
        return response()->json([
            'user' => $user,
            'message' => 'User registered successfully',
        ], 201);
    }

    public function emailVerify($id, Request $request)
    {

        $providerData = Telemedpro::where('email_verification', $request->get('token'))->where('id', $id)->first();

        if ($providerData) {
            $providerData->email_verification = '';
            $providerData->email_verified_at = Carbon::now()->format('Y-m-d H:i:s');
            $providerData->save();
            return response()->json([
                'message' => 'Account verified',
            ]);
        } else {
            return response()->json([
                'message' => 'already verified',
            ], 422);
        }
    }
    public function saveProfile($id, Request $request)
    {
        $providerData = Telemedpro::find($id);
        if (!$providerData) {
            return response()->json([
                'message' => 'Provider not found',
            ], 404);
        }
        $providerData->practice_state = $request->input('practice_state');
        $providerData->phone_number = $request->input('phone');
        $providerData->gender = $request->input('gender');
        $providerData->specialty = $request->input('specialty');
        $availabilityFrom = $request->input('availabilityFrom');
        if ($availabilityFrom && Carbon::hasFormat($availabilityFrom, 'H:i')) {
            $providerData->availability_from = Carbon::createFromFormat('H:i', $availabilityFrom)->format('H:i:s');
        } else {
            return response()->json([
                'message' => 'Invalid format for availability_from',
            ], 400);
        }

        // Validate and format availability_to
        $availability_to = $request->input('availabilityTo');
        if ($availability_to && Carbon::hasFormat($availability_to, 'H:i')) {
            $providerData->availability_to = Carbon::createFromFormat('H:i', $availability_to)->format('H:i:s');
        } else {
            return response()->json([
                'message' => 'Invalid format for availability_to',
            ], 400);
        }
        $providerData->home_address = $request->input('home_address');
        $providerData->medical_license_number = $request->input('medical_license_number');
        $providerData->years_of_experience = $request->input('years_of_experience');
        $providerData->city = $request->input('city');
        $providerData->state = $request->input('state');
        $providerData->zip_code = $request->input('zip_code');
        $providerData->save();
        $this->saveLicenseNumber($id, $request->input('medical_license_number'));
        return response()->json([
            'user' => $providerData,
            'message' => 'Data saved ',
        ], 201);
    }
    public function saveLicenseNumber($id, $licences)
    {
        foreach ($licences as $key => $value) {
            LicenseNumberModel::create([
                "provider_id" => $id,
                "state" => $key,
                "license_number" => $value,
                "status" => 1
            ]);
        }
    }
    public function resendCode($id)
    {
        $digits = 4;
        $code = rand(pow(10, $digits - 1), pow(10, $digits) - 1);
        $providerData = Telemedpro::find($id);
        $providerData->email_verification = $code; //update code in database
        $email = $providerData->email;
        $first_name = $providerData->first_name;
        $last_name = $providerData->last_time;
        $setting = Setting::find(1);
        Mail::send('emails.providerVerificationEmail', ['name' => $first_name . " " . $last_name, "code" => $code, 'setting' => $setting], function ($message) use ($first_name, $last_name, $email) {
            $message->to($email, $first_name . " " . $last_name)
                ->subject('Verify Your Email ');
        });
        $providerData->save();
        return response()->json([
            'message' => 'Verification code sent! ',
        ], 201);
    }
    public function getProviderMeetings()
    {
        $appointments = Appointment::select(
            "patients.profile_picture",
            "patients.first_name",
            "patients.last_name",
            "appointments.id as appointment_id",
            "appointments.start_time",
            "appointments.end_time",
            "appointments.timezone",
            "appointments.duration",
            "appointments.appointment_date",
            "appointments.appointment_time",
            "appointments.status as appointment_status",
            "appointments.patient_name",
            "carts.id as order_id",
            "appointments.id as appointment_id",
            "appointments.patient_id"
        )
            ->leftJoin("patients", "patients.id", "appointments.patient_id")
            ->leftJoin("carts", "carts.appointment_id", "appointments.id")
            ->where('telemed_pros_id', Auth::guard('agent')->user()->id)
            ->where('start_time', "!=", null)
            ->where('end_time', "!=", null)
            ->orderBy('appointments.created_at', 'desc')
            ->get();

        foreach ($appointments as $appointment) {
            if ($appointment->profile_picture)
                $appointment->profile_picture = $this->url->to("storage/profile_pictures/", $appointment->profile_picture);
            else
                $appointment->profile_picture = asset('img/avatars/1.png');
        }

        return response()->json($appointments, 200);
    }
}
