<?php

namespace App\Http\Controllers\superadmin;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoresuperadminRequest;
use App\Http\Requests\UpdatesuperadminRequest;
use App\Models\superadmin;
use Illuminate\Http\Request;
use Validator,Redirect,Response;
use Illuminate\Support\Facades\DB;
use App\Models\Websitesetting;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Mail;
use App\Mail\AdminSendOTP;
use App\Mail\SuperadminSendmail;
use Illuminate\Support\Facades\Http;
use Jenssegers\Agent\Agent;
use Crypt;
use Session;
use Hash;
use Illuminate\Support\Str;

class SuperadminController extends Controller
{
   public function login(Request $request){

    $superadminId = $request->session()->get('SUPERADMIN_ID');
    $superadminDetails = $request->session()->get('SUPERADMIN_DETAILS');

    if ($superadminId && isset($superadminDetails['password'])) {

        $admin = superadmin::where('id', $superadminId)->first();

        if (
            $admin &&
            $admin->password == $superadminDetails['password']
        ) {
            return redirect('superadmin/index');
        } else {

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

            return redirect('superadmin/login');
        }
    }

    return view("superadmin.login");
}
    
   public function index(Request $request){

    $superadminId = $request->session()->get('SUPERADMIN_ID');
    $superadminDetails = $request->session()->get('SUPERADMIN_DETAILS');

    $admin = superadmin::where('id', $superadminId)->first();

    if (
        !$superadminId ||
        !isset($superadminDetails['password']) ||
        !$admin ||
        $admin->password != $superadminDetails['password']
    ) {

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

        return redirect('superadmin/login')
            ->with('error', 'Session expired. Please login again.');
    }

    return view("superadmin.index");
}

    public function login_process(Request $request) {
        $result = superadmin::where('email', $request->email)->first(); 

        if ($result) {
            if (Hash::check($request->password, $result->password)) {
                $otp = 123456;
                $token = substr("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", mt_rand(0, 51), 1) . substr(md5(time()), 1);

                DB::table('superadmins')->where('id', $result->id)->update([
                    'otp' => $otp,
                    'token' => $token,
                ]);

                $admindata = [
                    'otp' => $otp,
                    'firstname' => $result->firstname,
                    'lastname' => $result->lastname,
                ];

                try {
                    Mail::to($request->email)->send(new AdminSendOTP($admindata));
                } catch (\Exception $e) {
                    return back()->with('error', $e->getMessage());
                }

                // -------- Insert login log --------
                $user_id = $result->id;
                $after = json_encode($result);
                $before = null;
                 insertLogsAPI($user_id, '5', 'Superadmin Login', '0', '', '', '', '', $after, $before, ''); 
                // ----------------------------------

                return redirect(asset('superadmin/adminotp/' . $token))
                    ->with('success', 'OTP send successful. Please check your email.');
            } else {
                toastr()->error('Please enter valid password');
                return back();
            }
        } else {
            toastr()->error('Please enter valid email id');
            return back();
        }
    }

    public function adminotp(Request $request) {
        $admin = superadmin::where('token', $request->token)->first();
        if ($admin) {
            $data['token'] = $admin;
        } else {
            return redirect()->back()->with('error', 'Invalid token');
        }
        return view('superadmin.adminotp', $data);
    }

    function adminotpverifyupdate(Request $request) {
        $admin = superadmin::where('token', $request->token)->first();
        if (!$admin) {
            return redirect()->back()->with('error', 'User not found.');
        }
        
        if ($admin->otp == $request->otp) {
            $admin->verift_status = '1';  
            $admin->token = substr("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", mt_rand(0, 51), 1) . substr(md5(time()), 1);  
            $admin->save();
            
            $request->session()->put('SUPERADMIN_ID', $admin->id);
            $request->session()->put('SUPERADMIN_DETAILS', [
                'username' => $admin->username,
                'email' => $admin->email,
                'mobile' => $admin->mobile,
                'password' => $admin->password
            ]);
            
            return redirect(asset('superadmin/index'))->with('success', 'Admin OTP Verified Successfully.');
        } else {
            return redirect()->back()->with('error', 'Invalid OTP. Please try again.');
        }
    }

    public function adminresendotp(Request $request) {
        $admin = superadmin::where('token', $request->token)->first();

        if (!$admin) {
            return redirect()->back()->with('error', 'Invalid token or user not found.');
        }

        $admin->otp = rand(100000, 999999);
        $admin->token = substr("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", mt_rand(0, 51), 1) . substr(md5(time()), 1);

        $admindata = [
            'otp' => $admin->otp,
            'firstname' => $admin->firstname,
            'lastname' => $admin->lastname,
        ];

        try {
            $setting = Websitesetting::where('id', 1)->first();

            if (!empty($admin->email)) {
                Mail::to(trim($admin->email))->send(new AdminSendOTP($admindata));
            }

            if (!empty($setting->emailtags)) {
                $emails = explode(',', $setting->emailtags);
                foreach ($emails as $email) {
                    $email = trim($email);
                    if (!empty($email) && filter_var($email, FILTER_VALIDATE_EMAIL)) {
                        Mail::to($email)->send(new AdminSendOTP($admindata));
                    }
                }
            }

        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }

        $admin->save();

        return redirect(asset('superadmin/adminotp/' . $admin->token))
            ->with('success', 'OTP resend successful. Please check your email.');
    }

    function logout(Request $request) {
        $request->session()->flush();
        return redirect('superadmin/login')->with('success','Successfully! Logout');
    }

    function forgotpassword() {
        return view('superadmin.login.forgotpassword');
    }
    
    function forchangepassword(Request $request){
        $email = $request->email;
        $superadmin = superadmin::where('email',$email)->first();

        if($superadmin){
            $superadmin->token = substr("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", mt_rand(0, 51), 1).substr(md5(time()), 1);
            $superadmin->save();
            
            $url = url("superadmin/updatepassword/".$superadmin->token);

            $emailData = ['url' => $url];
            $email = new SuperadminSendmail($emailData);
            Mail::to($request->email)->send($email);

            return redirect()->back()->with('success', 'Email Sent!');
        } else {
            return redirect()->back()->with('error', 'This email address is not registered.');
        }
    }  

    function updatepassword(Request $request){
        $data['token'] = superadmin::where('token',$request->token)->first();
        return view("superadmin.login.forchangepassword",$data);
    }

    function updatechangepassword(Request $request){
        $update = superadmin::where('token',$request->token)->first();
        $before = json_encode($update);

        $update->password = Hash::make($request->password);
        $update->token = $request->token;
        $update->save();

        $after = json_encode($update);

        // Insert log for password change
        $user_id = $update->id;
        insertLogsAPI($user_id,'6','Superadmin Password Change','0','','','',$before,$after,'',''); 

        // Flush session to force re-login after password change
        $request->session()->flush();

        return redirect(asset('superadmin/login'))->with('success', 'Password changed successfully. Please login again.');
    }
}