<?php

namespace App\Http\Controllers\Auth;

use App\Helpers\OtpHelper;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Mail\OtpMail;
use App\Models\Otp;
use App\Models\User;
use App\Providers\RouteServiceProvider;
use Carbon\Carbon;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use Illuminate\View\View;

class AuthenticatedSessionController extends Controller
{
    /**
     * Display the login view.
     */
    public function create(): View
    {
        // Send a GET request to the Django API
        $apiReachable = @fsockopen('41.215.147.34', 8080, $errno, $errstr, 5);

        if ($apiReachable) {
            // Set the "danger" message in the session
            session()->flash('danger', 'SMS System down');
            return view('auth.login');
        } else {
            return view('auth.login');
        }
    }

    public function store(LoginRequest $request): RedirectResponse
    {
        // 1. Check API availability
        $apiReachable = @fsockopen('41.215.147.34', 8080, $errno, $errstr, 5);

        if ($apiReachable) {
            session()->flash('danger', 'SMS System down');
            return redirect()->back();
        }

        // 2. Validate input (username + password)
        $request->validate([
            'email'    => 'required|string', // this is actually the USERNAME
            'password' => 'required|string',
        ]);

        // 3. Build FULL email (domain already has @)
        $email = $request->email . config('settings.domain'); // @mbbscms.com

        // 4. Validate credentials WITHOUT login
        $credentials = [
            'email'    => $email,
            'password' => $request->password,
        ];

        if (!Auth::validate($credentials)) {
            return back()->withErrors([
                'email' => 'Invalid credentials.',
            ]);
        }

        // 5. Fetch user
        $user = User::where('email', $email)->first();

        // 6. Account status check
        if ($user->status != 1) {
            return back()->withErrors([
                'email' => 'Your account is deactivated. Please contact the administrator.',
            ]);
        }

        // 7. Password expiry (1 month)
        if (
            !$user->password_changed_at ||
            Carbon::parse($user->password_changed_at)->addMonth()->isPast()
        ) {
            return redirect()->route('password.request')->withErrors([
                'email' => 'Your password has expired. Please reset it to continue.',
            ]);
        }

        // 8. ⏱️ OTP TIME CHECK (1 HOUR)
        $otpRequired = true;

        if ($user->last_otp_verified_at) {
            $otpRequired = Carbon::parse($user->last_otp_verified_at)
                ->addHour()
                ->isPast();
        }

        // 9. ✅ OTP NOT REQUIRED → LOGIN DIRECTLY
        if (!$otpRequired) {
            Auth::attempt($credentials);
            $request->session()->regenerate();

            return redirect()->intended(RouteServiceProvider::HOME);
        }

        // 10. 🔐 OTP REQUIRED → Generate & Send
        $otp = OtpHelper::generateOtp();

        Otp::updateOrCreate(
            ['email' => $email],
            [
                'otp' => $otp,
                'expires_at' => now()->addMinutes(5),
            ]
        );

        Mail::to($email)->send(new OtpMail($otp));

        // 11. Store TEMP login data in session
        session([
            'otp_sent'     => true,
            'otp_email'    => $email,
            'otp_password' => $request->password,
        ]);

        // 12. Redirect to OTP verification
        return redirect()->route('otp.verify');
    }


    /**
     * Destroy an authenticated session.
     */
    public function destroy(Request $request): RedirectResponse
    {
        Auth::guard('web')->logout();

        $request->session()->invalidate();

        $request->session()->regenerateToken();

        return redirect('/');
    }
}
