<?php

namespace App\Http\Controllers\Student\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\Services\Sms\SmsService;
use Carbon\Carbon;
use Illuminate\Support\Facades\Hash;
class StudentAuthController extends Controller
{
    private $smsService;

    public function __construct(SmsService $smsService)
    {
        $this->smsService = $smsService;
    }

    public function showLoginForm()
    {
        if (Auth::guard('student')->check()) {
            return redirect()->route('student.dashboard');
        }
        return view('students-dashboard.auth.login');
    }

    public function login(Request $request)
    {
        $request->validate([
            'student_id' => 'required',
            'password' => 'required|min:6',
        ]);

        try {
            // Find student info with branch scope applied
            $studentInfo = DB::table('student_infos')->where('student_id_no', $request->student_id)->first();

            if (!$studentInfo) {
                return redirect()->back()
                    ->withInput()
                    ->with('error', 'Invalid Student ID');
            }

            // Get user with branch check
            $user = User::where('id', $studentInfo->user_id)
                       ->first();

            if (!$user) {
                return redirect()->back()
                    ->withInput()
                    ->with('error', 'Invalid student account');
            }

            $credentials = [
                'id' => $user->id,
                'password' => $request->password,
            ];

            if (Auth::guard('student')->attempt($credentials)) {
                // Store branch_id in session for future scope filtering
                session(['branch_id' => $studentInfo->branch_id]);
                
                $request->session()->regenerate();
                return redirect()->route('student.dashboard');
            }

            return redirect()->back()
                ->withInput()
                ->with('error', 'Invalid Credentials!');

        } catch (\Exception $e) {
            return redirect()->back()
                ->withInput()
                ->with('error', 'An error occurred during login');
        }
    }

    public function logout(Request $request)
    {
        Auth::guard('student')->logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        session(['branch_id' => '']);
        return redirect()->route('student.login');
    }


    //forgot password
    public function showForgotPasswordForm()
    {
        return view('students-dashboard.auth.forgot-password');
    }

    public function forgotPassword(Request $request)
    {
        $request->validate([
            'student_id' => 'required',
            // 'phone_number' => 'required|exists:users,phone_number',
        ]);

        $studentInfo = DB::table('student_infos')->where('student_id_no', $request->student_id)->first();

        if (!$studentInfo) {
            return redirect()->back()->with('error', 'Invalid Student ID');
        }

        $user = User::where('id', $studentInfo->user_id)->first();

        if (!$user) {
            return redirect()->back()->with('error', 'Invalid student account');
        }

        $otp = random_int(100000, 999999);
        $user->otp = $otp;
        $user->otp_expires_at = Carbon::now()->addMinutes(2);
        $user->save();

        $userInfo = [
            'phone_number' => $user->phone_number,
            'user_id' => $user->id,
            'email' => $user->email,
            'branch_id' => $user->branch_id,
        ];

        // Simulate sending OTP via SMS
        $status = $this->smsService->sendSms($user->phone_number, "Your EduEasy password reset OTP is, $otp. This OTP will expire in 2 minutes.", 'forgot-password', $userInfo);

        if($status){
            return redirect()->route('student.forgot-password.verify')->with('success', 'OTP sent successfully.');
        }else{
            return redirect()->route('student.forgot-password.verify')->with('error', 'OTP sending failed.');
        }

        // Store phone number in session
        session(['phone_number' => $user->phone_number]);

        return redirect()->route('student.forgot-password.verify')->with('success', 'OTP sent successfully.');
    }

    public function showVerifyOtpForm(Request $request)
    {
        $phone_number = session('phone_number');
        if (!$phone_number) {
            return redirect()->route('student.forgot-password');
        }

        return view('students-dashboard.auth.verify-otp', compact('phone_number'));
    }

    public function verifyOtp(Request $request)
    {
        $request->validate([
            'phone_number' => 'required|exists:users,phone_number',
            'otp' => 'required|digits:6',
        ]);

        $user = User::where('phone_number', $request->phone_number)->first();

        if (!$user) {
            return back()->withErrors(['phone_error' => 'User not found with this phone number.']);
        }

        if (Carbon::now()->greaterThan($user->otp_expires_at)) {
            return back()->withErrors(['otp' => 'OTP has expired. Please request a new one.']);
        }

        if ($user->otp != $request->otp) {
            return back()->withErrors(['otp' => 'Invalid OTP.']);
        }

        $user->otp = null;
        $user->otp_expires_at = null;
        $user->save();

        return redirect()->route('student.forgot-password.reset')->with('success', 'OTP verified successfully.');
    }


    public function showResetPasswordForm(Request $request)
    {
        $phone_number = session('phone_number');
        if (!$phone_number) {
            return redirect()->route('student.forgot-password');
        }

        return view('students-dashboard.auth.reset-password', compact('phone_number'));
    }

    public function resetPassword(Request $request)
    {
        $request->validate([
            'password' => 'required|confirmed|min:6',
        ]);

        $user = User::where('phone_number', session('phone_number'))->first();
        $user->password = Hash::make($request->password);
        $user->save();

        return redirect()->route('student.login')->with('success', 'Password reset successfully.');
    }


    public function updatePassword()
    {
        return view('students-dashboard.auth.password-update');
    }

    public function updatePasswordSubmit(Request $request)
    {
        $request->validate([
            'password' => 'required|confirmed|min:6',
            'password_confirmation' => 'required',
        ]);

        $user = auth()->user();

        User::where('id', $user->id)->update([
            'password' => Hash::make($request->input('password'))
        ]);

        return redirect()->back()->with('status', 'Password updated successfully!');
    }
}
