<?php

namespace App\Http\Controllers\Registeration;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Validator;
use App\Http\Requests\Auth\RegisterationRequest;

class AuthController extends Controller
{

    public function showLogin()
    {
        $quotes = [];
        for ($i = 1; $i <= 3; $i++) {
            array_push($quotes, Inspiring::quote());
        }

        return view('auth.login')->with(['quotes' => $quotes]);
    }

    // public function login(Request $request)
    // {
    //     $validator = Validator::make(
    //         $request->all(),
    //         [
    //             'username' => 'required',
    //             'password' => 'required',
    //         ],
    //         [
    //             'username.required' => 'Please enter username',
    //             'password.required' => 'Please enter password',
    //         ]
    //     );

    //     if ($validator->passes()) {
    //         $username = $request->username;
    //         $password = $request->password;
    //         $remember_me = $request->has('remember_me') ? true : false;

    //         try {
    //             $user = User::where('email', $username)->first();

    //             if (!$user)
    //                 return response()->json(['error2' => 'No user found with this username']);

    //             if ($user->active_status == '0' && !$user->roles)
    //                 return response()->json(['error2' => 'You are not authorized to login, contact HOD']);

    //             if (!auth()->attempt(['email' => $username, 'password' => $password], $remember_me))
    //                 return response()->json(['error2' => 'Your entered credentials are invalid']);

    //             $userType = '';
    //             if ($user->hasRole(['User']))
    //                 $userType = 'user';

    //             return response()->json(['success' => 'login successful', 'user_type' => $userType]);
    //         } catch (\Exception $e) {
    //             DB::rollBack();
    //             Log::info("login error:" . $e);
    //             return response()->json(['error2' => 'Something went wrong while validating your credentials!']);
    //         }
    //     } else {
    //         return response()->json(['error' => $validator->errors()]);
    //     }
    // }


//    public function login(Request $request)
//     {
//         $step = $request->input('step', 1);

//         if ($step == 1) {
//             $validator = Validator::make(
//                 $request->all(),
//                 [
//                     'username' => 'required',
//                     'password' => 'required',
//                 ],
//                 [
//                     'username.required' => 'Please enter username',
//                     'password.required' => 'Please enter password',
//                 ]
//             );

//             if ($validator->fails()) {
//                 return response()->json(['error' => $validator->errors()]);
//             }

//             $username = $request->username;
//             $password = $request->password;

//             try {
//                 DB::beginTransaction();

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

//                 if (!$user) {
//                     DB::rollBack();
//                     return response()->json(['error2' => 'No user found with this username']);
//                 }

//                 if ($user->active_status == '0' && !$user->roles) {
//                     DB::rollBack();
//                     return response()->json(['error2' => 'You are not authorized to login, contact HOD']);
//                 }

//                 if (!auth()->validate(['email' => $username, 'password' => $password])) {
//                     DB::rollBack();
//                     return response()->json(['error2' => 'Your entered credentials are invalid']);
//                 }

//                 $otp = rand(1000, 9999);

//                 $mobile = $user->mobile;
//                 if (!$mobile) {
//                     DB::rollBack();
//                     return response()->json(['error2' => 'Mobile number not found for user']);
//                 }

//                 $text = "OTP for MBMC LOGIN is $otp for Mobile No $mobile. Please do not share OTP with anyone. Regards, Mira Bhaindar Municipal Corporation.";
//                 $url = "https://japi.instaalerts.zone/httpapi/QueryStringReceiver";

//                 $response = Http::get($url, [
//                     'ver' => '1.0',
//                     'key' => 'Isc5fvdX8tT3JF6X9aT9sA==',
//                     'encrpt' => '0',
//                     'dest' => '91' . $mobile,
//                     'send' => 'MBMCPT',
//                     'text' => $text,
//                     'dlt_entity_id' => '1001158085062848906',
//                     'dlt_template_id' => '1007530691210273647',
//                 ]);

//                 if ($response->successful()) {
//                     // Save OTP in users table
//                     $user->otp = $otp;
//                     $user->save();

//                     // Store info in session if needed
//                     session(['otp_mobile' => $mobile, 'otp_user_id' => $user->id]);

//                     DB::commit();

//                     return response()->json(['success' => 'otp generated successfully']);
//                 } else {
//                     DB::rollBack();
//                     return response()->json(['error' => 'Failed to send OTP'], 500);
//                 }
//             } catch (\Exception $e) {
//                 DB::rollBack();
//                 Log::error("Login error: " . $e->getMessage());
//                 return response()->json(['error2' => 'Something went wrong while validating your credentials!']);
//             }
//         }
//         elseif ($step == 2) {
//             $validator = Validator::make(
//                 $request->all(),
//                 [
//                     'otp' => 'required|array|size:4',
//                     'otp.*' => 'required|digits:1',
//                     'username' => 'required',
//                 ],
//                 [
//                     'otp.required' => 'OTP is required',
//                     'otp.size' => 'OTP must be 4 digits',
//                     'otp.*.digits' => 'Each OTP digit must be numeric',
//                     'username.required' => 'Username required',
//                 ]
//             );

//             if ($validator->fails()) {
//                 return response()->json(['error' => $validator->errors()]);
//             }

//             $user = User::where('email', $request->username)->first();

//             if (!$user) {
//                 return response()->json(['error2' => 'User not found']);
//             }

//             $enteredOtp = implode('', $request->otp);
//             $otpValid = $user->otp === $enteredOtp;

//             if (!$otpValid) {
//                 return response()->json(['error2' => 'Invalid or expired OTP']);
//             }

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

//             $userType = '';
//             if ($user->hasRole(['User'])) {
//                 $userType = 'user';
//             }
//             Auth::login($user, $request->has('remember_me'));

//             // Clear OTP after successful login


//             return response()->json(['success' => 'login successful', 'user_type' => $userType]);
//         }
//     }


    // public function login_old(Request $request)
    // {
    //     $step = $request->input('step', 1);

    //     if ($step == 1) {
    //         $validator = Validator::make(
    //             $request->all(),
    //             [
    //                 'username' => 'required',
    //                 'password' => 'required',
    //             ],
    //             [
    //                 'username.required' => 'Please enter username',
    //                 'password.required' => 'Please enter password',
    //             ]
    //         );

    //         if ($validator->fails()) {
    //             return response()->json(['error' => $validator->errors()]);
    //         }

    //         $username = $request->username;
    //         $password = $request->password;

    //         try {
    //             DB::beginTransaction();

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

    //             if (!$user) {
    //                 DB::rollBack();
    //                 return response()->json(['error2' => 'No user found with this username']);
    //             }

    //             if ($user->active_status == '0' && !$user->roles) {
    //                 DB::rollBack();
    //                 return response()->json(['error2' => 'You are not authorized to login, contact HOD']);
    //             }

    //             if (!auth()->validate(['email' => $username, 'password' => $password])) {
    //                 DB::rollBack();
    //                 return response()->json(['error2' => 'Your entered credentials are invalid']);
    //             }

    //             // ✅ OTP Generate depending on environment
    //             $otp = env('APP_ENV') === 'production' ? mt_rand(1000, 9999) : '0000';

    //             $mobile = $user->mobile;
    //             if (!$mobile) {
    //                 DB::rollBack();
    //                 return response()->json(['error2' => 'Mobile number not found for user']);
    //             }

    //             // ✅ SMS send only in production
    //             if (env('APP_ENV') === 'production') {
    //                 $text = "OTP for MBMC LOGIN is $otp for Mobile No $mobile. Please do not share OTP with anyone. Regards, Mira Bhaindar Municipal Corporation.";
    //                 $url = "https://japi.instaalerts.zone/httpapi/QueryStringReceiver";

    //                 $response = Http::get($url, [
    //                     'ver' => '1.0',
    //                     'key' => 'Isc5fvdX8tT3JF6X9aT9sA==',
    //                     'encrpt' => '0',
    //                     'dest' => '91' . $mobile,
    //                     'send' => 'MBMCPT',
    //                     'text' => $text,
    //                     'dlt_entity_id' => '1001158085062848906',
    //                     'dlt_template_id' => '1007530691210273647',
    //                 ]);

    //                 if (!$response->successful()) {
    //                     DB::rollBack();
    //                     return response()->json(['error' => 'Failed to send OTP'], 500);
    //                 }
    //             } else {


    //             }

    //             // Save OTP in users table
    //             $user->otp = $otp;
    //             $user->save();

    //             // Store info in session if needed
    //             session(['otp_mobile' => $mobile, 'otp_user_id' => $user->id]);

    //             DB::commit();

    //             return response()->json(['success' => 'otp generated successfully']);
    //         } catch (\Exception $e) {
    //             DB::rollBack();
    //             Log::error("Login error: " . $e->getMessage());
    //             return response()->json(['error2' => 'Something went wrong while validating your credentials!']);
    //         }
    //     }
    //     elseif ($step == 2) {
    //         $validator = Validator::make(
    //             $request->all(),
    //             [
    //                 'otp' => 'required|array|size:4',
    //                 'otp.*' => 'required|digits:1',
    //                 'username' => 'required',
    //             ],
    //             [
    //                 'otp.required' => 'OTP is required',
    //                 'otp.size' => 'OTP must be 4 digits',
    //                 'otp.*.digits' => 'Each OTP digit must be numeric',
    //                 'username.required' => 'Username required',
    //             ]
    //         );

    //         if ($validator->fails()) {
    //             return response()->json(['error' => $validator->errors()]);
    //         }

    //         $user = User::where('email', $request->username)->first();

    //         if (!$user) {
    //             return response()->json(['error2' => 'User not found']);
    //         }

    //         $enteredOtp = implode('', $request->otp);
    //         $otpValid = $user->otp === $enteredOtp;

    //         if (!$otpValid) {
    //             return response()->json(['error2' => 'Invalid or expired OTP']);
    //         }

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

    //         $userType = '';
    //         if ($user->hasRole(['User'])) {
    //             $userType = 'user';
    //         }
    //         Auth::login($user, $request->has('remember_me'));

    //         return response()->json(['success' => 'login successful', 'user_type' => $userType]);
    //     }
    // }



    public function login(Request $request)
{
    $step = $request->input('step', 1);

    if ($step == 1) {
        $validator = Validator::make(
            $request->all(),
            [
                'username' => 'required',
                'password' => 'required',
            ],
            [
                'username.required' => 'Please enter username',
                'password.required' => 'Please enter password',
            ]
        );

        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()]);
        }

        $username = $request->username;
        $password = $request->password;

        try {
            DB::beginTransaction();

            $user = User::where('email', $username)->first();

            if (!$user) {
                DB::rollBack();
                return response()->json(['error2' => 'No user found with this username']);
            }

            if ($user->active_status == '0' && !$user->roles) {
                DB::rollBack();
                return response()->json(['error2' => 'You are not authorized to login, contact HOD']);
            }

            if (!auth()->validate(['email' => $username, 'password' => $password])) {
                DB::rollBack();
                return response()->json(['error2' => 'Your entered credentials are invalid']);
            }

            // ✅ OTP Generate depending on domain name
            $otp = request()->getHost() == 'mbmcrts.in' && $user->email != 'admin@gmail.com'
                ? mt_rand(1000, 9999)
                : '0000';

            $mobile = $user->mobile;
            if (!$mobile) {
                DB::rollBack();
                return response()->json(['error2' => 'Mobile number not found for user']);
            }

            // ✅ Send OTP SMS only if on production domain
            if (request()->getHost() == 'mbmcrts.in') {
                $text = "OTP for MBMC LOGIN is $otp for Mobile No $mobile. Please do not share OTP with anyone. Regards, Mira Bhaindar Municipal Corporation.";
                $url = "https://japi.instaalerts.zone/httpapi/QueryStringReceiver";

                $response = Http::get($url, [
                    'ver' => '1.0',
                    'key' => 'Isc5fvdX8tT3JF6X9aT9sA==',
                    'encrpt' => '0',
                    'dest' => '91' . $mobile,
                    'send' => 'MBMCPT',
                    'text' => $text,
                    'dlt_entity_id' => '1001158085062848906',
                    'dlt_template_id' => '1007530691210273647',
                ]);

                if (!$response->successful()) {
                    DB::rollBack();
                    return response()->json(['error' => 'Failed to send OTP'], 500);
                }
            }

            // ✅ Save OTP in users table
            $user->otp = $otp;
            $user->save();

            // ✅ Store info in session
            session(['otp_mobile' => $mobile, 'otp_user_id' => $user->id]);

            DB::commit();

            return response()->json(['success' => 'OTP generated successfully']);
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error("Login error: " . $e->getMessage());
            return response()->json(['error2' => 'Something went wrong while validating your credentials!']);
        }
    }

    elseif ($step == 2) {
        $validator = Validator::make(
            $request->all(),
            [
                'otp' => 'required|array|size:4',
                'otp.*' => 'required|digits:1',
                'username' => 'required',
            ],
            [
                'otp.required' => 'OTP is required',
                'otp.size' => 'OTP must be 4 digits',
                'otp.*.digits' => 'Each OTP digit must be numeric',
                'username.required' => 'Username required',
            ]
        );

        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()]);
        }

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

        if (!$user) {
            return response()->json(['error2' => 'User not found']);
        }

        $enteredOtp = implode('', $request->otp);
        $otpValid = $user->otp === $enteredOtp;

        if (!$otpValid) {
            return response()->json(['error2' => 'Invalid or expired OTP']);
        }

        // ✅ Clear OTP after verification
        $user->otp = null;
        $user->save();

        $userType = '';
        if ($user->hasRole(['User'])) {
            $userType = 'user';
        }

        Auth::login($user, $request->has('remember_me'));

        return response()->json(['success' => 'login successful', 'user_type' => $userType]);
    }
}




public function resendOtp(Request $request)
{
    $username = $request->input('username');

    if (!$username) {
        return response()->json(['error2' => 'Username is required']);
    }

    $user = User::where('email', $username)->first();
    if (!$user) {
        return response()->json(['error2' => 'User not found']);
    }

    $otp = env('APP_ENV') === 'production' ? mt_rand(1000, 9999) : '0000';

    $mobile = $user->mobile;
    if (!$mobile) {
        return response()->json(['error2' => 'Mobile number not found for user']);
    }

    // Send SMS in production
    if (env('APP_ENV') === 'production') {
        $text = "OTP for MBMC LOGIN is $otp for Mobile No $mobile. Please do not share OTP with anyone. Regards, Mira Bhaindar Municipal Corporation.";
        $url = "https://japi.instaalerts.zone/httpapi/QueryStringReceiver";

        $response = Http::get($url, [
            'ver' => '1.0',
            'key' => 'Isc5fvdX8tT3JF6X9aT9sA==',
            'encrpt' => '0',
            'dest' => '91' . $mobile,
            'send' => 'MBMCPT',
            'text' => $text,
            'dlt_entity_id' => '1001158085062848906',
            'dlt_template_id' => '1007530691210273647',
        ]);

        if (!$response->successful()) {
            return response()->json(['error' => 'Failed to send OTP'], 500);
        }
    }

    // Save OTP
    $user->otp = $otp;
    $user->save();

    // Store session info if needed
    session(['otp_mobile' => $mobile, 'otp_user_id' => $user->id]);

    return response()->json(['success' => 'OTP resent successfully']);
}






    public function logout()
    {
        auth()->logout();

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


    public function showChangePassword()
    {
        return view('auth.change-password');
    }


    public function changePassword(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'old_password' => 'required',
            'password' => 'required',
            'confirm_password' => 'required|same:password',
        ]);

        if ($validator->passes()) {
            $old_password = $request->old_password;
            $password = $request->password;

            try {
                $user = DB::table('users')->where('id', $request->user()->id)->first();

                if (Hash::check($old_password, $user->password)) {
                    DB::table('users')->where('id', $request->user()->id)->update(['password' => Hash::make($password)]);

                    return response()->json(['success' => 'Password changed successfully!']);
                } else {
                    return response()->json(['error2' => 'Old password does not match']);
                }
            } catch (\Exception $e) {
                DB::rollBack();
                Log::info("password change error:" . $e);
                return response()->json(['error2' => 'Something went wrong while changing your password!']);
            }
        } else {
            return response()->json(['error' => $validator->errors()]);
        }
    }

    // function for show register
    public function showRegister()
    {
        return view('auth.register');
    }

    // function to register user
    public function register(RegisterationRequest $request)
    {
        if ($request->ajax()) {
            $user = User::create($request->all());

            DB::table('model_has_roles')->insert(['role_id' => 2, 'model_type' => 'App\Models\User', 'model_id' => $user->id]);

            return response()->json([
                'success' =>'User created successfully please login',
                'users' => $user
            ]);
        }
    }
}
