<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Mail\AdminPasswordResetEmail;
use Illuminate\Http\Request;
use App\Models\IamPrincipal;
use App\Models\IamPrincipalOtp;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Carbon;

class LoginController extends Controller
{
    /**
     * Created By : sayli Raut
     * Created at : 17 May 2024
     * Use : To view admin login page.
     */
    public function index()
    {
        return view('Admin.pages.auth.login');
    }

    /**
     * Created By : sayli Raut
     * Created at : 21 May 2024
     * Use : To check login.
     */
    public function login_check(Request $request)
    {
        $validatedData = $request->validate([
            'email' => 'required|email',
            'password' => 'required|string',
        ]);

        $user = IamPrincipal::where('email_address', $validatedData['email'])
            ->whereIn('principal_type_xid', [1, 2])
            ->first();

        if ($user) {
            if (Hash::check($validatedData['password'], $user->password)) {

                Auth::guard('admin')->login($user);
                return jsonResponseWithSuccessMessage(__('success.authentic_success'), 200);
            } else {
                return jsonResponseWithErrorMessage(__('auth.password'), 401);
            }
        } else {
            return jsonResponseWithErrorMessage(__('auth.email'), 401);
        }
    }


    /**
     * Created By : sayli Raut
     * Created at : 21 May 2024
     * Use : To view forgot password page.
     */
    public function forgot_password()
    {
        return view('Admin.pages.auth.forgot_password');
    }


    /**
     * Created By : sayli Raut
     * Created at : 21 May 2024
     * Use : To send otp.
     */
    public function add_forgot_password(Request $request)
    {
        $user = DB::table('iam_principal')->where('email_address', $request->email)->first();
        if (!$user) {
            return jsonResponseWithErrorMessage(__('auth.email'), 404);
        }

        $otp = rand(1234, 9999);
        $expirationTime = now()->addMinutes(5);

        $data = [
            'principal_xid' => $user->id,
            'otp_code' => $otp,
            'otp_purpose' => 'admin forgot password',
            'valid_till' => $expirationTime,
            'created_at' => Carbon::now(),
        ];

        $user_token = DB::table('iam_principal_otp')->where('principal_xid', $user->id)->first();
        if ($user_token) {
            DB::table('iam_principal_otp')
                ->where('principal_xid', $user->id)
                ->update($data);
        } else {
            DB::table('iam_principal_otp')
                ->insert($data);
        }

        Session::put('admin_data', $data);

        $sessionDetails = Session::get('admin_data');

        Mail::to($request->email)->send(new AdminPasswordResetEmail($data));

        return jsonResponseWithSuccessMessage(__('success.authentic_success'), 200);
    }


    /**
     * Created By : sayli Raut
     * Created at : 21 May 2024
     * Use : To view otp page.
     */
    public function otp_page()
    {
        return view('Admin.pages.auth.otp');
    }


    /**
     * Created By : sayli Raut
     * Created at : 21 May 2024
     * Use : To verify otp.
     */
    public function verify_otp(Request $request)
    {
        try {
            $admin = IamPrincipalOtp::where('principal_xid', $request->id)
                ->where('otp_code', $request->otp)
                ->where('valid_till', '>', now())
                ->first();

            if ($admin) {
                return jsonResponseWithSuccessMessage(__('success.confirmed_password'), 200);
            } else {
                return jsonResponseWithErrorMessage(__('auth.otp_expired_invalid'), 401);
            }
        } catch (\Exception $e) {
            Log::error('Passport function failed: ' . $e->getMessage());
            return jsonResponseWithErrorMessage(__('auth.something_went_wrong'), 500);
            return response()->json(['error' => $e->getMessage()]);
        }
    }


    /**
     * Created By : sayli Raut
     * Created at : 21 May 2024
     * Use : To view resend otp page.
     */
    public function reset_password_page()
    {
        return view('Admin.pages.auth.password_reset');
    }


    /**
     * Created By : sayli Raut
     * Created at : 21 May 2024
     * Use : To update password.
     */
    public function updatePassword(Request $request)
    {
        $id = $request->reset_id;
        $user = IamPrincipal::find($id);
        if (!$user) {
            return jsonResponseWithErrorMessage(__('auth.user_not_found'), 404);
        }

        $user->update([
            'password' => Hash::make($request->confirm_password),
        ]);

        return jsonResponseWithSuccessMessage(__('success.update_data'), 200);
    }

    /**
     * Created By : sayli Raut
     * Created at : 21 May 2024
     * Use : To logout admin.
     */
    public function logout()
    {
        Auth::guard('admin')->logout();
        return redirect('/');
    }
}
