<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Hospital;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Carbon\Carbon;

class HospitalAuthController extends Controller
{
    public function login()
    {
        return view('hospital.login');
    }

    public function save_login(Request $request)
    {
        if (Auth::guard('hospital')->attempt(['email' => $request->email, 'password' => $request->password])) {
            return redirect()->intended(route('hospital.dashboard'))->with('success', 'Login successfully completed');
        }

        return back()->with('error', 'The provided credentials do not match our records.');
    }

    public function contact()
    {

        return view('hospital.test');
    }

    public function register()
    {
        return view('hospital.register');
    }

    public function save_register(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'mobile' => 'nullable|string|max:255',
            'email' => 'required|email|max:255|unique:hospitals,email',
            'password' => 'required|max:64'
        ]);

        $input = $request->only(['name', 'mobile', 'email']);
        $input['register_no'] = generateUniqueCode(9);

        if ($request->has('password')) {
            $input['password'] = Hash::make($request->password);
        }

        if ($hospital = Hospital::create($input)) {
            Auth::guard('hospital')->login($hospital);

            // Generate OTP
            $otp = Str::upper(Str::random(6));
            $hospital->last_otp = $otp;
            $hospital->otp_sent_count = 1;
            $hospital->otp_created_at = Carbon::now();

            // Update the OTP fields in the database
            $hospital->save();

            // Redirect to OTP verification page
            return redirect()->route('hospital.verify.otp', ['user_id' => $hospital->id])
                ->with('info', 'Please verify your OTP to complete registration.');
        }

        return back()->with('error', 'Something went wrong. Please try again later.');
    }
    public function verifyOtphospital(Request $request)
    {
        // Retrieve the authenticated user
        $hospital = Auth::guard('hospital')->user();

        // Check if the hospital user is authenticated
        if (!$hospital) {
            return redirect()->route('hospital.login')->with('error', 'You need to be logged in to verify OTP.');
        }

        $otpExpiryDuration = 5 * 60; // 5 minutes in seconds

        // Ensure `otp_created_at` is handled as a Carbon instance
        $otpCreatedAt = $hospital->otp_created_at ? Carbon::parse($hospital->otp_created_at) : null;
        $otpExpiresAt = $otpCreatedAt ? $otpCreatedAt->addSeconds($otpExpiryDuration) : null;

        // Pass the OTP expiry time to the view
        return view('hospital.verify', compact('hospital', 'otpExpiresAt'));
    }


    public function verifyOtpMatch(Request $request)
    {
        $hospital = Auth::guard('hospital')->user();

        $otpExpiryTime = 5; // OTP expiry in minutes
        if ($hospital->otp_created_at && $hospital->otp_created_at->diffInMinutes(now()) > $otpExpiryTime) {
            return redirect()->back()->with('error', 'OTP has expired. Please request a new one.');
        }

        // Verify OTP
        if ($request->otp === $hospital->last_otp) {
            $hospital->update([
                'last_otp' => null,
                'otp_created_at' => null,
                'otp_sent_count' => 0,
            ]);

            return redirect()->route('hospital.dashboard')->with('success', 'OTP verified successfully!');
        } else {
            return redirect()->back()->with('error', 'Invalid OTP. Please try again.');
        }
    }
}