<?php

namespace App\Http\Controllers\User;

use Carbon\Carbon;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Models\Developer;
use App\Models\Carousel;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Mail;
use App\Mail\SampleEmail;
use App\Models\Marquee;
use App\Models\Sponsor;

class UserAuthController extends Controller
{
    public function register()
    {
        return view('frontend.pages.register');
    }
    public function foundationregister()
    {
        return view('frontend.pages.foundation_register');
    }
    // public function store_register(Request $request)
    // {
    //     $user = new User();
    //     $user->email = $request->email;
    //     $user->name = $request->name;
    //     $user->phone = $request->phone;
    //     $user->password = Hash::make($request->password);
    //     $user->save();
    //     $prefix = 'B';
    //     $generate = str_pad($user->id, '9', '0', STR_PAD_LEFT);
    //     $user->account_id = $prefix . $generate;
    //     $user->save();
    //     return redirect()->route('login');
    // }


    public function store_register(Request $request)
    {
        $request->validate([
            'email' => 'nullable|email|unique:users,email',
            'name' => 'required',
            'phone' => 'nullable',
            'password' => 'required|confirmed',
        ]);
        $user = new User();
        $user->email = $request->email;
        $user->name = $request->name;
        $user->phone = $request->phone;
        $user->password = Hash::make($request->password);

        $user->save();

        $prefix = 'U';
        $generate = str_pad($user->id, 9, '0', STR_PAD_LEFT);
        $user->account_id = $prefix . $generate;
        $user->save();

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

        $user->save();

        // Send OTP email if registration is via email
        // if ($request->contactType === 'email' && $user->email) {
        //     Mail::to($user->email)->send(new SampleEmail([
        //         'title' => 'Otp Verification',
        //         'otp' => $otp,
        //     ]));
        // }

        // Redirect to OTP verification page
        return redirect()->route('verify.otp', ['user_id' => $user->id]);
    }


    public function foundation_store_register(Request $request)
    {

        $otp = Str::upper(Str::random(6));

        $data = [
            'title' => 'Otp verification',
            'otp' => $otp
        ];

        $user = new User();
        $user->email = $request->email;
        $user->name = $request->name;
        $user->phone = $request->phone;
        $user->password = Hash::make($request->password);
        $user->last_otp = $otp;
        $user->otp_sent_count = 1;
        $user->otp_created_at = Carbon::now();
        $prefix = 'F';
        $generate = str_pad($user->id, '7', '0', STR_PAD_LEFT);
        $user->account_id = $prefix . $generate;
        $user->save();
        // if($user->save()){

        //     return view('mail.verify',[
        //         'data' => $data,
        //         'user' => $user
        //     ]);

        //     Mail::to($request->email)->send(new SampleEmail($data));
        // }
        $otp = Str::upper(Str::random(6));
        $user->last_otp = $otp;
        $user->otp_sent_count = 1;
        $user->otp_created_at = Carbon::now();

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

        return redirect()->route('verify.otp', ['user_id' => $user->id]);
        // return redirect()->back()->with('error', 'registration failed.');

        // return redirect()->route('login');
    }


    public function verifyOtpMatch(Request $request)
    {
        $user = User::find($request->user_id);
        $otpExpiryTime = 5;
        if ($user->otp_created_at && $user->otp_created_at->diffInMinutes(Carbon::now()) > $otpExpiryTime) {
            return redirect()->back()->with('error', 'OTP has expired. Please request a new one.');
        }

        // Verify the OTP
        if ($request->otp === $user->last_otp) {
            // OTP is correct; reset OTP values
            $user->last_otp = null;
            $user->otp_created_at = null;
            $user->otp_sent_count = 0;
            $user->save();

            return redirect()->route('home')->with('success', 'OTP verified successfully!');
        } else {
            return redirect()->back()->with('error', 'Invalid OTP. Please try again.');
        }
    }
    public function resendOtp(Request $request)
    {
        $user = User::find($request->user_id);

        // Check if OTP sent count has reached a limit (e.g., limit to 3 requests)
        if ($user->otp_sent_count >= 3) {
            return redirect()->back()->with('error', 'You have reached the maximum number of OTP requests.');
        }

        // Generate a new OTP and send it to the user
        $newOtp = Str::upper(Str::random(6)); // Generate a new OTP
        $user->last_otp = $newOtp;
        $user->otp_created_at = Carbon::now(); // Set current time
        $user->otp_sent_count++; // Increment the count
        $user->save();

        // Send the new OTP via email
        Mail::to($user->email)->send(new SampleEmail(['otp' => $newOtp]));

        return redirect()->back()->with('success', 'A new OTP has been sent to your registered email.');
    }



    public function store_login(Request $request)
    {
        $request->validate([
            'email' => 'required',
            'password' => 'required',
        ]);

        $credential = is_numeric($request->email)
            ? ['phone' => $request->email, 'password' => $request->password]
            : ['email' => $request->email, 'password' => $request->password];

        if (Auth::attempt($credential)) {
            $user = Auth::user();
            $otp = Str::upper(Str::random(6));
            $user->last_otp = $otp;
            $user->otp_sent_count += 1;
            $user->otp_created_at = Carbon::now();
            $user->save();

            // Optional: Send OTP via email

            // Mail::to($user->email)->send(new SampleEmail(['otp' => $otp]));
            return redirect()->route('verify.otp', ['user_id' => $user->id]);
        }

        return redirect()->route('login')->withErrors(['login' => 'Invalid credentials']);
    }

    public function verifyOtp(Request $request)
    {
        $user = Auth::user(); // Retrieve the authenticated user

        // Check if the user is authenticated
        if (!$user) {
            return redirect()->route('login')->with('error', 'Please log in to verify your OTP.');
        }

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

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

        return view('verify', compact('user', 'otpExpiresAt'));
    }


    public function logout()
    {


        Auth::logout();

        return redirect('login');
    }

    public function home()
    {
        $developers = Developer::all();
        $carousel = Carousel::all();
        $marquee = Marquee::all();
        $sponsors = Sponsor::all();
        return view('frontend.pages.home', compact("developers", "carousel", 'sponsors', "marquee"));
    }
    public function login()
    {
        return view('frontend.pages.login');
    }
    public function foundationlogin()
    {
        return view('frontend.pages.foundation-login');
    }
}