Title of Work: Email Insight 
Category: Computer Software (Literary Work)
Language: Php (Laravel Framework)
Author: Mukesoft Pvt. Ltd.
Year of Creation: 2025
Description: A software platform for AMC contract management, technician tracking, and customer service requests.
1) Module: Login Page
Module Description:- The login page offers a clean, modern, and responsive UI built with Laravel and Bootstrap 5. 
It includes:
•	Logo and branding for a professional look.
•	User authentication with email and password fields.
•	Login restricted to Google Workspace and Outlook users only for enhanced data security and seamless integration.
•	Error handling to display invalid login attempts.
•	OTP-based verification for an additional layer of security during login.
•	Navigation links for password recovery and new user registration.
•	Responsive design to ensure compatibility across devices.
a)Login Page Front end Code:-
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
    <!-- Bootstrap CDN -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

    <style>
        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(to right, #f6f8fc, #e8f0fe);
            height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .login-card {
            background-color: #ffffff;
            padding: 40px 35px;
            border-radius: 16px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
            width: 100%;
            max-width: 420px;
        }

        .login-title {
            text-align: center;
            font-size: 26px;
            font-weight: 600;
            color: #2f3542;
            margin-bottom: 10px;
        }

        .login-subtitle {
            text-align: center;
            font-size: 14px;
            color: #57606f;
            margin-bottom: 25px;
        }

        .form-label {
            font-weight: 500;
            color: #2f3542;
        }

        .form-control {
            border-radius: 10px;
            padding: 10px;
            font-size: 15px;
            border: 1px solid #ced6e0;
        }

        .btn-login {
            background-color: #4c83ff;
            border: none;
            border-radius: 10px;
            color: #fff;
            padding: 12px;
            font-weight: 600;
            width: 100%;
            transition: 0.3s ease;
        }

        .btn-login:hover {
            background-color: #3a6ee8;
        }

        .form-footer {
            text-align: center;
            font-size: 14px;
            margin-top: 20px;
            color: #57606f;
        }

        .form-footer a {
            color: #4c83ff;
            text-decoration: none;
        }

        .form-footer a:hover {
            text-decoration: underline;
        }

        .logo {
            width: 60px;
            display: block;
            margin: 0 auto 15px;
        }
    </style>
</head>

<body class="d-flex align-items-center justify-content-center vh-100 bg-light">

    <div class="login-card">

        <img src="{{ asset('/img/logo.jpeg') }}" alt="Logo" class="mb-3 mx-auto d-block"
            style="width: 200px; height: auto; border-radius: 8px;">
        <h2 class="login-title">Welcome to AI Email Insights</h2>
        <p class="login-subtitle">Sign in to continue to your dashboard</p>
        <!-- Error Message -->
        @if (session('error'))
            <div class="alert alert-danger">
                {{ session('error') }}
            </div>
        @endif
        <form action="{{ route('login') }}" method="POST">
            @csrf
            <div class="mb-3">
                <label for="email" class="form-label">Email address</label>
                <input type="email" name="email" class="form-control" id="email" placeholder="you@example.com"
                    required>
            </div>
            <div class="mb-3">
                <label for="password" class="form-label">Password</label>
                <input type="password" name="password" class="form-control" id="password" placeholder="••••••••"
                    required>
            </div>
            <button type="submit" class="btn btn-login">Login</button>
            <div class="form-footer mt-3">
               <a href="{{ route('password.request') }}">Forgot password?</a> | <a href="{{ route('register') }}">Create an account</a>
            </div>
        </form>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

    {{-- old --}}
    {{-- <div class="card shadow-lg p-4" style="width: 350px;">
        <h2 class="text-center mb-3">Login</h2>

        <!-- Error Message -->
        @if (session('error'))
            <div class="alert alert-danger">
                {{ session('error') }}
            </div>
        @endif

        <!-- Login Form -->
        <form action="{{ route('login') }}" method="POST">
            @csrf

            <!-- Email -->
            <div class="mb-3">
                <label class="form-label">Email</label>
                <input type="email" name="email" class="form-control" required>
            </div>

            <!-- Password -->
            <div class="mb-3">
                <label class="form-label">Password</label>
                <input type="password" name="password" class="form-control" required>
            </div>

            <!-- Submit Button -->
            <button type="submit" class="btn btn-primary w-100">Login</button>
            <!-- <a href="{{ route('register') }}" class="btn btn-secondary w-100 mt-3">Ragister</a> -->
        </form>
    </div> --}}

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>

</html>
b)Login Backend Code :- 

    public function check_conn_service_Account($email) //worksapce service accoutn check connetion
    {
        try {
            // ---------------- Service account setup ----------------
            // ---------------- CONFIG ----------------
            $SERVICE_ACCOUNT_FILE = storage_path('app/email/service-account.json');
            if (!file_exists($SERVICE_ACCOUNT_FILE)) {
                return [
                    'success' => false,
                    "message" => "Service account JSON file not found.",
                    "error" => "Missing service-account.json",
                    "code" => 408,
                    "file_path" => $SERVICE_ACCOUNT_FILE
                ];
            }
            $IMPERSONATED_EMAIL = $email;
            // ---------------- 1. Load Service Account JSON ----------------
            $json = file_get_contents($SERVICE_ACCOUNT_FILE);
            $data = json_decode($json, true);

            $client_email = $data['client_email'];
            $private_key = $data['private_key']; // this is a PEM 

            // ---------------- 2. Create JWT using package----------------
            $now = time();

            $payload = [
                "iss" => $client_email,
                "sub" => $IMPERSONATED_EMAIL,
                "scope" => "https://www.googleapis.com/auth/gmail.readonly",
                "aud" => "https://oauth2.googleapis.com/token",
                "iat" => $now,
                "exp" => $now + 3600
            ];

            // Create JWT using RS256 algorithm and your private key
            $jwt = JWT::encode($payload, $private_key, 'RS256');
            // ---------------- 3. Exchange JWT for Access Token ----------------
            $token_url = "https://oauth2.googleapis.com/token";
            $post_fields = http_build_query([
                'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
                'assertion' => $jwt
            ]);

            $ch = curl_init($token_url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Content-Type: application/x-www-form-urlencoded'
            ]);
            $response = curl_exec($ch);
            curl_close($ch);

            $token_data = json_decode($response, true);

            if (!isset($token_data['access_token'])) {
                return [
                    'message' => 'Service Google work-space Account Connection Failed: You Are not Company Team member Failed to get access token.',
                    'success' => false,
                    "code" => 430,
                    'error' => $token_data
                ];
                // echo "❌ Failed to get access token:<br>";
                // print_r($token_data);
                // exit;
            }
            $access_token = $token_data['access_token'];
            return [
                'success' => true,
                "code" => 200,
                'message' => "Service Account Connection Established Successfully!"
            ];
        } catch (\Exception $e) {
            // Handle any unexpected exceptions
            return [
                'success' => false,
                "code" => 500,
                'message' => "Catch block " . $e->getMessage()
                //   'message' => "Please send valid email or app password Exception: " . $e->getMessage()
            ];
        }
    }

    public function check_conn_outlook_Account($email)
    {
        try {
            // ========================
            // CONFIGURATION VARIABLES
            // ========================
            $tenantId     = "390abb91-8569-49d7-8fa5-e4467521cdea"; // Azure Tenant ID
            $clientId     = "1959220a-f969-4213-958c-7c3f120c0fed"; // App (Client) ID
            $clientSecret = "7DX8Q~zidSrJ7pZTshP_Q2nrjMiPsStrI5nLXcIT"; // Client Secret
            $redirectUri  = "https://serviz4u.mukesoft.com/callback.php"; // Redirect URI
            $tokenFile    = storage_path('app/email/outlook_account.json'); // Token storage file
            $userEmail    = $email; // Email account
            // =======================================
            // STEP 1: CHECK IF ACCESS TOKEN IS CACHED
            // =======================================
            $accessToken = "";
            $tokenData   = [];
            // Step 2: Check token file
            if (!file_exists($tokenFile)) {
                return [
                    'success'   => false,
                    'message'   => "Token file not found." . $tokenFile,
                    'error'     => "Missing token.json",
                    'code'      => 408,
                    'file_path' => $tokenFile
                ];
            }
            if (file_exists($tokenFile)) {
                $tokenData = json_decode(file_get_contents($tokenFile), true);

                if (!empty($tokenData['access_token']) && !empty($tokenData['expires_at'])) {
                    if (time() < $tokenData['expires_at']) {
                        // echo "Using cached token...<br>";
                        $accessToken = $tokenData['access_token'];
                    } else {
                        // ====================================================
                        // STEP 2: IF TOKEN NOT AVAILABLE OR EXPIRED, GET NEW
                        // ====================================================
                        if (empty($accessToken)) {
                            // echo "Token expired or missing, requesting new token...<br>";

                            $url = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token";

                            $postFields = [
                                'client_id'     => $clientId,
                                'scope'         => 'https://graph.microsoft.com/.default',
                                'client_secret' => $clientSecret,
                                'grant_type'    => 'client_credentials',
                            ];

                            $ch = curl_init($url);
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                            curl_setopt($ch, CURLOPT_POST, true);
                            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postFields));
                            $response = curl_exec($ch);
                            curl_close($ch);

                            $data = json_decode($response, true);

                            if (isset($data['access_token'])) {
                                $data['expires_at'] = time() + $data['expires_in'] - 60;

                                if (!is_dir(dirname($tokenFile))) {
                                    mkdir(dirname($tokenFile), 0777, true);
                                }

                                file_put_contents($tokenFile, json_encode($data));
                                $accessToken = $data['access_token'];
                            } else {
                                return [
                                    'success'   => false,
                                    'message'   => "Failed to get access token: " . $response,
                                    'error'     => "Failed to get access toekn ",
                                    'code'      => 401
                                ];
                                // die("Failed to get access token: " . $response);
                            }
                        }
                        // return [
                        //     'success'   => false,
                        //     'message'   => "Please Provide a valid toekn ",
                        //     'error'     => "Token Expire ",
                        //     'code'      => 401
                        // ];
                    }
                }
            }

            // ================================
            // STEP 3: FETCH LATEST EMAIL ID
            // ================================
            $listUrl = "https://graph.microsoft.com/v1.0/users/" . urlencode($userEmail) . "/messages?\$top=1&\$orderby=receivedDateTime%20DESC";

            $ch = curl_init($listUrl);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                "Authorization: Bearer $accessToken",
                "Accept: application/json",
            ]);
            $listResponse = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            if ($httpCode != 200) {
                return [
                    'message' => 'Service Outlook Account Connection Failed: You Are not Company Team member Failed to get access.',
                    'success' => false,
                    "code" => 430,
                    'error' => "Failed to fetch emails list: HTTP $httpCode, response: $listResponse"
                ];
                // die("Failed to fetch emails list: HTTP $httpCode, response: $listResponse");
            }
            return [
                'success' => true,
                "code" => 200,
                'message' => "Service Outlook Account Connection Established Successfully!"
            ];
        } catch (\Exception $e) {
            // Handle any unexpected exceptions
            return [
                'success' => false,
                "code" => 500,
                'message' => "Catch block " . $e->getMessage()
                //   'message' => "Please send valid email or app password Exception: " . $e->getMessage()
            ];
        }
    }
    public function login(Request $request)
    {
        $credentials = $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

        // dd($credentials);

        if (Auth::validate($credentials)) {
            $user = User::where('email', $request->email)->first();

            if ($user && $user->user_level == 0) {
                return back()->with('error', 'Only Admin Or Department Head Have Access');
            }

            //uncomment this block for testing ks0530 8-2-2025
            if (Auth::attempt($credentials)) {
                $user = Auth::user();
                // dd($user);
                // $imapResponse = $this->check_conn($user->email, $user->app_email_pass);

                // if (!$imapResponse['success']) {
                //     // If connection fails, redirect back with error message
                //     $message="Your App password is expire please genrate a new app password via your google account and fill up this given link ->";
                //     return back()->with('error', $message);
                //     // return back()->with('error', $imapResponse['message']);
                // }

                return redirect()->route('dashboard')->with('success', 'Login Successful!');
            }
            //uncomment this block for testing ks0530 8-2-2025

            // Generate OTP
            $otp = rand(100000, 999999);

            DB::table('user_otps')->updateOrInsert(
                ['user_id' => $user->id],
                ['otp' => $otp, 'expires_at' => now()->addMinutes(5), 'created_at' => now()]
            );

            // Send OTP
            $this->sendOtpEmail($user->email, $otp);

            return redirect()->route('otp.form', ['user' => $user->id]);
        }

        return back()->with('error', 'Invalid Email or Password');
    }
c)Opt Front End Code :-
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Verify OTP</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

    <style>
        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(to right, #f6f8fc, #e8f0fe);
            height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .login-card {
            background-color: #ffffff;
            padding: 40px 35px;
            border-radius: 16px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
            width: 100%;
            max-width: 420px;
        }

        .login-title {
            text-align: center;
            font-size: 26px;
            font-weight: 600;
            color: #2f3542;
            margin-bottom: 10px;
        }

        .login-subtitle {
            text-align: center;
            font-size: 14px;
            color: #57606f;
            margin-bottom: 25px;
        }

        .form-label {
            font-weight: 500;
            color: #2f3542;
        }

        .form-control {
            border-radius: 10px;
            padding: 10px;
            font-size: 15px;
            border: 1px solid #ced6e0;
        }

        .btn-login {
            background-color: #4c83ff;
            border: none;
            border-radius: 10px;
            color: #fff;
            padding: 12px;
            font-weight: 600;
            width: 100%;
            transition: 0.3s ease;
        }

        .btn-login:hover {
            background-color: #3a6ee8;
        }

        .timer-text {
            text-align: center;
            color: #57606f;
            margin-top: 15px;
            font-size: 14px;
        }

        .btn-resend {
            display: block;
            margin: 10px auto 0;
        }
    </style>
</head>

<body>
    <div class="login-card">

        <img src="{{ asset('/img/logo.jpeg') }}" alt="Logo" class="mb-3 mx-auto d-block"
            style="width: 200px; height: auto; border-radius: 8px;">
        <h2 class="login-title">OTP Verification</h2>
        <p class="login-subtitle">Enter the OTP sent to your registered email</p>

        @if(session('error'))
            <div class="alert alert-danger">{{ session('error') }}</div>
        @endif

        @if(session('success'))
            <div class="alert alert-success">{{ session('success') }}</div>
        @endif

        <form method="POST" action="{{ route('otp.verify') }}">
            @csrf
            <input type="hidden" name="user_id" value="{{ $userId }}">

            <div class="mb-3">
                <label for="otp" class="form-label">OTP</label>
                <input type="text" name="otp" id="otp" class="form-control" required maxlength="6" placeholder="Enter OTP">
            </div>

            <button type="submit" class="btn btn-login">Verify OTP</button>
        </form>

        <input type="hidden" id="user_id" value="{{ $userId }}">
        <div class="timer-text" id="timerText">
            Resend OTP in <span id="timer">60</span>s
        </div>
        <button type="button" class="btn btn-outline-secondary btn-sm btn-resend d-none" id="resendBtn">
            Resend OTP
        </button>
    </div>

    <script>
        let countdown = 60;
        const resendBtn = document.getElementById('resendBtn');
        const timerText = document.getElementById('timerText');
        const timerSpan = document.getElementById('timer');
        const userId = document.getElementById('user_id').value;

        const startTimer = () => {
            countdown = 60;
            timerSpan.textContent = countdown;
            timerText.classList.remove('d-none');
            resendBtn.classList.add('d-none');

            const interval = setInterval(() => {
                countdown--;
                timerSpan.textContent = countdown;

                if (countdown <= 0) {
                    clearInterval(interval);
                    timerText.classList.add('d-none');
                    resendBtn.classList.remove('d-none');
                    resendBtn.textContent = "Resend OTP";
                    resendBtn.disabled = false;
                }
            }, 1000);
        };

        window.onload = startTimer;

        resendBtn.addEventListener('click', () => {
            resendBtn.disabled = true;
            resendBtn.textContent = "Sending...";

            fetch("{{ route('otp.resend') }}", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "X-CSRF-TOKEN": "{{ csrf_token() }}"
                },
                body: JSON.stringify({ user_id: userId })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert("OTP resent successfully.");
                    startTimer();
                } else {
                    resendBtn.textContent = "Failed. Retry";
                    resendBtn.disabled = false;
                }
            })
            .catch(() => {
                resendBtn.textContent = "Retry";
                resendBtn.disabled = false;
            });
        });
    </script>
</body>
</html>
d)Otp Back End Code :- 

    public function showOtpForm(User $user)
    {
        return view('login.otp_verify', ['userId' => $user->id]);
    }

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

        $otpRecord = DB::table('user_otps')
            ->where('user_id', $request->user_id)
            ->where('otp', $request->otp)
            ->where('expires_at', '>=', now())
            ->first();

        if ($otpRecord) {
            Auth::loginUsingId($request->user_id);
            DB::table('user_otps')->where('user_id', $request->user_id)->delete(); // remove used OTP
            //   dd('Redirecting to dashboard...'); // Add this line temporarily
            return redirect()->route('dashboard');
        }

        return back()->with('error', 'Invalid or expired OTP');
    }
    private function sendOtpEmail($email, $otp)
    {
        $mail = new PHPMailer(true);
        try {
            $mail->isSMTP();
            $mail->Host       = 'smtp.gmail.com';
            $mail->SMTPAuth   = true;
            $mail->Username   = 'monika.mukesoft@gmail.com';
            $mail->Password   = 'brugkoyccvjcwfoz'; // Use App Password
            $mail->SMTPSecure = 'tls';
            $mail->Port       = 587;

            $mail->setFrom('monika.mukesoft@gmail.com', 'EmailInsightAI OTP');
            $mail->addAddress($email);

            $subject = "Your OTP Code";
            $body = "Hi,<br><br>";
            $body .= "Your OTP is: <strong>{$otp}</strong><br><br>";
            $body .= "It is valid for 5 minutes.<br><br>";
            $body .= "Regards,<br>EmailInsightAI Team";

            $mail->isHTML(true);
            $mail->Subject = $subject;
            $mail->Body    = $body;

            $mail->send();
        } catch (Exception $e) {
            \Log::error('Mail error: ' . $mail->ErrorInfo);
        }
    }

    public function resendOtp(Request $request)
    {
        $user = User::find($request->user_id);

        if (!$user) {
            return response()->json(['success' => false, 'message' => 'User not found.'], 404);
        }

        $otp = rand(100000, 999999);

        DB::table('user_otps')->updateOrInsert(
            ['user_id' => $user->id],
            ['otp' => $otp, 'expires_at' => now()->addMinutes(5), 'created_at' => now()]
        );

        $this->sendOtpEmail($user->email, $otp);

        return response()->json(['success' => true, 'message' => 'OTP resent successfully.']);
    }
2) Module: Laravel Blade Inheritance
•	Laravel Blade inheritance is used to avoid code duplication and maintain a consistent layout across the application.
•	Instead of writing the same header, footer, navigation bar, CSS, and JavaScript code on every page, you create a base layout where all the common structure and styles are defined.
•	Each page, called a child view, inherits this base layout and only defines its unique content.
•	This approach makes the code cleaner, reusable, and easier to maintain.
a)App.blade.php:-
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@yield('title', 'Mail Dashboard')</title> <!-- Dynamic title -->
    <style>
        body {
            background-color: #f8f9fa;
            font-family: 'Segoe UI', sans-serif;
        }

        .navbar {
            background-color: #0d6efd;
        }

        .navbar-brand,
        #d_dropdown,
        .nav-link {
            color: #fff !important;
            font-weight: 500 !important;
        }
    </style>
    @yield('css')
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Google tag (gtag.js) -->
    {{-- <script async src="https://www.googletagmanager.com/gtag/js?id=G-ESG5P2ZQZQ"></script>
    <script>
        window.dataLayer = window.dataLayer || [];

        function gtag() {
            dataLayer.push(arguments);
        }
        gtag('js', new Date());
        gtag('config', 'G-ESG5P2ZQZQ');
    </script> --}}
</head>

<body style="background-color: #f0f2f5; font-family: 'Segoe UI', sans-serif;">

    @php
        // dd($counts);
        if (!Auth::check()) {
            header('Location: ' . route('login'));
            // exit();
        }
    @endphp
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <a class="navbar-brand" style="margin-left:15px " href="{{ route('settings') }}">
            MukeSoft
            {{-- <img
                src="{{ asset('img/favicon.ico') }}" alt="Logo" class="mx-auto d-block"
                style="width: 150px; height: 30px; border-radius: 8px;"> --}}

        </a>
        <div class="collapse navbar-collapse" style="margin-right:15px ">
            <ul class="navbar-nav ms-auto">
                <li class="nav-item"><a class="nav-link" href="{{ route('dashboard') }}">Home</a></li>
                <li class="nav-item"><a class="nav-link" href="{{ route('set_email') }}">Email Settings</a></li>

                @if (Auth::check() || Auth::user()->user_level != 0)
                    <li class="nav-item"><a class="nav-link" href="{{ route('employee') }}">All Employee</a></li>
                    {{-- <li class="nav-item"><a class="nav-link" href="{{ route('showGroup') }}">Group Settings</a></li> --}}
                    {{-- <li class="nav-item"><a class="nav-link" href="{{ route('departments.index') }}">Department</a></li> --}}
                    @if (Auth::check() && Auth::user()->auth_id == 0)
                        <li class="nav-item"><a class="nav-link" href="{{ route('add.route') }}">Add Email</a></li>
                        <div class="dropdown">
                            <button class="btn btn-primary dropdown-toggle " id='d_dropdown' type="button"
                                data-bs-toggle="dropdown" aria-expanded="false">Department
                            </button>
                            <ul class="dropdown-menu dropdown-menu-end">
                                <li><a class="dropdown-item" href="{{ route('departments.index') }}">Add Department</a>
                                </li>
                                <li><a class="dropdown-item" href="{{ route('assign.department') }}">Assign
                                        Department</a>
                                </li>
                                <li class="nav-item"><a class="dropdown-item" href="{{ route('showGroup') }}">Department
                                        List</a>
                            </ul>
                        </div>
                    @endif
                @endif
                <li class="nav-item"><a class="nav-link" href="{{ route('domain') }}">Domain</a></li>
                <li class="nav-item"><a class="nav-link" href="{{ route('mail.info') }}">Email Inbox</a></li>
                <div class="dropdown">
                    <button class="btn btn-primary dropdown-toggle " type="button" data-bs-toggle="dropdown"
                        aria-expanded="false">
                        <i class="bi bi-person-circle me-1"></i>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end">
                        <li>
                            <a class="dropdown-item" href="{{ route('settings') }}">
                                {{-- {{ isset($employee) ? $employee->email : Auth::user()->email ?? 'Guest' }} --}}
                                @if (Auth::user()->account_type == 0)
                                    <i class="fa-brands fa-google text-danger"></i>
                                @else
                                    <i class="fa-brands fa-microsoft text-primary"></i>
                                @endif
                                {{ isset($employee) ? Auth::user()->email : Auth::user()->email ?? 'Guest' }}
                            </a>
                        </li>
                        <li><a class="dropdown-item" href="{{ route('dashboard') }}">Home</a></li>
                        @if (Auth::check() && Auth::user()->auth_id == 0)
                            <li><a class="dropdown-item" href="{{ route('employee') }}">Team Member</a></li>
                        @endif
                        <li>
                            <hr class="dropdown-divider">
                        </li>
                        <li>
                            <form action="{{ route('logout') }}" method="POST">
                                @csrf
                                <button type="submit" class="dropdown-item text-danger">Logout</button>
                            </form>
                            {{-- <a class="dropdown-item text-danger" href="#">Logout</a> --}}
                        </li>
                    </ul>
                </div>
            </ul>
        </div>
    </nav>
    @php
        $routeName = Route::currentRouteName();
    @endphp
    {{-- @if ($routeName != 'mail.info' || $routeName != 'mails.filter' || $routeName != 'mails.show') --}}
    {{-- @if (!in_array($routeName, ['mail.info', 'mails.filter', 'mails.show']))
        <!-- Content Section -->
        {{ $routeName }}
        <div class="container-fluid mt-4">
            @yield('content')
        </div>
    @endif --}}

    {{-- mail dashbord below --}}
    <div class="col-md-4 text-end" id="user_detail" style="display: none;"
        data-account-type={{ isset($employee) ? $employee->account_type : Auth::user()->account_type ?? 'Guest' }}
        data-email="{{ isset($employee) ? $employee->email : Auth::user()->email }}"
        data-app-pass="{{ isset($employee) ? $employee->app_email_pass : Auth::user()->app_email_pass }}"
        data-user-id="{{ isset($employee) ? $employee->id : Auth::id() }}">
    </div>

    <!-- Navbar display none its rejected layout -->
    <nav class="navbar navbar-expand-lg navbar-primary bg-primary shadow-sm" style="display:none;">
        <div class="container-fluid d-flex justify-content-between align-items-center">
            <!-- Brand -->
            @php
                $mailInfoRoute = isset($employee) ? route('mail.info', $employee->id) : route('mail.info');
            @endphp
            <span class="navbar-brand fw-bold text-white"><a class="text-white" href="{{ $mailInfoRoute }}">Mail
                    Dashboard</a></span>
            <!-- Right side icons -->
            <div class="d-flex align-items-center gap-3 text-white">

                <!-- Refresh Icon -->
                <span role="button" title="Refresh" id="refreshIcons" style="font-size: 1.2rem; cursor: pointer;">
                    <i class="bi bi-arrow-clockwise"></i>
                </span>

                <!-- User Dropdown -->
                <div class="dropdown">
                    <button class="btn btn-primary dropdown-toggle text-white border-0 p-0 bg-transparent"
                        type="button" data-bs-toggle="dropdown" aria-expanded="false">
                        <i class="bi bi-person-circle me-1"></i>
                        {{ isset($employee) ? $employee->email : Auth::user()->email ?? 'Guest' }}
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end">
                        <li><a class="dropdown-item" href="{{ route('dashboard') }}">Home</a></li>
                        @if (Auth::check() && Auth::user()->auth_id == 0)
                            <li><a class="dropdown-item" href="{{ route('employee') }}">Team Member</a></li>
                        @endif
                        <li>
                            <hr class="dropdown-divider">
                        </li>
                        <li>
                            <form action="{{ route('logout') }}" method="POST">
                                @csrf
                                <button type="submit" class="dropdown-item text-danger">Logout</button>
                            </form>
                            {{-- <a class="dropdown-item text-danger" href="#">Logout</a> --}}
                        </li>
                    </ul>
                </div>

            </div>
        </div>
    </nav>

    <!-- Main Container -->
    <div class="container-fluid py-4">
        <div class="container-fluid ">
            <div class="d-flex flex-wrap gap-2 mb-4">

                <!-- Reply Dropdown -->
                <div class="dropdown" style="margin-left:8px;">
                    <button id="replyDropdown" class="btn btn-warning dropdown-toggle  text-dark"
                        style=" font-weight:bold; font-size: 0.85rem; color: white !important; border-radius: 30px;"
                        type="button" data-bs-toggle="dropdown">
                        <i class="bi bi-reply"></i> Reply <span id="reply"
                            class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">
                            {{ $counts['send-mail'] ?? 0 }}
                            {{-- {{ ($counts['send-mail'] ?? 0) + ($counts['replied_mail'] ?? 0) }} --}}
                        </span>
                    </button>
                    <ul class="dropdown-menu">
                        <li>
                            <a class="dropdown-item d-flex justify-content-between align-items-center"
                                href="{{ isset($employee) ? route('mails.filter', ['send-mail', $employee->id]) : route('mails.filter', ['send-mail']) }}">
                                <span>Pending Reply</span>
                                <span id="send_mail"
                                    class="badge bg-success rounded-pill">{{ $counts['send-mail'] ?? 0 }}</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex justify-content-between align-items-center"
                                href="{{ isset($employee) ? route('mails.filter', ['replied_mail', $employee->id]) : route('mails.filter', ['replied_mail']) }}">
                                <span>Replied Mail</span>
                                <span id="replied_mail"
                                    class="badge bg-secondary  rounded-pill">{{ $counts['replied_mail'] ?? 0 }}</span>
                            </a>
                        </li>
                    </ul>
                </div>

                <!-- Group By Dropdown -->
                <div class="dropdown" style="margin-left:8px;">
                    <button id="promotionDropdown" class="btn btn-info dropdown-toggle text-dark"
                        style="font-weight:bold; font-size: 0.85rem; border-radius: 30px; color: white !important;"
                        type="button" data-bs-toggle="dropdown">
                        <i class="bi bi-diagram-3"></i> Group By
                        {{-- {{ isset($employee) ? $employee->id : Auth::user()->id }} --}}
                        <span id="group_by"
                            class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">
                            {{ ($counts['sales'] ?? 0) + ($counts['amc'] ?? 0) }}
                        </span>
                    </button>
                    <ul class="dropdown-menu">
                        <li>
                            <a class="dropdown-item d-flex justify-content-between align-items-center"
                                href="{{ isset($employee) ? route('mails.filter', ['sales', $employee->id]) : route('mails.filter', ['sales']) }}">
                                <span>Sales</span>
                                <span id="group_by_sales"
                                    class="badge bg-primary rounded-pill ms-2">{{ $counts['sales'] ?? 0 }}</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex justify-content-between align-items-center"
                                href="{{ isset($employee) ? route('mails.filter', ['amc', $employee->id]) : route('mails.filter', ['amc']) }}">
                                <span>AMC</span>
                                <span id="group_by_amc"
                                    class="badge bg-success rounded-pill ms-2">{{ $counts['amc'] ?? 0 }}</span>
                            </a>
                        </li>
                        @php
                            $userId = isset($employee) ? $employee->id : Auth::user()->id;
                            $groups = DB::table('inbox_groups')->where('auth_id', $userId)->get();

                        @endphp @forelse ($groups as $group)
                            {{-- <tr>
                                <td>{{ $group->id }}</td>
                                <td>{{ $group->group_name }}</td>
                                <td>{{ $group->auth_id }}</td>
                                <td>{{ $group->created_at }}</td>
                                <td>{{ $group->updated_at }}</td>
                            </tr> --}}
                            <li>
                                <a class="dropdown-item d-flex justify-content-between align-items-center"
                                    href="{{ isset($employee) ? route('mails.filter', ['search-' . $group->id, $employee->id]) : route('mails.filter', ['search-' . $group->id]) }}">
                                    <span>
                                        {{ $group->group_name }}
                                    </span>
                                    <span id="group_by_amc"
                                        class="badge bg-success rounded-pill ms-2">{{ $counts['acsmc'] ?? '' }}</span>
                                </a>
                            </li>
                        @empty
                            {{-- <li>
                                <a class="dropdown-item d-flex justify-content-between align-items-center"
                                    href="">
                                    <span>
                                        No Have More Group
                                    </span>
                                    <span id="group_by_amc"
                                        class="badge bg-success rounded-pill ms-2">{{ $counts['acmc'] ?? '' }}</span>
                                </a>
                            </li> --}}
                        @endforelse

                        {{-- @if (isset($employee))
                            <li>
                                {{ $employee->id }}
                            </li>
                        @else
                            <li>
                                {{ Auth::user()->id }}
                            </li>
                        @endif --}}

                    </ul>
                </div>

                <!-- Sentiment Dropdown -->
                <div class="dropdown" style="margin-left:8px;">
                    <button id="sentimentDropdown" class="btn btn-secondary dropdown-toggle  text-white"
                        style="font-weight:bold; font-size: 0.85rem; border-radius: 30px; color: white !important;"
                        type="button" data-bs-toggle="dropdown">
                        <i class="bi bi-emoji-smile"></i> Sentiment
                        <span id="sentiment"
                            class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">
                            {{ ($counts['countis_not_spam'] ?? 0) + ($counts['countis_spam'] ?? 0) + ($counts['neutral'] ?? 0) }}
                        </span>
                    </button>
                    <ul class="dropdown-menu">
                        <!-- Positive -->
                        <li>
                            <a class="dropdown-item d-flex justify-content-between align-items-center"
                                href="{{ isset($employee) ? route('mails.filter', ['is_not_spam', $employee->id]) : route('mails.filter', ['is_not_spam']) }}">
                                <span>Positive Mail</span>
                                <span id="countis_not_spam"
                                    class="badge bg-success rounded-pill">{{ $counts['countis_not_spam'] ?? 0 }}</span>
                            </a>
                        </li>
                        <!-- Negative -->
                        <li>
                            <a class="dropdown-item d-flex justify-content-between align-items-center"
                                href="{{ isset($employee) ? route('mails.filter', ['is_spam', $employee->id]) : route('mails.filter', ['is_spam']) }}">
                                <span>Negative Mail</span>
                                <span id="countis_spam"
                                    class="badge bg-danger rounded-pill">{{ $counts['countis_spam'] ?? 0 }}</span>
                            </a>
                        </li>
                        <!-- Neutral -->
                        <li>
                            <a class="dropdown-item d-flex justify-content-between align-items-center"
                                href="{{ isset($employee) ? route('mails.filter', ['neutral', $employee->id]) : route('mails.filter', ['neutral']) }}">
                                <span>Neutral Mail</span>
                                <span id="neutral"
                                    class="badge bg-secondary rounded-pill">{{ $counts['neutral'] ?? 0 }}</span>
                            </a>
                        </li>
                    </ul>
                </div>

                <!-- Other Badges -->

                <!-- promotion-mail -->
                <div class="position-relative" style="margin-left:8px;">
                    <a href="{{ isset($employee) ? route('mails.filter', ['promotion', $employee->id]) : route('mails.filter', ['promotion']) }}"
                        class="badge bg-primary"
                        style="font-size: 0.85rem; padding: 0.59rem 0.9rem; border-radius: 30px; cursor: pointer;">

                        {{-- <a href="{{ route('mails.filter', 'promotion') }}" class="btn btn-info rounded-pill px-4"> --}}

                        <i class="bi bi-star-fill"></i> Promotion Mail</a>
                    <span id="promotion"
                        class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">
                        {{ $counts['promotion'] ?? 0 }}
                    </span>
                </div>

                <!-- Unread Mail -->
                <div class="position-relative" style="margin-left:8px;">
                    <a href="{{ isset($employee) ? route('mails.filter', ['unread', $employee->id]) : route('mails.filter', ['unread']) }}"
                        class="badge bg-info text-dark"
                        style="font-size: 0.85rem; padding: 0.59rem 0.9rem; border-radius: 30px; cursor: pointer;">
                        {{-- <a href="{{ route('mails.filter', 'unread') }}"
                                class="btn btn-primary rounded-pill px-4"> --}}
                        <i class="bi bi-envelope-open"></i> Unread</a>
                    <span id="countUnread"
                        class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">
                        {{ $counts['countUnread'] ?? 0 }}
                    </span>
                </div>
                <!-- Read Mail -->
                <div class="position-relative" style="margin-left:8px;">
                    <a href="{{ isset($employee) ? route('mails.filter', ['read', $employee->id]) : route('mails.filter', ['read']) }}"
                        class="badge bg-danger"
                        style="font-size: 0.85rem; padding: 0.59rem 0.9rem; border-radius: 30px; cursor: pointer; ">
                        {{-- <a href="{{ route('mails.filter', 'read') }}"
                                class="btn btn-outline-primary rounded-pill px-4"> --}}
                        <i class="bi bi-envelope-check"></i> Read</a>
                    <span id="countRead"
                        class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">
                        {{ $counts['countRead'] ?? 0 }}
                    </span>
                </div>
                <!-- All Mail -->
                <div class="position-relative" style="margin-left:8px;">
                    <a href="{{ isset($employee) ? route('mails.filter', ['all', $employee->id]) : route('mails.filter', ['all']) }}"
                        class="badge bg-dark"
                        style="font-size: 0.85rem; padding: 0.59rem 0.9rem; border-radius: 30px; cursor: pointer;">
                        {{-- <a href="{{ route('mails.filter', 'all') }}" class="btn btn-dark rounded-pill px-4">All --}}
                        <i class="bi bi-archive"></i> Mail</a>
                    <span id="countAll"
                        class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">
                        {{ $counts['countAll'] ?? 0 }}
                    </span>
                </div>

                @if (Auth::check() && Auth::user()->auth_id == 0)
                    <!-- Summary Mail -->
                    <div class="position-relative" style="margin-left:8px;">
                        <a href="#" id="fetch-summary-btn"
                            data-account-type={{ isset($employee) ? $employee->account_type : Auth::user()->account_type ?? 'Guest' }}
                            data-user-id="{{ isset($employee) ? $employee->id : Auth::id() }}" {{-- <a href="#" id="fetch-summary-btn" data-user-id="7" --}}
                            class="badge bg-secondary" data-bs-toggle="modal" data-bs-target="#summaryModal"
                            style="font-size: 0.85rem; padding: 0.59rem 0.9rem; border-radius: 30px; cursor: pointer; ">
                            <i class="bi bi-graph-up"></i> Summary
                        </a>
                    </div>
                    <!-- Summary Modal -->
                    <div class="modal fade" data-bs-backdrop="static" data-bs-keyboard="false" id="summaryModal"
                        tabindex="-1" aria-labelledby="summaryModalLabel" aria-hidden="true">
                        <div class="modal-dialog modal-lg modal-dialog-scrollable">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title" id="summaryModalLabel">Latest 20 Mails</h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal"
                                        aria-label="Close"></button>
                                </div>
                                <div class="modal-body" id="summary-container" class="container-fluid ">
                                    <p class="text-muted">Loading summary...</p>
                                </div>
                            </div>
                        </div>
                    </div>
                @endif

                <!-- Refresh Icon -->
                <span role="button" title="Refresh" id="refreshIcon" style="font-size: 1.2rem; cursor: pointer;">
                    <i class="bi bi-arrow-clockwise"></i>
                </span>

                <!-- User Dropdown -->
                {{-- <div class="dropdown"> --}}
                <div class="">
                    <button style="cursor: default;" class="btn btn-primary" type="button"
                        data-bs-toggle="dropdown" aria-expanded="false">
                        <i class="bi bi-person-circle me-1"></i>
                        {{ isset($employee) ? $employee->email : Auth::user()->email ?? 'Guest' }}
                    </button>
                    @php
                        $account_type = isset($employee)
                            ? $employee->account_type
                            : Auth::user()->account_type ?? 'Guest';
                    @endphp

                    @if ($account_type == 0)
                        <i class="fa-brands fa-google text-danger"></i>
                    @else
                        <i class="fa-brands fa-microsoft text-primary"></i>
                    @endif
                    {{-- <ul class="dropdown-menu dropdown-menu-end">
                        <li><a class="dropdown-item" href="{{ route('dashboard') }}">Home</a></li>
                        @if (Auth::check() && Auth::user()->auth_id == 0)
                            <li><a class="dropdown-item" href="{{ route('employee') }}">Team Member</a></li>
                        @endif
                        <li>
                            <hr class="dropdown-divider">
                        </li>
                        <li>
                            <form action="{{ route('logout') }}" method="POST">
                                @csrf
                                <button type="submit" class="dropdown-item text-danger">Logout</button>
                            </form>
                        </li>
                    </ul> --}}
                </div>

                {{-- <span> Promotion Mail (10)
            </span> --}}
            </div>
        </div>
        <!-- Main Content -->
        <!-- Card -->
        <div class="container-fluid">
            @yield('content') <!-- Content placeholder -->
        </div>

    </div>

    <div id="emailAlert" class="position-fixed end-0 bottom-0 p-3 d-none" style="z-index: 1055;">
        <div class="alert alert-success" role="alert">
            <span id="emailalertMessage"></span>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        function fetchMailStats() {
            var userId = "{{ isset($employee) ? $employee->id : Auth::id() }}";
            // var apiUrl = "http://localhost/email/public/mail/stats?user_id=" + userId;
            var apiUrl = "{{ route('mail_states') }}?user_id=" + userId;

            $.ajax({
                url: apiUrl,
                type: "GET",
                contentType: "application/json",
                success: function(response) {
                    // console.log(response);
                    if (response.status) {
                        $("#countAll").text(response.data.countAll);
                        $("#countUnread").text(response.data.countUnread);
                        $("#countRead").text(response.data.countRead);
                        $("#countis_not_spam").text(response.data.countis_not_spam);
                        $("#countis_spam").text(response.data.countis_spam);
                        $("#promotion").text(response.data.promotion);
                        $("#neutral").text(response.data.neutral);
                        $("#send_mail").text(response.data.send_mail);

                        let total_sentiment = response.data.countis_spam + response.data.countis_not_spam +
                            response.data.neutral;
                        $("#sentiment").text(total_sentiment);
                        $("#reply").text(response.data.send_mail);
                        $("#group_by_sales").text(response.data.sales);
                        $("#group_by_amc").text(response.data.amc);
                        let toalt_group_by = response.data.amc + response.data.sales;
                        $("#group_by").text(toalt_group_by);

                    } else {
                        console.error("Error:", response.message);
                    }

                    //  API Response 
                    // setTimeout(fetchMailStats, 3000);
                },
                error: function(xhr) {
                    console.log(
                        'i am fetchMailStats function in app.blade file or api get some error please check respective function'
                    );
                    console.log(xhr);
                    console.log("i am the line no 510 API Call Failed: ", xhr.responseText);
                    // alert(xhr.responseText);
                    alert('Please try later.');
                    // setTimeout(fetchMailStats, 5000);
                }
            });
        }

        function storeNewEmail() {
            var email = $("#user_detail").data("email");
            var app_pass = $("#user_detail").data("app-pass");
            var user_id = $("#user_detail").data("user-id");
            var account_type = $("#user_detail").data("account-type");
            // alert(email + app_pass + user_id + "Account Type value :- " + account_type);
            // return;

            // var apiUrl = "http://localhost/email/public/store-new-email";
            // var apiUrl = "{{ route('store_new_email') }}";
            var apiUrl = "";

            if (account_type == 1) {
                apiUrl = "{{ route('store_new_outlook') }}";
            } else if (account_type == 0) {
                apiUrl = "{{ route('store_new_email') }}";
            } else {
                console.log("Please send valid data");
                alert("⚠️ Please send valid data (TTY-LATE)");
                return;
            }
            // alert(email + app_pass + user_id + "Account Type value :- " + account_type + " Api Url :- " + apiUrl);
            // return;
            $.ajax({
                url: apiUrl,
                type: "GET",
                data: {
                    email: email,
                    app_pass: app_pass,
                    user_id: user_id
                },
                success: function(response) {
                    console.log("Response one:", response?.code);
                    if (response?.code == 250) {
                        // alert(
                        //     "Your Api Not Working So you are not able to show New email Please check gemini api is start or not"
                        // );
                        alert('Please try later.');
                        console.log(
                            "i am the line no 542 code 250 Your Api Not Working So you are not able to show New email Please check gemini api is start or not"
                        );
                        console.log(
                            'i am storeNewEmail function in app.blade file or api get some error please check respective function'
                        );
                    }
                    if (response?.code == 429) {
                        // alert(
                        //     "occure issue here send multiple request in email server so please wait and Click Ok"
                        // );
                        alert('Please try later.');
                        console.log(
                            "i am the line no 552 code 429 occure issue here send multiple request in email server so please wait and Click Ok"
                        );
                        console.log(
                            'i am storeNewEmail function in app.blade file or api get some error please check respective function'
                        );
                    }
                    if (response?.code == 503) {
                        // alert(
                        //     "The model is overloaded. Please try again later. Ai is For some time UNAVAILABLE please wait For Some times and Click Ok"
                        // );
                        alert('Please try later.');
                        console.log(
                            "i am the line no 562 code 503 The model is overloaded. Please try again later. Ai is For some time UNAVAILABLE please wait For Some times and Click Ok"
                        );
                        console.log(
                            'i am storeNewEmail function in app.blade file or api get some error please check respective function'
                        );
                    }
                    if (response?.code == 430) {
                        // alert(
                        //     "The model is overloaded. Please try again later. Ai is For some time UNAVAILABLE please wait For Some times and Click Ok"
                        // );
                        alert('Please try later.');
                        console.log(
                            "i am the line no 593 code 430 You Are not Company Team member Failed to get access token. Please try again later."
                        );
                        console.log(
                            'i am storeNewEmail function in app.blade file or api get some error please check respective function'
                        );
                    }
                    console.log("Response two:", response);
                    // alert("Success: " + JSON.stringify(response));
                    console.log(response.store_data);
                    $('#loaderOverlay').hide();
                    fetchMailStats()
                    if (response.store_data > 0) {
                        $("#emailalertMessage").text(response.store_data + " new emails received!");
                        $("#emailAlert").removeClass("d-none").fadeIn();
                        setTimeout(function() {
                            $("#emailAlert").fadeOut("slow", function() {
                                $(this).addClass("d-none"); // 3 sec baad hide kar do
                            });
                        }, 3000);
                        // alert("Success! " + response.store_data + " new emails stored.");
                    } else {
                        $("#emailalertMessage").text("No Have New emails !");
                        $("#emailAlert").removeClass("d-none").fadeIn();
                        setTimeout(function() {
                            $("#emailAlert").fadeOut("slow", function() {
                                $(this).addClass("d-none"); // 3 sec baad hide kar do
                            });
                        }, 3000);
                        // console.log("no data inserted");
                        // alert("no data inserted")
                    }
                    // setTimeout(storeNewEmail, 3000);
                },
                error: function(xhr) {
                    console.log(xhr);
                    $('#loaderOverlay').hide();
                    console.log(
                        'i am storeNewEmail function in app.blade file or api get some error please check respective function'
                    );
                    console.log("i am the storeNewEmail error API Call Failed:", xhr);
                    // alert(xhr.responseText);
                    try {
                        const errorJson = JSON.parse(xhr.responseText);
                        console.log("line no 603 Error: " + errorJson.message);
                        // alert("Error: " + errorJson.message);
                        alert('Please try later.');
                    } catch (e) {
                        console.log("line no 607Unknown error: " + xhr.responseText);
                        // alert("Unknown error: " + xhr.responseText);
                        alert('Please try later.');
                    }
                    // setTimeout(storeNewEmail, 5000); 
                }
            });
        }
        $(document).ready(function() {
            // Hide loader

            $('#refreshIcon').on('click', function() {
                // alert("ok");
                $('#loaderOverlay').show();
                storeNewEmail();
                // fetchMailStats();
                // alert("okw");
            });
            //     fetchMailStats();
            //    storeNewEmail()
            $('#fetch-summary-btn').on('click', function(e) {
                e.preventDefault(); // optional, since modal will open anyway
                let userId = $(this).data('user-id');
                // alert(userId);
                // return;

                $('#summary-container').html('<p class="text-muted">Loading summary...</p>');

                $.ajax({
                    url: "{{ route('summary') }}",
                    method: 'GET',
                    data: {
                        user_id: userId
                    },
                    success: function(response) {
                        // console.log(response);
                        console.log("i a success");
                        if (response.status) {
                            $('#summary-container').html(response.summary);
                        } else {
                            $('#summary-container').html('<p class="text-danger">Error: ' +
                                response.message + '</p>');
                        }
                    },
                    error: function(xhr) {
                        // console.log(xhr);
                        console.log("i a xhr");
                        $('#summary-container').html(
                            '<p class="text-danger">Failed to load summary. Getting Some Issue</p>'
                        );

                        console.log(xhr.responseText);
                    }
                });
            });
        });
    </script>
    <script>
        function goBack() {
            if (document.referrer === "" || window.history.length <= 1) {
                alert("Looks like you opened this page directly — there's no previous page to go back to.");
            } else {
                window.history.back();
            }
        }
    </script>
    @stack('scripts') <!-- Ensures pushed scripts load here -->
    <style>
        #loaderOverlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100vh;
            background-color: rgba(0, 0, 0, 0.5);
            display: none;
            z-index: 1050;
        }

        #loaderOverlay .spinner {
            position: absolute;
            top: 50%;
            left: 48%;
        }

        .bounce-text {
            animation: bounce 1s infinite;
        }

        @keyframes bounce {

            0%,
            100% {
                transform: translateY(0);
            }

            50% {
                transform: translateY(-8px);
            }
        }

        /* code #4 */

        .loading04 span {
            display: inline-block;
            animation: loading04 0.7s infinite;
        }

        /* Delay each letter */
        .loading04 span:nth-child(2) {
            animation-delay: 0.1s;
        }

        .loading04 span:nth-child(3) {
            animation-delay: 0.2s;
        }

        .loading04 span:nth-child(4) {
            animation-delay: 0.3s;
        }

        .loading04 span:nth-child(5) {
            animation-delay: 0.4s;
        }

        .loading04 span:nth-child(6) {

            animation-delay: 0.5s;
        }

        .loading04 span:nth-child(7) {
            animation-delay: 0.6s;
        }

        @keyframes loading04 {

            0%,
            100% {
                transform: translateY(0);
            }

            50% {
                transform: translateY(15px);
            }
        }
    </style>
    <!-- Loader Overlay -->
    <div id="loaderOverlay">
        <div class="spinner ">
            {{-- <span class="text-light fs-4 d-block bounce-text">Loding .....</span> --}}
            <div class="text-light loading loading04 ">
                <span>L</span>
                <span>O</span>
                <span>A</span>
                <span>D</span>
                <span>I</span>
                <span>N</span>
                <span>G</span>
            </div>
            <div class="spinner-border text-light mt-3 " style="margin-left: 30px;" role="status">
                <span class="sr-only"></span>
            </div>
        </div>
    </div>

</body>

</html>
b)Nav.blade.php:-
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@yield('title', 'My App')</title>

    <!-- Bootstrap CDN for styling (optional) -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">

    <!-- DataTables CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css">
    <!-- Page-specific styles -->
    <!-- jQuery and DataTables JS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">

    @yield('styles')
    <style>
        body {
            background-color: #f8f9fa;
            font-family: 'Segoe UI', sans-serif;
        }

        .navbar {
            background-color: #0d6efd;
        }

        .navbar-brand,
        #d_dropdown,
        .nav-link {
            color: #fff !important;
            font-weight: 500;
        }
    </style>
    {{-- <!-- Google tag (gtag.js) -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-ESG5P2ZQZQ"></script>
    <script>
        window.dataLayer = window.dataLayer || [];

        function gtag() {
            dataLayer.push(arguments);
        }
        gtag('js', new Date());
        gtag('config', 'G-ESG5P2ZQZQ');
    </script> --}}
</head>

<body>
    @if (!auth()->check())
        <script>
            window.location.href = "{{ route('login') }}"; // Redirect to login page
        </script>
    @endif
    <!-- Navigation Bar (Navbar) -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">

        {{-- <div class="container">
            <a class="navbar-brand" href="{{ route('settings') }}">{{ Auth::user()->email ?? 0 }}</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav">
                    <li class="nav-item">
                        <a class="nav-link" href="{{ route('dashboard') }}">Home</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="{{ route('set_email') }}">Email Settings</a>
                    </li>
                    @if (Auth::check() && Auth::user()->auth_id == 0)
                        <a href="{{ route('add.route') }}" class="nav-link">
                            Add Email
                        </a> <!-- Add button with icon --> 
                        <a href="{{ route('employee') }}" class="nav-link">
                            All Employee
                        </a>
                    @endif
                    <li class="nav-item">
                        <a class="nav-link" href="{{ route('domain') }}">Domain</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="{{ route('showGroup') }}">Group Settings</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="{{ route('departments.index') }}">Department</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="{{ route('mail.info') }}">Email Inbox</a>
                    </li>
                    {{-- <li class="nav-item">
                        <a class="nav-link" href="#">Profile</a>
                    </li> --}}
        {{-- </ul>
            </div>
        </div> --}}

        <a class="navbar-brand" style="margin-left:15px " href="{{ route('settings') }}">
            MukeSoft
            {{-- <img
                src="{{ asset('/img/logo.jpeg') }}" alt="Logo" class="mx-auto d-block"
                style="width: 150px; height: 30px; border-radius: 8px;"> --}}
        </a>
        <div class="collapse navbar-collapse" style="margin-right:15px ">
            <ul class="navbar-nav ms-auto">
                <li class="nav-item"><a class="nav-link" href="{{ route('dashboard') }}">Home</a></li>
                <li class="nav-item"><a class="nav-link" href="{{ route('set_email') }}">Email Settings</a></li>

                @if (Auth::check() || Auth::user()->user_level != 0)
                    <li class="nav-item"><a class="nav-link" href="{{ route('employee') }}">All Employee</a></li>
                    {{-- <li class="nav-item"><a class="nav-link" href="{{ route('showGroup') }}">Group Settings</a></li> --}}
                    {{-- <li class="nav-item"><a class="nav-link" href="{{ route('departments.index') }}">Department</a></li> --}}
                    @if (Auth::check() && Auth::user()->auth_id == 0)
                        <li class="nav-item"><a class="nav-link" href="{{ route('add.route') }}">Add Email</a></li>
                        <div class="dropdown">
                            <button class="btn btn-primary dropdown-toggle " id='d_dropdown' type="button"
                                data-bs-toggle="dropdown" aria-expanded="false">Department
                            </button>
                            <ul class="dropdown-menu dropdown-menu-end">
                                <li><a class="dropdown-item" href="{{ route('departments.index') }}">Add Department</a>
                                </li>
                                <li><a class="dropdown-item" href="{{ route('assign.department') }}">Assign
                                        Department</a>
                                </li>
                                <li class="nav-item"><a class="dropdown-item" href="{{ route('showGroup') }}">Department
                                        List</a>
                                </li>
                            </ul>
                        </div>
                    @endif
                @endif
                <li class="nav-item"><a class="nav-link" href="{{ route('domain') }}">Domain</a></li>
                <li class="nav-item"><a class="nav-link" href="{{ route('mail.info') }}">Email Inbox</a></li>
            </ul>
            <div class="dropdown">
                <button class="btn btn-primary dropdown-toggle " type="button" data-bs-toggle="dropdown"
                    aria-expanded="false">
                    <i class="bi bi-person-circle me-1"></i>
                </button>
                <ul class="dropdown-menu dropdown-menu-end">
                    <li>
                        <a class="dropdown-item" href="{{ route('settings') }}">
                            @if (Auth::user()->account_type == 0)
                                <i class="fa-brands fa-google text-danger"></i>
                            @else
                                <i class="fa-brands fa-microsoft text-primary"></i>
                            @endif
                            {{ isset($employee) ? $employee->email : Auth::user()->email ?? 'Guest' }}
                        </a>
                    </li>
                    <li><a class="dropdown-item" href="{{ route('dashboard') }}">Home</a></li>
                    <li><a class="dropdown-item" href="{{ route('mail.info') }}">Email Inbox</a></li>
                    @if (Auth::check() && Auth::user()->auth_id == 0)
                        <li><a class="dropdown-item" href="{{ route('employee') }}">Team Member</a></li>
                    @endif
                    <li>
                        <hr class="dropdown-divider">
                    </li>
                    <li>
                        <form action="{{ route('logout') }}" method="POST">
                            @csrf
                            <button type="submit" class="dropdown-item text-danger">Logout</button>
                        </form>
                        {{-- <a class="dropdown-item text-danger" href="#">Logout</a> --}}
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- Content Section -->
    <div class="container-fluid mt-4">
        @yield('content')
    </div>

    <!-- Bootstrap Script (Optional) -->
    @yield('scripts')
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>

</html>
3)Module:-Sentiment Analysis & Email Categorization OR Reply tracking
a)Sentiment Analysis
•	Evaluates the tone of each email as Positive, Neutral, or Negative.
•	Helps users prioritize responses based on sentiment.
b)Reply Suggestion / Tracking
•	Suggests appropriate responses based on email content and sentiment.
•	Tracks replies to ensure timely follow-ups.
c)Email Categorization
•	Automatically classifies emails into Promotions, Mass Mail, or Normal (Primary) categories.
•	Flags emails as Spam when detected, helping users focus on important messages.
d)Efficiency & Automation
•	Reduces manual sorting and enables faster decision-making.
•	Supports businesses in handling large volumes of emails effectively.
I)Sentiment Analysis & Email Categorization OR Reply tracking Front End Code :-
@extends('layouts.app')
@section('css')
    <style>
        @keyframes shakeX {

            0%,
            100% {
                transform: translateX(0);
            }

            20% {
                transform: translateX(-1px);
            }

            40% {
                transform: translateX(1px);
            }

            60% {
                transform: translateX(-1px);
            }

            80% {
                transform: translateX(1px);
            }
        }

        .shake {
            /* background-color:pink;  */
            animation: shakeX 0.5s infinite;
        }
    </style>
@endsection
@section('content')

    <!-- Card -->
    <div class="card border-0 shadow-sm" style="border-radius: 1rem;">
        <div class="card-header d-flex justify-content-between align-items-center text-white"
            style="position:Sticky; top:0; border-radius: 1rem 1rem 0 0; background: linear-gradient(135deg, #4e73df, #1cc88a); font-size: 1.25rem; font-weight: 600;">
            <span>{{ $type }}</span>
            <div style="width: 250px;">
                <input type="text" id="customSearch" class="form-control" placeholder="Search mails..."
                    style="border-radius: 30px; padding: 0.4rem 1rem;">
            </div>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive" style="max-height: 400px; overflow-y: auto;">

                <!-- Here you can add content specific to the 'mail_dashboard' page -->
                {{-- <h2>{{ $type }}</h2><br> --}}
                {{-- <p>Welcome to your inbox Mail Dashboard</p> --}}
                <!-- Add more content as needed -->
                {{-- <div class="container-fluid" style="height: 340px; overflow: auto;"> --}}
                {{-- <h2 class="mb-4">Emails ({{ $type }})</h2> --}}
                {{-- {{ dd($mails) }} --}}
                @if ($mails->isEmpty())
                    <h2 class="text-center text-danger">No mails available</h2>
                @else
                    <table class="table table-bordered table-striped" id="mails-table">
                        <thead style="position: sticky; top: 0; z-index: 1;">
                            <tr>
                                <th>ID</th>
                                <th>User ID</th>
                                <th>Sender Name</th>
                                <th>Sender Email</th>
                                <th>Subject</th>
                                <th>Attachment</th>
                                <th>Sent Date</th>
                                {{-- <th>is_spam</th> --}}
                                @if ($type == 'Reply pending mail')
                                    <th>Waiting for Reply Since</th>
                                @endif
                                @if ($type == 'Replied Mail')
                                    <th>Replied Date</th>
                                    {{-- <th>Response Time</th> --}}
                                @endif
                                @if ($type == 'Read Mail' || $type == 'Un-Read Mail' || $type == 'All Mail')
                                    @if ($type == 'All Mail')
                                        <th>Message Status</th>
                                        <th>Sentiment</th>
                                        <th>Lable</th>
                                        {{-- <th>Group By</th> --}}
                                        <th>Action Required</th>
                                    @endif
                                    {{-- <th>Types Mail</th> --}}
                                    {{-- @elseif ($type == 'send-mail')
                            <th>Spam Status</th> --}}
                                @endif
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach ($mails as $mail)
                                {{-- @php
                            $currentEmail = isset($employee) ? $employee->email : Auth::user()->email ?? 'Guest';
                        @endphp

                        @if ($mail->sender_email === $currentEmail)
                            @continue
                        @endif --}}
                                <tr>
                                    @php
                                        // Create DateTime objects in Asia/Kolkata timezone
                                        // $sent = new DateTime($mail->sent_date, new DateTimeZone('Asia/Kolkata'));
                                        // $mail->sent_date = preg_replace('/\s*\(.*\)$/', '', $mail->sent_date);
                                        // $mail->sent_date_s = preg_replace('/\s*\(.*\)$/', '', $mail->sent_date_s);

                                        $sent = new DateTime($mail->sent_date); // Let it parse the actual timezone
                                        $sent->setTimezone(new DateTimeZone('Asia/Kolkata'));
                                        // $replied = new DateTime($mail->sent_date_s, new DateTimeZone('Asia/Kolkata'));
                                        $replied = new DateTime($mail->sent_date_s); // Let it parse the actual timezone
                                        $replied->setTimezone(new DateTimeZone('Asia/Kolkata'));
                                    @endphp

                                    <td>{{ $loop->iteration }} </td>
                                    <td>
                                        <!-- Button -->
                                        <a type="button" class="" data-bs-toggle="modal"
                                            data-bs-target="#modal-{{ $mail->id }}">
                                            <i class="bi bi-info-circle text-primary"></i>
                                        </a>({{ $mail->id }})

                                        <!-- Modal -->
                                        <div class="modal fade" id="modal-{{ $mail->id }}" tabindex="-1"
                                            aria-hidden="true">
                                            <div class="modal-dialog">
                                                <div class="modal-content">
                                                    <div class="modal-header">
                                                        <h5 class="modal-title">Mail Info</h5>
                                                        <button type="button" class="btn-close" data-bs-dismiss="modal"
                                                            aria-label="Close"></button>
                                                    </div>
                                                    <div class="modal-body">
                                                        Email Uniqe Id :- {{ $mail->email_id }} / Id :
                                                        - ({{ $mail->id }})
                                                    </div>
                                                    <div class="modal-footer">
                                                        <button type="button" class="btn btn-secondary"
                                                            data-bs-dismiss="modal">Close</button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                    </td>
                                    <td>{{ $mail->sender_name }}</td>
                                    <td>{{ $mail->sender_email }}</td>
                                    <td>{{ $mail->subject === 'No Subject' ? '-' : $mail->subject }}</td>
                                    <td>{{ $mail->attachment_status == 1 ? 'Yes' : 'No' }}</td>
                                    <td>{{ $sent->format('d M Y H:i A') }}</td>
                                    {{-- <td>{{ $mail->sent_date }}</td> --}}
                                    @if ($type == 'Reply pending mail')
                                        @php
                                            $now = new DateTime('now', new DateTimeZone('Asia/Kolkata'));
                                            $interval = $sent->diff($now);

                                            // Difference formatting
                                            $diffParts = [];
                                            if ($interval->y) {
                                                $diffParts[] = "{$interval->y} years";
                                            }
                                            if ($interval->m) {
                                                $diffParts[] = "{$interval->m} months";
                                            }
                                            if ($interval->d) {
                                                $diffParts[] = "{$interval->d} days";
                                            }
                                            if ($interval->h) {
                                                $diffParts[] = "{$interval->h} hours";
                                            }
                                            if ($interval->i) {
                                                $diffParts[] = "{$interval->i} minutes";
                                            }
                                            if ($interval->s) {
                                                $diffParts[] = "{$interval->s} seconds";
                                            }

                                            $diffText = implode(' ', $diffParts) . ' ago';

                                            // Color logic
                                            if ($interval->y >= 2) {
                                                $color = 'text-dark';
                                            } elseif ($interval->y >= 1) {
                                                $color = 'text-secondary';
                                            } elseif ($interval->m >= 6) {
                                                $color = 'text-warning';
                                            } elseif ($interval->m >= 1) {
                                                $color = 'text-danger';
                                            } elseif ($interval->d >= 2) {
                                                $color = 'text-danger';
                                            } elseif ($interval->d == 1) {
                                                $color = 'text-primary';
                                            } else {
                                                $color = 'text-success';
                                            }
                                        @endphp
                                        <td><span class="{{ $color }}">{{ $diffText }}</span></td>
                                    @endif

                                    @if ($type == 'Replied Mail')
                                        <td>{{ $replied->format('d M Y H:i A') }}</td>

                                        @php
                                            $interval = $sent->diff($replied);

                                            $diffParts = [];
                                            if ($interval->y) {
                                                $diffParts[] = "{$interval->y} years";
                                            }
                                            if ($interval->m) {
                                                $diffParts[] = "{$interval->m} months";
                                            }
                                            if ($interval->d) {
                                                $diffParts[] = "{$interval->d} days";
                                            }
                                            if ($interval->h) {
                                                $diffParts[] = "{$interval->h} hours";
                                            }
                                            if ($interval->i) {
                                                $diffParts[] = "{$interval->i} minutes";
                                            }
                                            if ($interval->s) {
                                                $diffParts[] = "{$interval->s} seconds";
                                            }

                                            $diffText = implode(' ', $diffParts);

                                            // Color logic
                                            if ($interval->y >= 1) {
                                                $color = 'text-secondary';
                                            } elseif ($interval->m >= 1) {
                                                $color = 'text-warning';
                                            } elseif ($interval->d >= 2) {
                                                $color = 'text-danger';
                                            } elseif ($interval->d == 1) {
                                                $color = 'text-primary';
                                            } else {
                                                $color = 'text-success';
                                            }
                                        @endphp

                                        {{-- <td><span class="{{ $color }}">{{ $diffText }}</span></td> --}}
                                    @endif

                                    @if ($type == 'Read Mail' || $type == 'Un-Read Mail' || $type == 'All Mail')
                                        @if ($type == 'All Mail')
                                            <td>{{ $mail->message_status == 1 ? 'Read' : 'Unread' }}</td>
                                            {{-- Sentiment --}}
                                            <td>

                                                @php
                                                    $getting_spam = strpos($mail->label_ids, 'SPAM') !== false ? 1 : 0;
                                                @endphp
                                                {{ $mail->is_promotion == 1 ? 'Mass mail' : ($getting_spam == 1 ? 'Mass mail' : ucfirst($mail->is_spam_value)) }}
                                                {{-- {{ $mail->is_promotion == 1
                                                    ? ($getting_spam == 1
                                                        ? 'Spam & Promotion'
                                                        : 'Promotion')
                                                    : ($getting_spam == 1
                                                        ? 'Spam'
                                                        : ucfirst($mail->is_spam_value)) }} --}}
                                                {{-- {{ $mail->is_promotion == 1 ? $getting_spam . 'Promotion ' : ucfirst($mail->is_spam_value) }} --}}
                                            </td>
                                            <td>
                                                @php
                                                    $getting_spam = strpos($mail->label_ids, 'SPAM') !== false ? 1 : 0;
                                                @endphp
                                                {{ $mail->is_promotion == 1 ? 'Promotion' : ($getting_spam == 1 ? 'Spam' : 'No Lable') }}

                                            </td>
                                            {{-- Category --}}
                                            {{-- <td>
                                        {{$mail->is_category_value }}
                                    </td> --}}
                                            <td>{{ $mail->action_required == 1 ? 'Yes' : 'No' }}</td>
                                        @endif
                                        {{-- <td>
                                    @php
                                        switch ($mail->is_spam) {
                                            case 0:
                                                $statusText = 'Negative';
                                                break;
                                            case 1:
                                                $statusText = 'Positive';
                                                break;
                                            case 2:
                                                $statusText = 'Reply Mail';
                                                break;
                                            case 3:
                                                $statusText = 'Neutral';
                                                break;
                                            case 4:
                                                $statusText = 'Promotion';
                                                break;
                                            case 5:
                                                $statusText = 'Sales';
                                                break;
                                            case 6:
                                                $statusText = 'AMC';
                                                break;
                                            default:
                                                $statusText = 'Unknown';
                                                break;
                                        }
                                    @endphp
                                    {{ $statusText }}
                                </td> --}}
                                        {{-- @elseif ($type == 'send-mail')
                                <td>ok</td> --}}
                                    @endif
                                    {{-- <td>{{ $mail->is_spam }}1</td> --}}
                                    <td>
                                        <div class="d-flex gap-1">
                                            <a href="{{ route('mails.show', ['emial_id' => $mail->email_id, 'is_sent' => '0', 'user_id' => $employee->id ?? null]) }}"
                                                class="btn btn-primary btn-sm ">View</a>
                                            <!-- View-mail -->
                                            {{-- <div class="position-relative">
                                            <a href="{{ route('mails.show', ['emial_id' => $mail->email_id, 'user_id' => $employee->id ?? null]) }}"
                                                class="btn btn-primary btn-sm rounded-fpill px-2"> --}}
                                            {{-- <a href="{{ route('mails.filter', 'send-mail') }}"class="btn btn-warning rounded-pill px-4"> --}}
                                            {{-- {{ $counts['countis_not_spam_heading'] ?? 'Negative' }}  --}}
                                            {{-- View</a>
                                            @if ($mail->new_feteched_data == '0')
                                                 <span class="position-absolute top-0 start-100 translate-middle">
                                                    <span id="track_mail" class="shake badge rounded-pill bg-danger"> --}}
                                            {{-- ! --}}
                                            {{-- {{ $mail->related_message_status }} --}}
                                            {{-- {{ $mail->message_status  }}{{  $mail->related_email_id }} --}}
                                            {{-- </span>
                                                    </span>
                                            @endif --}}
                                            {{-- </div> --}}
                                            @if ($mail->sent_mail_id != -1)
                                                {{-- {{ $mail->sent_mail_id }} --}}
                                                {{-- {{ $mail->action_required }}  --}}
                                                @if ($mail->action_required == 1)
                                                    <div class="position-relative">
                                                        <a href="{{ route('mails.show', ['emial_id' => $mail->sent_mail_id, 'is_sent' => '1', 'user_id' => $employee->id ?? null]) }}"
                                                            class="btn btn-success btn-sm rounded-fpill px-2">
                                                            Track</a>
                                                    </div>
                                                @endif
                                            @endif

                                        </div>
                                        {{-- <a href="{{ route('mails.show', $mail->email_id) }}" class="btn btn-primary btn-sm">View</a> --}}
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>

                @endif

            </div>
        </div>
    </div>

@endsection

@push('scripts')
    <!-- DataTables CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css" />

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <!-- DataTables JS -->
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script>
        $(document).ready(function() {
            var table = $('#mails-table').DataTable({
                // pageLength: 5,
                // lengthChange: false,
                ordering: true,
                info: true,
                // pagingType: 'simple',
                pagingType: 'full_numbers',
                language: {
                    search: "",
                    searchPlaceholder: "Search...",
                    // paginate: {
                    //     previous: "<",
                    //     next: ">"
                    // }
                },
                dom: 't<"d-flex justify-content-between align-items-center p-3"p>'
                //      dom: `<"d-flex justify-content-between align-items-center px-3 pt-3"l>t
            // <"d-flex justify-content-between align-items-center p-3"p>`
            });

            // Connect custom search box
            $('#customSearch').on('keyup', function() {
                table.search(this.value).draw();
            });

            // Style pagination buttons
            setTimeout(function() {
                $('.dataTables_paginate .paginate_button').addClass('btn btn-sm btn-outline-secondary mx-1')
                    .css({
                        borderRadius: '30px'
                    });
            }, 100);
        });
    </script>

    <script>
        // $(document).ready(function() {
        // $('#mails-table').DataTable();
        // // $('#mails-table').DataTable({
        // // pageLength: 25,
        // // ordering: true,
        // // responsive: true
        // // });
        // });
    </script>
@endpush
II)Sentiment Analysis & Email Categorization OR Reply tracking Backend Code 
 public function store_new_email(Request $request)
    {
        // GET parameters fetch karo
        $email_name = $request->query('email');  // ?email=xyz@example.com
        $app_pass = $request->query('app_pass'); // ?app_pass=12345
        $user_id = $request->query('user_id');
        // $email_name = 'krishna0530mukesoft@gmail.com';
        // $IMPERSONATED_EMAIL = 'rajani@mukesoft.com';
        // $email_name = 'rajani@mukesoft.com';
        // $email_name = 'pankaj@mukesoft.com';
        // $email_name = 'hari@mukesoft.com';
        // $email_name = 'prerana@mukesoft.in';
        // $email_name = 'accounts@mukesoft.com';
        // $user_id = 7;

        date_default_timezone_set('Asia/Kolkata');
        $time = date('H:i:s');        // Hour:Minute:Second
        $date = date('d/m/y');
        // without app password
        $logFile =  storage_path('logs/MailController_log.txt');
        $check_lod_time = storage_path('logs/MailController_check_load_time_log.txt');
        if (true) {
            // $TimelogMessage = PHP_EOL . str_repeat(PHP_EOL, 3) . "[$date $time] Email: $email_name | User ID: $user_id | Message:  Enter In IF Condition" . PHP_EOL;
            // file_put_contents($check_lod_time, $TimelogMessage, FILE_APPEND);

            $this->customLogWriter(storage_path('logs/MailController_check_load_time_log.txt'), $email_name, $user_id, "Enter In IF Condition", 3, 0);

            if (!$email_name  || !$user_id) {
                return response()->json(['error' => 'user_id and email are required'], 400);
            }
            $dummyData = [
                'id' => $user_id,
                'user_id' => $user_id,
                'email_id' => -1,
                'sender_name' => null,
                'sender_email' => null,
                'subject' => null,
                'sent_date' => null,
                'attachment_status' => 0, // No attachment
                'message' => null,
                'message_with_html' => "no data",
                'message_status' => '0',
                'is_spam' => 0,
                'action_required' => 0,
                'category' => 0,
                'root_email_id' => 0,
                'track_reply_email' => 0,
                'sender_mail_id' => 0,
                'sent_mail_id' => -1,
                'clean_subject' => null,
                'is_spam_value' => null,
                'is_action_required_value' => null,
                'is_category_value' => null,
                'is_promotion' => 0,
                'gemini_return_json' => null,
                'message_id_uniqe' => null,
                'sent_message' => null,
                'threadId' => null,
                'is_sent_mail' => 0,
                'sent_date_s' => null,
                'message_with_regx' => null,
                'mimeType' => 'no meme'
            ];
            $id = intval($dummyData['id']);
            $p_inbox_record = DB::table('user_emails_id_data')->where('user_id', $id)->where('is_sent_mail', '0')->first();
            $p_inbox_email_ids = [];
            $p_inbox_email_ids = json_decode($p_inbox_record->email_ids ?? '[]', true);

            $emailIds = $p_inbox_email_ids;
            $messages = Message::where('user_id', $id)
                ->select('email_id', 'user_id')
                ->get();

            // Check if data exists
            if ($messages->isNotEmpty()) {
                $data = $messages->toArray();
            } else {
                $data = ["error" => "No record found for ID: " . $id];
            }
            // Extract only email IDs
            $inboxemailIds = collect($data)->pluck('email_id')->toArray();
            if (!empty($inboxemailIds)) {
                $emailIds = array_merge($p_inbox_email_ids, $inboxemailIds);
            }
            // $emailIds = [];
            // print_r($emailIds);
            // ---------------- Service account setup ----------------
            // ---------------- CONFIG ----------------
            $SERVICE_ACCOUNT_FILE = storage_path('app/email/service-account.json');
            if (!file_exists($SERVICE_ACCOUNT_FILE)) {
                return response()->json([
                    "status" => false,
                    "message" => "Service account JSON file not found.",
                    "error" => "Missing service-account.json",
                    "file_path" => $SERVICE_ACCOUNT_FILE
                ], 400);
            }
            $IMPERSONATED_EMAIL = $email_name;
            // ---------------- 1. Load Service Account JSON ----------------
            $json = file_get_contents($SERVICE_ACCOUNT_FILE);
            $data = json_decode($json, true);

            $client_email = $data['client_email'];
            $private_key = $data['private_key']; // this is a PEM 

            // ---------------- 2. Create JWT using package----------------
            $now = time();

            $payload = [
                "iss" => $client_email,
                "sub" => $IMPERSONATED_EMAIL,
                "scope" => "https://www.googleapis.com/auth/gmail.readonly",
                "aud" => "https://oauth2.googleapis.com/token",
                "iat" => $now,
                "exp" => $now + 3600
            ];

            // Create JWT using RS256 algorithm and your private key
            $jwt = JWT::encode($payload, $private_key, 'RS256');

            // $time = date('H:i:s');        // Hour:Minute:Second
            // $date = date('d/m/y');
            // $TimelogMessage = "[$date $time] Email: $email_name | User ID: $user_id | Message:  Getting Process to Start Token For Login" . PHP_EOL;
            // file_put_contents($check_lod_time, $TimelogMessage, FILE_APPEND);

            $this->customLogWriter(storage_path('logs/MailController_check_load_time_log.txt'), $email_name, $user_id, " Getting Process to Start Token For Login", 0, 0);

            // ---------------- 3. Exchange JWT for Access Token ----------------
            $token_url = "https://oauth2.googleapis.com/token";
            $post_fields = http_build_query([
                'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
                'assertion' => $jwt
            ]);

            $ch = curl_init($token_url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Content-Type: application/x-www-form-urlencoded'
            ]);
            $response = curl_exec($ch);
            curl_close($ch);

            $token_data = json_decode($response, true);

            if (!isset($token_data['access_token'])) {
                return response()->json([
                    'message' => 'Google Work space You Are not Company Team member Failed to get access token.',
                    'status' => false,
                    'code' => 430,
                    'error' => $token_data
                ], 200);
                // echo "Failed to get access token:<br>";
                // print_r($token_data);
                // exit;
            }
            $access_token = $token_data['access_token'];

            // $time = date('H:i:s');        // Hour:Minute:Second
            // $date = date('d/m/y');
            // $TimelogMessage = "[$date $time] Email: $email_name | User ID: $user_id | Message: Now getting token process is finish" . PHP_EOL;
            // file_put_contents($check_lod_time, $TimelogMessage, FILE_APPEND);

            $this->customLogWriter(storage_path('logs/MailController_check_load_time_log.txt'), $email_name, $user_id, " Now getting token process is finish", 0, 0);

            // ---------------- 4. Call Gmail API to List Emails ----------------

            // $time = date('H:i:s');        // Hour:Minute:Second
            // $date = date('d/m/y');
            // $TimelogMessage = "[$date $time] Email: $email_name | User ID: $user_id | Message: Message: Now calling Gmail API to fetch latest mail process is start" . PHP_EOL;
            // file_put_contents($check_lod_time, $TimelogMessage, FILE_APPEND);

            $this->customLogWriter(storage_path('logs/MailController_check_load_time_log.txt'), $email_name, $user_id, " Now calling Gmail API to fetch latest mail process is start", 0, 0);

            $url = 'https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=40&q=in:anywhere';

            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                "Authorization: Bearer $access_token"
            ]);
            $email_list_response = curl_exec($ch);
            curl_close($ch);

            $email_list = json_decode($email_list_response, true);

            // $time = date('H:i:s');        // Hour:Minute:Second
            // $date = date('d/m/y');
            // $TimelogMessage = "[$date $time] Email: $email_name | User ID: $user_id | Message: Message: Now calling Gmail API to fetch latest mail process is finish" . PHP_EOL;
            // file_put_contents($check_lod_time, $TimelogMessage, FILE_APPEND);
            $this->customLogWriter(storage_path('logs/MailController_check_load_time_log.txt'), $email_name, $user_id, " Now calling Gmail API to fetch latest mail process is finish.", 0, 0);

            // echo "<pre>";
            // print_r($email_list);

            // 1. Extract only IDs into a flat array
            $allemailIds = [];
            if (isset($email_list['messages'])) {
                foreach ($email_list['messages'] as $msg) {
                    $allemailIds[] = $msg['id'];
                }
            }
            // echo "<pre>";
            // print_r($allemailIds);
            // ---------------- 5.Extract not soter email id`s our database ----------------
            $matchedEmails = [];
            $nonMatchedEmails = [];
            foreach ($allemailIds as $email) {

                if (in_array($email, $emailIds)) {
                    $matchedEmails[] = $email; // If matched, store here
                } else {
                    $nonMatchedEmails[] = $email; // If not matched, store here
                }
            }
            // echo "<pre>";
            // print_r($nonMatchedEmails);
            // die;

            $store_data = 0;
            $insert_messgae = "No have new mail";
            if ($nonMatchedEmails) {
                $count = 0;
                $reversedEmails = array_reverse($nonMatchedEmails);

                // $time = date('H:i:s');        // Hour:Minute:Second
                // $date = date('d/m/y');
                // $TimelogMessage = "[$date $time] Email: $email_name | User ID: $user_id | Message: Storing Data Loop Start :-" . PHP_EOL;
                // file_put_contents($check_lod_time, $TimelogMessage, FILE_APPEND);

                $this->customLogWriter(storage_path('logs/MailController_check_load_time_log.txt'), $email_name, $user_id, "Storing Data Loop Start :-", 0, 0);

                foreach ($reversedEmails as $msg_id) {
                    if ($count >= 40) break;
                    $count++;
                    // $msg_id = '19836fe64c58a32a';
                    // echo $msg_id . "<br>";

                    // $time = date('H:i:s');        // Hour:Minute:Second
                    // $date = date('d/m/y');
                    // $TimelogMessage = PHP_EOL . "[$date $time] Email: $email_name | User ID: $user_id | Message: Now calling Gmail API to fetch full details of message ID:- $msg_id process is start" . PHP_EOL;
                    // file_put_contents($check_lod_time, $TimelogMessage, FILE_APPEND);

                    $this->customLogWriter(storage_path('logs/MailController_check_load_time_log.txt'), $email_name, $user_id, "Now calling Gmail API to fetch full details of message ID:- $msg_id process is start.", 0, 0);

                    $msg_url = "https://gmail.googleapis.com/gmail/v1/users/me/messages/$msg_id?format=full";
                    $ch = curl_init($msg_url);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_HTTPHEADER, [
                        "Authorization: Bearer $access_token"
                    ]);
                    $msg_response = curl_exec($ch);
                    curl_close($ch);

                    // $time = date('H:i:s');        // Hour:Minute:Second
                    // $date = date('d/m/y');
                    // $TimelogMessage = "[$date $time] Email: $email_name | User ID: $user_id | Message: Now calling Gmail API to fetch full details of message ID:- $msg_id process is finish" . PHP_EOL;
                    // file_put_contents($check_lod_time, $TimelogMessage, FILE_APPEND);

                    $this->customLogWriter(storage_path('logs/MailController_check_load_time_log.txt'), $email_name, $user_id, "Now calling Gmail API to fetch full details of message ID:- $msg_id process is finish", 0, 0);

                    $msg_data = json_decode($msg_response, true);
                    // echo $msg_data['id'] . "<br>";
                    // echo $msg_data['threadId'] . "<br>";
                    $dummyData['threadId'] = $msg_data['threadId'];
                    // echo "<pre>";
                    // print_r($msg_data);

                    // Extract headers
                    $headers = $msg_data['payload']['headers'];
                    $dummyData['mimeType'] = $msg_data['payload']['mimeType'] ?? $dummyData['mimeType'];
                    $subject = $from = $from_email = $date = $message_id_unique = null;
                    $dummyData['email_id'] = $msg_id;
                    foreach ($headers as $header) {
                        // if ($header['name'] === 'Subject') $subject = $header['value'];
                        // if ($header['name'] === 'From') {
                        //     $from = $header['value'];
                        //     if (preg_match('/<(.*?)>/', $from, $matches)) {
                        //         $from_email = $matches[1];
                        //     }
                        // }
                        // if ($header['name'] === 'Date') $date = $header['value'];
                        // if ($header['name'] === 'Message-ID') $message_id_unique = $header['value'];
                        if ($header['name'] === 'Subject') $dummyData['subject'] = $header['value'];
                        $cleanSubject = preg_replace('/^(Re:|Fwd:)\s*/i', '', $dummyData['subject']);
                        $dummyData['clean_subject'] = $cleanSubject;
                        if ($header['name'] === 'From') {
                            $dummyData['sender_name'] = $header['value'];
                            // print_r($header);
                            if (preg_match('/<(.*?)>/', $dummyData['sender_name'], $matches)) {
                                $dummyData['sender_email'] = $matches[1];
                            }
                            $dummyData['sender_name'] = preg_replace('/<[^>]+>/', '', $dummyData['sender_name']);
                        }
                        if ($header['name'] === 'Date') $dummyData['sent_date'] = $header['value'];
                        if ($header['name'] === 'Message-ID') $dummyData['message_id_uniqe'] = $header['value'];

                        // if (preg_match('/@mail\.gmail\.com>$/', $dummyData['message_id_uniqe'])) {
                        //     $dummyData['is_promotion'] = 0;
                        // echo 'F<br>';
                        // } else {
                        //     $dummyData['is_promotion'] = 0;
                        //     if ($dummyData['sender_email'] === 'drive-shares-dm-noreply@google.com') {
                        //         $dummyData['is_promotion'] = 0;
                        //     }
                        // echo $message_id_safe . '<br>';
                        // }
                    }

                    // Get labelIds
                    $label_ids = isset($msg_data['labelIds']) ? $msg_data['labelIds'] : [];

                    // Optional: snippet or plain text preview
                    // $dummyData['message'] = isset($msg_data['snippet']) ? $msg_data['snippet'] : null;
                    // $dummyData['message_with_html'] = 'no data';

                    //  Use this in your loop after $msg_data is fetched
                    list($plainMessage, $htmlMessage) = $this->extractTextAndHtml($msg_data['payload'], $msg_data['payload']['mimeType'] ?? '0');

                    $dummyData['message'] = $plainMessage ?: (isset($msg_data['snippet']) ? $msg_data['snippet'] : null);
                    // echo $dummyData['message'];
                    $send_body = preg_replace('/On\s(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s.*?at\s.*?,\s.*?<.*?\s?wrote:.*$/s', '', $dummyData["message"]);
                    $dummyData['message_with_regx'] = $send_body;
                    $dummyData['message_with_html'] = $htmlMessage ?: 'no data';

                    // $time = date('H:i:s');        // Hour:Minute:Second
                    // $date = date('d/m/y');
                    // $TimelogMessage = "[$date $time] Email: $email_name | User ID: $user_id | Message: Now calling Gemini API for categorization process is start" . PHP_EOL;
                    // file_put_contents($check_lod_time, $TimelogMessage, FILE_APPEND);
                    $this->customLogWriter(storage_path('logs/MailController_check_load_time_log.txt'), $email_name, $user_id, "Now calling Gemini API for categorization process is start", 0, 0);

                    $result = $this->callFlaskAPI($send_body);
                    // dd($result);

                    if (isset($result['code']) && $result['code'] == 403) {
                        return response()->json([
                            'message' => 'The provided API key has an IP address restriction.',
                            'status' => false,
                            'code' => 403
                        ], 200);
                    }
                    if (isset($result['code']) && $result['code'] == 503) {
                        $this->customLogWriter(storage_path('logs/MailController_check_load_time_log.txt'), $email_name, $user_id, "Now calling Gemini API for categorization process is end gettig 503", 0, 0);
                        $this->customLogWriter(storage_path('logs/MailController_check_load_time_log.txt'), $email_name, $user_id, "Now calling Gemini API for categorization process is start with dealy 2 min", 0, 0);
                        sleep(30);  // 120 seconds = 2 minutes
                        $result = $this->callFlaskAPI($send_body);
                        if (isset($result['code']) && $result['code'] == 503) {
                            $this->customLogWriter(storage_path('logs/MailController_check_load_time_log.txt'), $email_name, $user_id, "Now calling Gemini API for categorization process is start with dealy 2 min is end gettig 503", 0, 0);
                            $this->customLogWriter(storage_path('logs/MailController_check_load_time_log.txt'), $email_name, $user_id, "Now calling Gemini API pro for categorization process is start", 0, 0);
                            $result = $this->callFlaskAPI($send_body, 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro:generateContent?key=', 'gemini-1.5-pro');
                            $this->customLogWriter(storage_path('logs/MailController_check_load_time_log.txt'), $email_name, $user_id, "Now calling Gemini API pro for categorization process is start", 0, 0);
                        }
                    }
                    $fullResultString = print_r($result, true);

                    // $time = date('H:i:s');
                    // $date = date('d/m/y');
                    // Convert array to string for logging
                    // or use json_encode($result, JSON_PRETTY_PRINT);
                    // $logMessage = "[$date $time] Email: $email_name | User ID: $user_id | Message: Gemini Array \nResult:\n$fullResultString" . PHP_EOL . str_repeat(PHP_EOL, 2);
                    // file_put_contents($logFile, $logMessage, FILE_APPEND);

                    $this->customLogWriter(storage_path('logs/MailController_check_load_time_log.txt'), $email_name, $user_id, " Now calling Gemini API for categorization process is finish", 0, 0);

                    // $time = date('H:i:s');        // Hour:Minute:Second
                    // $date = date('d/m/y');
                    // $TimelogMessage = "[$date $time] Email: $email_name | User ID: $user_id | Message: Now calling Gemini API for categorization process is finish" . PHP_EOL;
                    // file_put_contents($check_lod_time, $TimelogMessage, FILE_APPEND);

                    // $resultArray = json_decode($result, true);
                    if (isset($result['code']) && $result['code'] == 250) {
                        $this->customLogWriter(storage_path('logs/MailController_log.txt'), $email_name, $user_id, " flask method return result Array \nResult:\n$fullResultString", 2, 0);
                        // $logMessage = "[$date $time] Email: $email_name | User ID: $user_id | Message: Predict API not working...! Please check this API" . PHP_EOL;
                        // file_put_contents($logFile, $logMessage, FILE_APPEND);

                        return response()->json([
                            'message' => 'Predict API not working...! Please check this API',
                            'status' => false,
                            'code' => 250
                        ], 200);
                    }
                    if (isset($result['code']) && $result['code'] == 429) {
                        // $logMessage = "[$date $time] Email: $email_name | User ID: $user_id | Message:  Occure 429 Error" . PHP_EOL;
                        // file_put_contents($logFile, $logMessage, FILE_APPEND);
                        $this->customLogWriter(storage_path('logs/MailController_log.txt'), $email_name, $user_id, " flask method return result Array \nResult:\n$fullResultString", 2, 0);

                        return response()->json([
                            'message' => 'store new email occure issue ai cant handle 15-20 request please wait and try anothor time',
                            'status' => false,
                            //Use the API every day for free, as long as you don’t exceed:1,500 requests per day, and 15 requests per minute, and 1 million tokens per minute
                            'code' => 429 //"code": 429 this belongs to handle request is | *Requests per minute (RPM)*   | *15 requests* per minute   
                        ], 200);
                    }
                    if (isset($result['code']) && $result['code'] == 503) {
                        // $logMessage = "[$date $time] Email: $email_name | User ID: $user_id | Message:  Occure 503 Error" . PHP_EOL;
                        // file_put_contents($logFile, $logMessage, FILE_APPEND);
                        $this->customLogWriter(storage_path('logs/MailController_log.txt'), $email_name, $user_id, " flask method return result Array \nResult:\n$fullResultString", 2, 0);

                        return response()->json([
                            'message' => 'The model is overloaded. Please try again later. Ai is For some time UNAVAILABLE get new mail method',
                            'status' => false,
                            //Use the API every day for free, as long as you don’t exceed:1,500 requests per day, and 15 requests per minute, and 1 million tokens per minute
                            'code' => 503 //"code": 429 this belongs to handle request is | *Requests per minute (RPM)*   | *15 requests* per minute   
                        ], 200);
                    }
                    $result = is_array($result) ? '' : trim($result);
                    // dd($result);
                    $normalizedResult = strtolower($result);

                    $cleanJson = trim($normalizedResult);
                    $cleanJson = preg_replace('/^```json|```$/i', '', $cleanJson); // remove ```json or ```
                    $cleanJson = trim($cleanJson);
                    $jsonArray = json_decode($cleanJson, true);

                    if ($cleanJson == '') {
                        // $logMessage = "[$date $time] Email: $email_name | User ID: $user_id | Message:  AI Not work Properly data found or invalid JSON." . PHP_EOL;
                        // file_put_contents($logFile, $logMessage, FILE_APPEND);
                        $this->customLogWriter(storage_path('logs/MailController_log.txt'), $email_name, $user_id, " flask method return result Array \nResult:\n$fullResultString", 2, 0);

                        return response()->json([
                            'status' => false,
                            'message' => 'AI Not work Properly data found or invalid JSON.',
                            'data' => $cleanJson,
                        ], 404);
                    }
                    // dd($cleanJson);
                    $dummyData['gemini_return_json'] = $cleanJson;

                    $action_required = $jsonArray['action_required'] ?? null;
                    $sentiment = $jsonArray['sentiment'] ?? null;
                    $category = $jsonArray['category'] ?? null;

                    // echo "Action Required: " . $action_required . "<br>";
                    // echo "Sentiment: " . $sentiment . "<br>";
                    // echo "Category: " . $category . "<br>";

                    $dummyData["is_spam_value"] = $sentiment;
                    $dummyData["is_action_required_value"] =  $action_required;
                    $dummyData["is_category_value"] =  $category;
                    // echo $dummyData["is_spam_value"]. "<br>";
                    // var_dump($result);
                    // echo "heoo " . $result;
                    // die($result);
                    switch ($sentiment) {
                        case 'positive':
                            $dummyData["is_spam"] = 1;
                            break;
                        case 'negative':
                            $dummyData["is_spam"] = 0;
                            break;
                        case 'send-mail':
                            $dummyData["is_spam"] = 2;
                            break;
                        case 'neutral':
                            $dummyData["is_spam"] = 3;
                            break;
                        case 'promotion':
                            $dummyData["is_spam"] = 4;
                            break;
                        case 'sales':
                            $dummyData["is_spam"] = 5;
                            break;
                        case 'amc':
                            $dummyData["is_spam"] = 6;
                            break;
                        default:
                            $dummyData["is_spam"] = 101;
                            break;
                    }

                    // Numeric mapping for action_required
                    // $dummyData["action_required"] = ($action_required === 'send-mail') ? 1 : 0;
                    switch ($action_required) {
                        case 'send-mail':
                            $dummyData["action_required"] = 1;
                            break;
                        case 'no-action':
                            $dummyData["action_required"] = 0;
                            break;
                        default:
                            $dummyData["action_required"] = 101;
                            break;
                    }
                    // Numeric mapping for category
                    switch ($category) {
                        case 'sales':
                            $dummyData["category"] = 1;
                            break;
                        case 'amc':
                            $dummyData["category"] = 2;
                            break;
                        case 'external':
                            $dummyData["category"] = 3;
                            break;
                        default:
                            $dummyData["category"] = 101;
                            break;
                    }

                    // if ($dummyData['is_promotion'] == 1) {
                    //     if (stripos($dummyData['subject'], 'FW:') === 0 || stripos($dummyData['subject'], 'Fwd:') === 0 || stripos($dummyData['subject'], 'RE:') === 0 || stripos($dummyData['subject'], 'Re:') === 0) {
                    //     } else {
                    //         // $store_data--;
                    //         $dummyData["is_spam"] = 100;
                    //         $dummyData["category"] = 100;
                    //     }
                    // }

                    $dummyData['message_status'] = '0';
                    // $dummyData['category'] = 0;
                    $dummyData['label_ids'] = $label_ids;

                    $prmotion_labels = ['CATEGORY_PROMOTIONS', 'CATEGORY_SOCIAL', 'CATEGORY_UPDATES'];
                    $dummyData['is_promotion'] = 0;
                    if (!empty($label_ids) && array_intersect($prmotion_labels, $label_ids)) {
                        $dummyData['is_promotion'] = 1;
                    }
                    $skip_labels = ['TRASH', 'DRAFT'];
                    if (!empty($label_ids) && array_intersect($skip_labels, $label_ids)) {
                        // continue;
                        // $count--;
                        $dummyData['sender_email'] = $email_name;
                    }

                    $sent_labels = ['SENT'];
                    $created_at = date('Y-m-d H:i:s');
                    $updated_at = date('Y-m-d H:i:s');

                    $dummyData['sent_date_s'] = $dummyData['sent_date'];

                    $dummyData['is_sent_mail'] = 0;
                    if (!empty($label_ids) && array_intersect($sent_labels, $label_ids)) {
                        // echo "sent find";
                        $dummyData['is_sent_mail'] = 1;
                        // continue;
                    }
                    //track reply
                    $firstMessageBy_thread = Message::where('threadId', $dummyData['threadId'])
                        ->orderBy('id', 'asc') // Ascending = oldest first
                        ->first();
                    $dummyData['root_email_id'] = 0;
                    if ($firstMessageBy_thread) {
                        $dummyData['root_email_id'] = $firstMessageBy_thread->email_id;
                    }

                    $latestMessageBy_thread = Message::where('threadId', $dummyData['threadId'])
                        ->orderBy('id', 'desc') // Descending = last
                        ->first();
                    $dummyData['track_reply_email'] = 0;
                    $dummyData['sent_mail_id'] = -1;

                    $dummyData['sent_date_s'] = preg_replace('/\s*\(.*\)$/', '', $dummyData['sent_date_s']);
                    $dummyData["sent_date"] = preg_replace('/\s*\(.*\)$/', '', $dummyData["sent_date"]);
                    // dd($dummyData);
                    try {
                        if ($latestMessageBy_thread) {
                            $latestMessageBy_thread->sent_mail_id = $dummyData['email_id'];
                            $latestMessageBy_thread->track_reply_email =  $dummyData['email_id'];
                            $latestMessageBy_thread->sent_date_s =  $dummyData['sent_date_s'];
                            $latestMessageBy_thread->save();

                            SentMail::create([
                                'user_id'         => $dummyData['user_id'],
                                'sent_mail_id'    => $dummyData["email_id"], // message index/id
                                'matched_subject' => 1, // 0 = not matched
                                'subject'         => $dummyData["subject"],
                                'clean_subject'   => $dummyData["clean_subject"],
                                'receiver_email'  => $dummyData["sender_email"],
                                'receiver_name'   => $dummyData["sender_name"],
                                'sent_htmlMessage' => $dummyData['message'],
                                'sent_date_s' =>  $dummyData['sent_date_s'],
                            ]);
                            // if ($firstMessageBy_thread->id > $latestMessageBy_thread->id) {
                            // $dummyData['sent_mail_id'] = $latestMessageBy_thread->email_id;
                            // $dummyData['track_reply_email'] = $latestMessageBy_thread->email_id;
                            // }
                        }
                        //track reply
                        // if ($dummyData['is_promotion'] == 1) {
                        //     if (stripos($dummyData['subject'], 'FW:') === 0 || stripos($dummyData['subject'], 'Fwd:') === 0 || stripos($dummyData['subject'], 'RE:') === 0 || stripos($dummyData['subject'], 'Re:') === 0) {
                        //     } else {
                        //         // $store_data--;
                        //         $dummyData["is_spam"] = 100;
                        //         $dummyData["category"] = 100;
                        //     }
                        // }
                        // echo "<pre>";
                        // print_r($dummyData);
                        // die();
                        $impmail = DB::table('impmail')
                            ->where('user_id', $dummyData["user_id"])
                            ->where('sender_email', $dummyData["sender_email"])
                            ->first();
                        // dd($impmail);
                        // dd($dummyData);
                        if (!$impmail) {
                            // Insert only if record does not exist
                            DB::table('impmail')->insert([
                                'user_id' => $dummyData["user_id"],
                                'sender_name' => $dummyData["sender_name"],
                                'sender_email' => $dummyData["sender_email"] ?? $dummyData["sender_name"],
                                'created_at' => now(),
                                'updated_at' => now(),
                            ]);
                        }
                        $data = [
                            "user_id" => $dummyData["user_id"],
                            "email_id" => $dummyData["email_id"],
                            "sender_name" => $dummyData["sender_name"],
                            // "sender_name" => htmlspecialchars($dummyData["sender_name"]),
                            "sender_email" => $dummyData["sender_email"] ?? $dummyData["sender_name"],
                            "subject" => $dummyData["subject"],
                            "sent_date" => $dummyData["sent_date"],
                            "attachment_status" => $dummyData["attachment_status"],
                            "message" => mb_convert_encoding($dummyData["message"], 'UTF-8', 'UTF-8'),
                            "message_with_html" => mb_convert_encoding($dummyData["message_with_html"], 'UTF-8', 'UTF-8'),
                            "message_status" => $dummyData["message_status"],
                            "is_spam" => $dummyData["is_spam"],
                            "action_required" => $dummyData["action_required"],
                            "category" => $dummyData["category"],
                            "created_at" => $created_at,
                            "updated_at" => $updated_at,
                            "root_email_id" => $dummyData["root_email_id"],
                            "track_reply_email" => $dummyData["track_reply_email"],
                            "clean_subject" => $dummyData["clean_subject"],
                            "is_spam_value" => $dummyData["is_spam_value"],
                            "is_action_required_value" => $dummyData["is_action_required_value"],
                            "is_category_value" => $dummyData["is_category_value"],
                            "is_promotion" => $dummyData['is_promotion'],
                            "gemini_return_json" => $dummyData['gemini_return_json'],
                            "message_id_uniqe" => $dummyData['message_id_uniqe'],
                            "label_ids" => json_encode(json_encode($dummyData['label_ids'])),
                            'threadId' => $dummyData['threadId'],
                            'is_sent_mail' => $dummyData['is_sent_mail'],
                            'sent_date_s' => $dummyData['sent_date_s'],
                            'sent_mail_id' => $dummyData['sent_mail_id'],
                            'message_with_regx' => $dummyData['message_with_regx'],
                            'mimeType' => $dummyData['mimeType']
                        ];
                        // echo "<pre>";
                        // print_r($data);
                        // break;
                        // continue;
                        $message = Message::create($data);

                        // $time = date('H:i:s');        // Hour:Minute:Second
                        // $date = date('d/m/y');
                        $store_data++;
                        // $TimelogMessage = PHP_EOL . "[$date $time] Email: $email_name | User ID: $user_id | Message: $store_data record inserted in database" . PHP_EOL;
                        // file_put_contents($check_lod_time, $TimelogMessage, FILE_APPEND);
                        $this->customLogWriter(storage_path('logs/MailController_check_load_time_log.txt'), $email_name, $user_id, " $store_data record inserted in database", 0, 0);

                        if ($message) {
                            // $store_data++;
                            $insert_messgae = "Get New Mail";
                            // echo "Message inserted successfully!";
                        } else {
                            $insert_messgae = "Error inserting message!";
                            $this->customLogWriter(storage_path('logs/MailController_check_load_time_log.txt'), $email_name, $user_id, " Error inserting message", 0, 0);
                            echo "Error inserting message!";
                        }
                    } catch (\Exception $e) {
                        $this->customLogWriter(
                            storage_path('logs/MailController_check_load_time_log.txt'),
                            $email_name,
                            $user_id,
                            "$store_data record inserted in database. Error: " . $e->getMessage(),
                            0,
                            0
                        );
                        return response()->json([
                            'status' => false,
                            'message' => 'Please Try later.' . print_r($dummyData),
                            'message_sql' => 'sql error' . $e->getMessage(),
                            'data' => $cleanJson,
                        ], 404);
                    }
                }

                // $time = date('H:i:s');        // Hour:Minute:Second
                // $date = date('d/m/y');
                // $TimelogMessage = "[$date $time] Email: $email_name | User ID: $user_id | Message:Loop is end for stroing data IF condition End total store data:- $store_data" . PHP_EOL;
                // file_put_contents($check_lod_time, $TimelogMessage, FILE_APPEND);
                $this->customLogWriter(storage_path('logs/MailController_check_load_time_log.txt'), $email_name, $user_id, "Loop is end for stroing data IF condition End total store data:- $store_data", 0, 0);

                // $counts_not_use = $this->common($dummyData["user_id"]); //its not use anywhere 
                return response()->json([
                    'message' => 'Service account Connection Established Successfully! or close!',
                    'email' => $email_name,
                    'store_data' => $store_data,
                    'insert messgae' => $insert_messgae
                ], 200);
            }
            // echo "Done";
            // $counts_not_use = $this->common($dummyData["user_id"]); //its not use anywhere 
            // return response()->json([
            //     'message' => 'Service account Established Successfully! or close!',
            //     'email' => $email_name,
            //     'store_data' => $store_data,
            //     'insert messgae' => $insert_messgae
            // ], 200);
        } 
    }
APi Callmethod:-
    function callFlaskAPI($value, $api_url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=',  $apiname = 'Geminiapi-flash',  $Categorization = 'usefull', $ai_Prompt = null)
    {
        // echo "<br>enter gemini api calling";
        $email_content = $value;
        $is_variable = $Categorization;
        // $is_variable = "usefull";
        $not_variable = "not " . $is_variable;
        $reason_variable = $ai_Prompt;

        // $reason_variable = "classify into good an bad ";
        // $categorised_based_on_text = "i want to know given mail is " . $is_variable . " or not for " . $reason_variable . " give me answer in  in good or bad if " . $is_variable . "  retrun good or " . $not_variable . "then return bad.";
        // $categorised_based_on_text_or_give_reason = "i want to know given mail is " . $is_variable . " or not for " . $reason_variable . "  provide a reasone why u pridict is it good or bad";
        //         $categorised_based_on_text = "You are an expert email sentiment classifier. 
        // Classify the following email as either:
        // - positive → if the email shows appreciation, satisfaction, gratitude, praise, or polite inquiry.
        // - negative → if the email shows complaint, dissatisfaction, blame, rudeness, or frustration.

        // Only respond with one word: \"good\" or \"bad\".

        // Email:
        // \"$email_content\"";

        //         $categorised_based_on_text = "You are an expert email analyzer.
        //         Your task is to extract and classify only the reply portion of the email — strictly ignore any quoted text or previous message threads. That includes **any line starting with or after**:
        // - 'On [date], [someone] wrote:'
        // - '> '
        // Classify the email based on the following rules:

        // - send-mail → if the email is asking a question, requesting help, or needs a reply/action (e.g., password reset, help request)
        // - positive → for appreciation, gratitude, praise, or polite inquiry
        // - negative → for complaints, blame, dissatisfaction, rudeness, or frustration
        // - neutral → for general updates, status information, or factual statements with no emotion
        // - promotion → For mass marketing, offers, discounts, advertisements, or newsletters. These emails often contain words like: offer, discount, limited time, coupon, sale, save now, special deal, subscribe now, newsletter, exclusive, buy now, free trial.
        // - sales → For personalized or business-to-business emails where a product/service is being pitched or discussed directly. These emails often contain words like: proposal, quotation, pricing, demo, lead, solution, offering, Business-inquiry, sales team, contact us, client requirement, business opportunity.
        // - amc → For emails related to AMC (Annual Maintenance Contracts), including contract renewals, maintenance schedules, service reports, or warranty-related communication. These emails often include words like: AMC, annual maintenance, service due, contract renewal, preventive maintenance, next visit, service report, maintenance visit, warranty, SLA, support contract, service schedule, service invoice.

        // Respond with only one word: send-mail, positive, negative, neutral, promotion, sales, amc.

        // Email:
        // \"$email_content\"";

        //         $categorised_based_on_text = "You are an expert email analyzer.

        // Your task is to analyze only the reply portion of the email — strictly ignore any quoted text or previous message threads. That includes:
        // - Any line starting with '> '
        // - Any section starting with lines like: 'On [date], [person] wrote:' or similar.

        // Assume that the sender is internal **only if** the email content includes discussion about our own product or service.

        // Examples of internal product references include:  
        // - Our app, CRM, ERP, internal dashboard  
        // - Bugs/issues in our system  
        // - Client escalations related to our delivery  
        // - Feature requests or tickets from clients  
        // - Terms like 'SLA breach', 'service visit', 'AMC', 'support ticket', 'client onboarding', 'module integration', 'quotation shared', 'demo scheduled'

        // ---

        // Return a JSON with the following 3 fields:

        // 1. \"action_required\":  
        //    - \"send-mail\" → if the reply asks a question, requests help, or needs a response/action  
        //    - \"no-action\" → otherwise

        // 2. \"sentiment\":  
        //    - \"positive\" → appreciation, thanks, politeness  
        //    - \"negative\" → complaints, blame, frustration  
        //    - \"neutral\" → status updates, factual statements  
        //    - \"promotion\" → ads, offers, marketing content

        // 3. \"category\":  
        //    - If mail is AMC-related and appears internal → \"amc\"  
        //    - If mail is sales/business-related and appears internal → \"sales\"  
        //    - Else → \"external\"

        // Respond with valid JSON only. Example:  
        // {\"action_required\": \"send-mail\", \"sentiment\": \"negative\", \"category\": \"amc\"}

        // Email:  
        // \"$email_content\"";
        $categorised_based_on_text = "You are an expert email analyzer.

            Your task is to analyze only the reply portion of the email — strictly ignore any quoted text or previous message threads. That includes:
            - Any line starting with '> '
            - Any section starting with lines like: 'On [date], [person] wrote:' or similar.
            If no meaningful reply is found, or the email is unclear, still respond with default values.

            Respond with a **valid JSON only**, with these 3 fields:

            1. \"action_required\":  
            - \"send-mail\" → if the reply asks a question, requests help, or needs a response/action  
            - \"no-action\" → otherwise

            2. \"sentiment\":  
            - \"positive\" → appreciation, thanks, politeness  
            - \"negative\" → complaints, blame, frustration  
            - \"neutral\" → status updates, factual statements  

            3. \"category\":  
            - if emails related to AMC (Annual Maintenance Contracts), including contract renewals,
            maintenance schedules, service reports, or warranty-related communication. amc related Business-inquiry
            These emails often include words like: AMC, annual maintenance, service due, contract renewal, preventive maintenance, next visit, service report
            maintenance visit, warranty, SLA, support contract, service schedule, service invoice. → \"amc\"  

            - If personalized or business-to-business emails where a product/service is being pitched or 
            discussed directly. These emails often contain words like: proposal but not amc proposal, quotation but not amc quotation, 
            or not amc related Business-inquiry ,or not amc related lead ,or not amc related solution ,or not amc related offering,or not amc related business opportunity
            lead, solution, offering, Business-inquiry, sales team, contact us, client requirement, business opportunity.
            → \"sales\"  

            - If the mail is about public communication, media, press release, uploading to website/social media (SM), or includes domains like `@adfactorspr.com` → \"external\"  
            - Else → \"external\"

            Even if uncertain, **always return all 3 fields** with your best guess or default values.

            Example:
            {\"action_required\": \"no-action\", \"sentiment\": \"neutral\", \"category\": \"external\"}

            Email:

        \"$email_content\"";
        $promptText = "$categorised_based_on_text\n\nQuestion: $email_content";
        // $promptText = $categorised_based_on_text;
        // Gemini API call setup
        $apiKey = env('GEMINI_API_KEY'); //paid api key
        // $endpoint = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=' . $apiKey;
        $endpoint = $api_url . $apiKey;

        $postData = [
            'contents' => [
                [
                    'role' => 'user',
                    'parts' => [
                        ['text' => $promptText]
                    ]
                ]
            ]
        ];
        // echo "<br>Calling start gemini api calling";
        $ch = curl_init($endpoint);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json'
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));

        $response = curl_exec($ch);

        if (curl_errno($ch)) {
            echo "cURL Error: " . curl_error($ch);
            curl_close($ch);
            die("<br>API Not Working: cURL Error -> " . curl_error($ch));
            return false; // Agar error ho to false return karo
        }
        // echo "<br>Getting Responce with gemini api calling";
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        // echo $httpCode;

        curl_close($ch); // cURL Close Karein

        // JSON Response Decode Karna
        $data = json_decode($response, true);
        // dd($data);

        date_default_timezone_set('Asia/Kolkata');
        $time = date('H:i:s');        // Hour:Minute:Second
        $date = date('d/m/y');
        $dataString = print_r($data, true);
        // without app password
        $falsklogFile =  storage_path('logs/MailController_flask_Api_log.txt');
        $flasklogMessage = PHP_EOL . str_repeat(PHP_EOL, 3) . "[$date $time] Message:  ia m falsk api :- [$dataString]" . PHP_EOL;
        // file_put_contents($falsklogFile, $flasklogMessage, FILE_APPEND);

        // HTTP Status Code Handling
        if ($httpCode == 404) {
            $dataString = print_r($data, true);
            $this->customLogWriter(storage_path('logs/MailController_flask_Api_log.txt'), 'flask method Mail Controller', $apiname . ' 404', $dataString, 1, 1);
            return [
                'message' => 'Predict Api not working ...! please check this api',
                'status' => false,
                'code' => 250
            ];
            echo "<br>Error 404: API Endpoint Not Found. Please check the URL: " . $url;
            die("<br>API Not Working: Error 404 - API Endpoint Not Found. Please check the URL: " . $url);
            return false;
        } elseif ($httpCode == 500) {
            $this->customLogWriter(storage_path('logs/MailController_flask_Api_log.txt'), 'flask method Mail Controller ', $apiname . ' 500', $dataString, 1, 1);
            return [
                'message' => 'Predict Api not working ...! please check this api 500',
                'status' => false,
                'code' => 250
            ];
            echo "<br>Error 500: Server Error. Check Gemini API logs." . $response;
            die("<br>API Not Working: Error 500 - Server Error. Check Flask API logs.");
            return false;
        } elseif ($httpCode == 403) {
            $this->customLogWriter(storage_path('logs/MailController_flask_Api_log.txt'), 'flask method Mail Controller ', $apiname . ' 403', $dataString, 1, 1);
            return [
                'message' => 'The provided API key has an IP address restriction.',
                'status' => false,
                'code' => 403
            ];
            echo "<br>Error 403: Gemini Api Error. Check Gemini API logs." . $response;
            die("<br>API Not Working: Error 403 - Server Error. Check Flask API logs.");
            return false;
        } elseif ($httpCode == 503) {
            $this->customLogWriter(storage_path('logs/MailController_flask_Api_log.txt'), 'flask method Mail Controller', $apiname . ' 503', $dataString, 1, 1);
            return [
                'message' => 'The model is overloaded. Please try again later.',
                'status' => false,
                'code' => 503
            ];
            echo "<br>Error 500: Server Error. Check Gemini API logs." . $response;
            die("<br>API Not Working: Error 500 - Server Error. Check Flask API logs.");
            return false;
        }

        // echo "<pre>";
        // print_r($data);
        $request_error_code = $data['error']['code'] ?? null;
        if (isset($request_error_code)) {
            // echo "<pre>";
            // print_r($data);
            // echo  $request_error_code;
            // die ;
            $this->customLogWriter(storage_path('logs/MailController_flask_Api_log.txt'), 'flask method Mail Controller', $apiname . ' another no', $dataString, 1, 1);
            return [
                'message' => 'callFlaskAPI occure issue ai cant handle 15-20 request please wait and try anothor time',
                'status' => false,
                //Use the API every day for free, as long as you don’t exceed:1,500 requests per day, and 15 requests per minute, and 1 million tokens per minute
                'code' => $request_error_code //"code": 429 this belongs to handle request is | *Requests per minute (RPM)*   | *15 requests* per minute   
            ];
        }

        $decodedResponse = $data['candidates'][0]['content']['parts'][0]['text'] ?? null;
        // echo  $decodedResponse;
        // echo "hello";

        if (isset($decodedResponse)) {
            $category = $decodedResponse;
            // echo "Predicted Category: " . $category;
            // $cleanJson = trim($category);
            // $cleanJson = preg_replace('/^```json|```$/i', '', $cleanJson); // remove ```json or ```
            // $cleanJson = trim($cleanJson);
            // $jsonArray = json_decode($cleanJson, true);
            // $action_required = $jsonArray['action_required'] ?? null;
            // $sentiment = $jsonArray['sentiment'] ?? null;
            // $category = $jsonArray['category'] ?? null;

            // echo "Action Required: " . $action_required . "<br>";
            // echo "Sentiment: " . $sentiment . "<br>";
            // echo "Category: " . $category . "<br>";

            // die;
            // ✅ "Good" ho to true, "Bad" ho to false return karega
            // return strtolower(trim($category)) === "good";
            return strtolower(trim($category));
            if (strtolower(trim($category)) === "positive") {
                $result = 1;
            } elseif (strtolower(trim($category)) === "negative") {
                $result = 0;
            } elseif (strtolower(trim($category)) === "send-mail") {
                $result = 2;
            } else {
                $result = "ok"; // unknown case
            }
        } else {
            // echo "<pre>";
            // print_r($data);
            // $request_error_code = $data['error']['code'] ?? null;
            // echo "Invalid API Response: " . $response;
            // die;
            // echo "OR invalid error code ".$request_error_code;
            return 100;
        }
    }
4)Module:-Bulk Employee Excel Uploading 
This module allows administrators to efficiently upload multiple employee email IDs using an Excel file. It ensures data accuracy, validation, and seamless integration with the system. Key features include:
a)Bulk Upload via Excel
•	Upload a list of employee emails in bulk using an Excel spreadsheet.
•	Designed to handle large volumes of data efficiently.
b)Email Validation
•	Checks if the email belongs to Google Workspace or Outlook.
•	Ensures only valid, paid, and active accounts are added.
•	Prevents duplicates and ignores invalid entries.
c)Error Handling & Reporting
•	Separates invalid, empty, or mismatched email entries for review.
•	Provides an option to download invalid entries for correction.
d)Seamless Integration
•	Automatically uploads validated emails into the system’s database.
•	Reduces manual entry and ensures data consistency.
e)Admin Control & Efficiency
•	Enables administrators to manage employee accounts efficiently.
•	Minimizes errors and saves time during mass onboarding.
I)Front End Code :-
@extends('setting.nav')

@section('title', 'Home Page')

@section('content')
    <div class="row">
        <div class="col-12">
            <div class="row">
                <form action="{{ route('bulk.upload') }}" method="POST" enctype="multipart/form-data"
                    class="d-flex align-items-center" id="uploadexcelForm">
                    @csrf
                    <input type="hidden" name="admin_id" value="{{ Auth::id() }}">
                    @error('admin_id')
                        <div class="invalid-feedback d-block">{{ $message }}</div>
                    @enderror
                    {{-- <span class="me-3">Select File </span> --}}
                    <input type="file" class="form-control me-2" id="bulk_file" name="bulk_file" accept=".csv,.xlsx"
                        required style="max-width: 250px;">
                    <button type="submit" class="btn btn-primary me-2">
                        Upload
                    </button>

                    <!-- Loader Overlay -->
                    <div id="loaderOverlay">
                        <div class="spinner">
                            <div class="text-light ">
                                Importing Excel
                                <span class="dot-1">.</span><span class="dot-2">.</span><span class="dot-3">.</span><span
                                    class="dot-4">.</span>
                            </div>
                            <div class="spinner-border text-light mt-3" style="margin-left: 150px;" role="status">
                                <span class="sr-only"></span>
                            </div>
                        </div>
                    </div>

                    <!-- CSS (already shared by you) -->
                    <style>
                        #loaderOverlay {
                            font-size: 38px;
                            position: absolute;
                            top: 0;
                            left: 0;
                            width: 100%;
                            height: 100vh;
                            background-color: rgba(0, 0, 0, 0.5);
                            display: none;
                            z-index: 1050;
                        }

                        #loaderOverlay .spinner {
                            position: absolute;
                            top: 50%;
                            left: 48%;
                            transform: translate(-50%, -50%);
                        }

                        .dot-1,
                        .dot-2,
                        .dot-3,
                        .dot-4,
                        .dot-5,
                        .dot-6 {
                            opacity: 0;
                            animation: blink 1.5s infinite;
                        }

                        .dot-2 {
                            animation-delay: 0.3s;
                        }

                        .dot-3 {
                            animation-delay: 0.6s;
                        }

                        .dot-4 {
                            animation-delay: 0.9s;
                        }

                        .dot-5 {
                            animation-delay: 0.12s;
                        }

                        .dot-6 {
                            animation-delay: 0.15s;
                        }

                        @keyframes blink {
                            0% {
                                opacity: 0;
                            }

                            33% {
                                opacity: 1;
                            }

                            66% {
                                opacity: 0;
                            }

                            100% {
                                opacity: 0;
                            }
                        }
                    </style>

                    <!-- JS to show loader -->
                    <script>
                        document.getElementById("uploadexcelForm").addEventListener("submit", function() {
                            document.getElementById("loaderOverlay").style.display = "block";
                        });
                    </script>
                    <a href="{{ route('sample.download') }}" class="btn btn-success">
                        Download Sample File
                    </a>
                    @if (session('excel_inserted_success') && session('excel_inserted_success')['insertedCount'] !== 0)
                        <div
                            style="border: 1px solid #28a745; background-color: #d4edda; color: #155724;  padding: 8px; padding-right: 15px; margin-left:50px; border-radius: 5px; position: relative;">
                            <button onclick="this.parentElement.style.display='none';"
                                style="position: absolute; top:-10px; right: -5px; background: none; border: none; font-size: 18px; cursor: pointer;">&times;
                            </button>
                            <span style="margin-top: 0; font-weight:bold;"> Successfully inserted records :-</span>
                            <span> Total <strong>{{ session('excel_inserted_success')['insertedCount'] ?? 0 }}</strong>
                                records
                                inserted successfully.</span>
                        </div>
                        <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
                        <script>
                            Swal.fire({
                                icon: 'success',
                                title: 'Success!',
                                text: 'Total {{ session('excel_inserted_success')['insertedCount'] }} records inserted successfully.',
                                confirmButtonText: 'OK'
                            });
                        </script>

                        {{-- <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        {{ session('excel_inserted_success')['message'] ?? 0 }}
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div> --}}
                    @endif
                </form>

                {{-- @if ($errors->any())
                    <div class="alert alert-danger">
                        <ul>
                            @foreach ($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                @endif --}}
            </div>

            <div class="row mt-3 p-3">

                {{-- sweat alert --}}
                {{-- <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
                <script>
                    Swal.fire({
                        icon: 'success',
                        title: 'Success!',
                        text: 'Total 123 records inserted successfully.',
                        confirmButtonText: 'OK'
                    });
                </script> --}}

                @error('bulk_file')
                    <div class="invalid-feedback d-block">{{ $message }}</div>
                @enderror
                {{-- Excel Error  --}}
                @if (session('excel_error_column'))
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        {{ session('excel_error_column') }}
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                @endif
                {{-- @if (session('excel_inserted_success'))
                    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
                    <script>
                        Swal.fire({
                            icon: 'success',
                            title: 'Success!',
                            text: 'Total {{ session('excel_inserted_success')['insertedCount'] }} records inserted successfully.',
                            confirmButtonText: 'OK'
                        });
                    </script>
                @endif --}}

                @if (session('excel_error_catch'))
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        {{ session('excel_error_catch') }}
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                @endif
                @if (session('excel_error'))
                    <div style="max-height: 450px; overflow-y: auto; overflow-x: auto;"
                        class="alert alert-secondary alert-dismissible fade show" role="alert">
                        <div class="col-12 mb-3">
                            <div class="p-3 border rounded bg-light">
                                <strong class="me-4">Note :- </strong>
                                {{-- <a href="#" class="btn btn-sm btn-dark">view</a> --}}
                                <span class="me-3 text-dark">Total Data :-
                                    <strong>{{ session('excel_error')['total_count'] ?? 0 }}</strong> </span>
                                {{-- <a href="#" class="btn btn-sm btn-dark">view</a> --}}
                                <span class="me-3 text-dark">Detected Data :-
                                    <strong>{{ session('excel_error')['detectedCount'] ?? 0 }}</strong> </span>
                                {{-- 
                            <a href="#" class="btn btn-sm btn-success" data-bs-toggle="modal"
                                data-bs-target="#excelModal" data-type="valid" data-title="Valid">View</a>
                            <span class="me-3 text-success">Valid :-
                                <strong>{{ session('excel_error')['validCount'] ?? 0 }}</strong> </span>
                            <a href="#" class="btn btn-sm btn-warning" data-bs-toggle="modal"
                                data-bs-target="#excelModal" data-type="blank" data-title="Blank">View</a>
                            <span class="me-3 text-warning">Blank :-
                                <strong>{{ session('excel_error')['emptyCount'] ?? 0 }}</strong> </span>
                            <a href="#" class="btn btn-sm btn-danger" data-bs-toggle="modal"
                                data-bs-target="#excelModal" data-type="error" data-title="Error">View</a>
                            <span class="me-3 text-danger">Error :-
                                <strong>{{ session('excel_error')['errorCount'] ?? 0 }}</strong> </span>
                            <a href="#" class="btn btn-sm btn-primary" data-bs-toggle="modal"
                                data-bs-target="#excelModal" data-type="duplicate" data-title="Duplicate">View</a>
                            <span class="me-4 text-primary">Duplicate :-
                                <strong>{{ session('excel_error')['duplicateCount'] ?? 0 }}</strong></span>
                                 --}}

                                @php
                                    $excelSession = session('excel_error') ?? [];

                                    $types = [
                                        'valid' => [
                                            'class' => 'success',
                                            'label' => 'Valid',
                                            'count' => $excelSession['validCount'] ?? 0,
                                            'data' => $excelSession['validData'] ?? [],
                                        ],
                                        'blank' => [
                                            'class' => 'warning',
                                            'label' => 'Blank',
                                            'count' => $excelSession['emptyCount'] ?? 0,
                                            'data' => $excelSession['blankData'] ?? [],
                                        ],
                                        'error' => [
                                            'class' => 'danger',
                                            'label' => 'Error',
                                            'count' => $excelSession['errorCount'] ?? 0,
                                            'data' => $excelSession['errorData'] ?? [],
                                        ],
                                        'duplicate' => [
                                            'class' => 'primary',
                                            'label' => 'Duplicate',
                                            'count' => $excelSession['duplicateCount'] ?? 0,
                                            'data' => $excelSession['duplicateData'] ?? [],
                                        ],
                                    ];
                                @endphp

                                @foreach ($types as $key => $type)
                                    <a href="#" class="btn btn-sm btn-{{ $type['class'] }}" data-bs-toggle="modal"
                                        data-bs-target="#excelModal" data-type="{{ $key }}"
                                        data-title="{{ $type['label'] }}" data-items='@json($type['data'] ?? [])'>
                                        Download {{ $type['label'] }} Data :- <strong>{{ $type['count'] }}</strong>
                                    </a>
                                    {{-- <span class="me-3 text-{{ $type['class'] }}">
                                        {{ $type['label'] }} :- <strong>{{ $type['count'] }}</strong>
                                    </span> --}}
                                @endforeach

                                <!-- DataTables CSS -->
                                <link rel="stylesheet"
                                    href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">

                                <!-- Modal -->
                                <div class="modal fade" id="excelModal" tabindex="-1" aria-labelledby="excelModalLabel"
                                    aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
                                    <div class="modal-dialog modal-lg">
                                        <div class="modal-content">
                                            <div class="modal-header ">
                                                <h5 class="modal-title" id="excelModalLabel">Excel Details</h5>
                                                <button type="button" class="btn-close mt-2 me-2" data-bs-dismiss="modal"
                                                    aria-label="Close"></button>
                                            </div>

                                            <div class="modal-body">
                                                <!-- Form for Excel Download -->
                                                <form id="excelDownloadForm" method="POST"
                                                    action="{{ route('download.excel') }}" target="_blank">
                                                    @csrf
                                                    <input type="hidden" name="title" id="excelTitle">
                                                    <input type="hidden" name="data" id="excelData">
                                                    <button type="submit" class="btn btn-outline-success mb-3"
                                                        id="downloadBtn">
                                                        ⬇ Download Excel
                                                    </button>
                                                </form>

                                                <!-- Table to show data -->
                                                <table id="excelTable" class="table table-striped table-hover ">
                                                    <thead class="table-dark text-white">
                                                        <tr>
                                                            <th scope="col">First Name</th>
                                                            <th scope="col">Last Name</th>
                                                            <th scope="col">Email Id</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody id="excelDataBody"></tbody>
                                                </table>
                                            </div>

                                            <div class="modal-footer">
                                                <button type="button" class="btn btn-secondary"
                                                    data-bs-dismiss="modal">Close</button>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- jQuery + DataTables JS -->
                                <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
                                <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>

                                <script>
                                    let currentTitle = '';
                                    let dataTableInstance = null;

                                    const excelModal = document.getElementById('excelModal');

                                    excelModal.addEventListener('show.bs.modal', function(event) {
                                        const button = event.relatedTarget;
                                        const title = button.getAttribute('data-title');
                                        const rawData = button.getAttribute('data-items');
                                        const data = JSON.parse(rawData || '[]');

                                        currentTitle = title;

                                        // Update modal title
                                        document.getElementById('excelModalLabel').textContent = `Excel Data - ${title}`;

                                        // Fill form inputs
                                        document.getElementById('excelTitle').value = title;
                                        document.getElementById('excelData').value = JSON.stringify(data);

                                        // Destroy existing DataTable if present
                                        if ($.fn.DataTable.isDataTable('#excelTable')) {
                                            $('#excelTable').DataTable().destroy();
                                        }

                                        // Clear existing data rows
                                        document.getElementById('excelDataBody').innerHTML = '';

                                        // Populate new rows
                                        data.forEach(item => {
                                            const row = `<tr>
                <td>${item.first_name ?? ''}</td>
                <td>${item.last_name ?? ''}</td>
                <td>${item.email ?? ''}</td>
            </tr>`;
                                            document.getElementById('excelDataBody').insertAdjacentHTML('beforeend', row);
                                        });

                                        // Initialize DataTable
                                        setTimeout(() => {
                                            dataTableInstance = $('#excelTable').DataTable({
                                                paging: true,
                                                searching: true,
                                                ordering: true
                                            });
                                        }, 100);
                                    });

                                    // Form validation before export
                                    document.getElementById('excelDownloadForm').addEventListener('submit', function(e) {
                                        const data = document.getElementById('excelData').value;
                                        try {
                                            const parsed = JSON.parse(data);
                                            if (!Array.isArray(parsed) || parsed.length === 0) {
                                                alert('No data to export!');
                                                e.preventDefault();
                                            }
                                        } catch (err) {
                                            alert('Invalid data format!');
                                            e.preventDefault();
                                        }
                                    });
                                </script>

                                <ul class="mt-2 mb-0">
                                    <li>
                                        <span class="bg-success text-white"
                                            style=" border-radius: 0.25rem; font-size: 0.875em;">
                                            Green (Valid)
                                        </span>
                                        – All fields are valid. Data is correctly filled and ready for upload.
                                    </li>
                                    <li>
                                        <span
                                            style="background-color: #fff3cd; color: #664d03; border-radius: 0.25rem; font-size: 0.875em;">
                                            Yellow (Blank - Warning)
                                        </span>
                                        – Incomplete data detected ! One or more fields are empty. Please fill in all
                                        required
                                        fields before uploading.
                                    </li>
                                    <li>
                                        <span
                                            style="background-color: #f8d7da; color: #842029; border-radius: 0.25rem; font-size: 0.875em;">
                                            Red (Error)
                                        </span>
                                        – Invalid credentials detected ! Email ID is incorrect. Please
                                        verify
                                        and correct the entry.
                                    </li>
                                    <li>
                                        <span
                                            style="background-color: #d1e7dd; color: #0f5132; border-radius: 0.25rem; font-size: 0.875em;">
                                            Blue (Duplicate)
                                        </span>
                                        – Duplicate entry detected ! Please remove the duplicate row from the Excel file
                                        before
                                        uploading.
                                    </li>
                                </ul>
                            </div>
                            @if (session('excel_error') && isset(session('excel_error')['table']))
                                {!! session('excel_error')['table'] !!}
                            @endif
                        </div>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                @endif

            </div>
            {{-- <div class="row mt-3 p-3">
                <div style="max-height: 450px; overflow-y: auto;" class="alert alert-secondary alert-dismissible fade show"
                    role="alert">
                    <div class="col-12 mb-3">
                        <div class="p-3 border rounded bg-light">
                            <strong class="me-4">Note :- </strong>
                            <span class="me-4 text-dark">Total Data :- <strong>6</strong> </span>
                            <span class="me-4 text-success">Valid :- <strong>1</strong> </span>
                            <span class="me-4 text-warning">Blank :- <strong>2</strong> </span>
                            <span class="me-4 text-danger">Error :- <strong>1</strong> </span>
                            <span class="me-5 text-primary">Duplicate :- <strong>2</strong></span>

                            <ul class="mt-2 mb-0">
                                <li>
                                    <span class="bg-success text-white"
                                        style=" border-radius: 0.25rem; font-size: 0.875em;">
                                        Green (Valid)
                                    </span>
                                    – All fields are valid. Data is correctly filled and ready for upload.
                                </li>
                                <li>
                                    <span
                                        style="background-color: #fff3cd; color: #664d03; border-radius: 0.25rem; font-size: 0.875em;">
                                        Yellow (Blank - Warning)
                                    </span>
                                    – Incomplete data detected ! One or more fields are empty. Please fill in all required
                                    fields before uploading.
                                </li>
                                <li>
                                    <span
                                        style="background-color: #f8d7da; color: #842029; border-radius: 0.25rem; font-size: 0.875em;">
                                        Red (Error)
                                    </span>
                                    – Invalid credentials detected ! Email ID or App Password is incorrect. Please verify
                                    and correct the entry.
                                </li>
                                <li>
                                    <span
                                        style="background-color: #d1e7dd; color: #0f5132; border-radius: 0.25rem; font-size: 0.875em;">
                                        Blue (Duplicate)
                                    </span>
                                    – Duplicate entry detected ! Please remove the duplicate row from the Excel file before
                                    uploading. <b> Excel file cannot be uploaded until all rows are valid. Please correct or
                                        remove invalid entries.</b>
                                </li>
                            </ul>
                        </div>
                    </div>

                    <table class="table table-bordered">
                        <thead class="table-dark">
                            <tr>
                                <th>ID</th>
                                <th>First Name</th>
                                <th>Last Name</th>
                                <th>Email</th>
                                <th>App Password</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr class="table-success">
                                <td>1</td>
                                <td>Rahul</td>
                                <td>Sharma</td>
                                <td>rahul@example.com</td>
                                <td>app@1234</td>
                            </tr>
                            <tr class="table-warning">
                                <td>2</td>
                                <td>Priya</td>
                                <td></td>
                                <td>priya@example.com</td>
                                <td>pass@5678</td>
                            </tr>
                            <tr class="table-danger">
                                <td>3</td>
                                <td>Amit</td>
                                <td>Kumar</td>
                                <td>amit@@example</td>
                                <td>amit@9999</td>
                            </tr>
                            <tr>
                                <td class="bg-success text-white">4</td>
                                <td class="bg-success text-white">Neha</td>
                                <td class="bg-success text-white">Verma</td>
                                <td class="bg-success text-white">neha@example.com</td>
                                <td class="bg-success text-white">neha@0000</td>
                            </tr>
                            <tr class="table-warning">
                                <td>5</td>
                                <td>Vikas</td>
                                <td>Yadav</td>
                                <td></td>
                                <td>vikas@1111</td>
                            </tr>
                            <tr class="table-success">
                                <td>6</td>
                                <td>Rahul</td>
                                <td>Sharma</td>
                                <td>rahul@example.com</td>
                                <td>app@1234</td>
                            </tr>
                        </tbody>
                    </table>

                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            </div> --}}

        </div>

        {{-- <div class="col-4">
            <div class="card shadow p-4" style="width: 400px;"> --}}
        {{-- <p>Authenticated User ID: {{ Auth::id() }}</p> --}}
        {{-- <h2 class="text-center mb-4">Employee Register</h2> --}}

        <!-- Success Message -->
        @if (session('success'))
            <div class="alert alert-success alert-dismissible fade show" role="alert">{{ session('success') }} <a
                    href="{{ route('login') }}">Go to Login</a>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        @endif
        {{-- @if (session('error'))
                    <div class="alert alert-danger">{{ session('error') }}</div>
                @endif --}}
        @if (session('error'))
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                {{ session('error') }}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        @endif
        <!-- Form Start -->
        {{-- <form action="{{ route('register.submit') }}" method="POST">
                    @csrf --}}

        <!-- Email -->
        {{-- <div class="mb-3">
                        <input type="hidden" name="auth_id" value="{{ Auth::id() }}">
                        <label class="form-label">Email Id </label>
                        <input type="text" name="email" required
                            class="form-control @error('email') is-invalid @enderror" value="{{ old('email') }}">
                        @error('email')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div> --}}

        <!-- App Email -->
        {{-- <div class="mb-3">
                        <label class="form-label">App Email Password</label>
                        <input type="password" name="app_email" required
                            class="form-control @error('app_email') is-invalid @enderror" value="{{ old('app_email') }}">
                        @error('app_email')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div> --}}

        <!-- Password -->
        {{-- <div class="mb-3"> --}}
        {{-- <label class="form-label">Password</label> --}}
        {{-- <input type="hidden" name="password" value="123456"
                            class="form-control @error('password') is-invalid @enderror">
                        @error('password')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div> --}}

        <!-- Login Password -->
        {{-- <div class="mb-3"> --}}
        {{-- <label class="form-label">Confirm Password</label> --}}
        {{-- <input type="hidden" name="password_confirmation" value="123456"
                            class="form-control @error('password_confirmation') is-invalid @enderror">
                        @error('password_confirmation')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div> --}}

        <!-- Submit Button -->
        {{-- <button type="submit" class="btn btn-primary w-100">Register</button> --}}

        {{-- <div class="row mt-3">
                        <div class="col-12 text-center"><a href="{{ route('email_app_password') }}">How to Get App
                                Email</a>
                        </div>
                    </div>
                </form> --}}

        {{-- </div>
        </div> --}}
    </div>

@endsection
II)Bakcend Code For Excel Uplaoding Feture:-
a) help Download a smaple file
    public function downloadSample()
    {
        $filePath = public_path('sample/Email_Data_sample.xlsx');

        if (file_exists($filePath)) {
            return response()->download($filePath, 'Email_Data_sample.xlsx');
            // return redirect()->back()->with('error', 'Sample file found.');
        } else {
            return redirect()->back()->with('error', 'Sample file not found.');
        }
    }
b) Download a Excel File
    public function downloadExcel(Request $request)
    {
        $data = json_decode($request->input('data'), true) ?? [];
        $title = $request->input('title', 'ExcelData');

        // ✅ If no data, return plain response
        if (empty($data)) {
            return response('No data to export');
        }
        // Create new Spreadsheet
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        // Set headings
        $headings = ['First Name', 'Last Name', 'Email Id'];
        $sheet->fromArray($headings, null, 'A1');

        // Fill rows starting from 2nd row
        $rowIndex = 2;
        foreach ($data as $row) {
            $sheet->setCellValue("A{$rowIndex}", $row['first_name'] ?? '');
            $sheet->setCellValue("B{$rowIndex}", $row['last_name'] ?? '');
            $sheet->setCellValue("C{$rowIndex}", $row['email'] ?? '');
            $rowIndex++;
        }

        // Write to temporary file
        // Get current date and time in Asia/Kolkata
        $timestamp = Carbon::now('Asia/Kolkata')->format('Y-m-d_H-i-s');
        $writer = new WriterXlsx($spreadsheet);
        $fileName = $title . "_file_Data_Exported_Report_{$timestamp}.xlsx";
        $tempFile = tempnam(sys_get_temp_dir(), $fileName);
        $writer->save($tempFile);

        // Download response
        // echo $title . "<br><pre>";
        // echo print_r($data);
        return response()->download($tempFile, $fileName)->deleteFileAfterSend(true);
        dd("downloadExcel method");
    }
c)Upload BUlk Process
    public function uploadBulk(Request $request)
    {
        $request->validate([
            'bulk_file' => 'required|file|mimes:xlsx',
            'admin_id' => 'required',
        ]);
        $adminId = $request->input('admin_id');
        try {
            // $check_conn = new AuthController();
            // $email = 'Prerana@mukesoft.in';
            // $email = 'vishal@mukesoft.com';
            // if (Auth::user()->account_type == 0) {
            //     $imap_conn = $check_conn->check_conn_service_Account($email);
            // } else {
            //     $imap_conn = $check_conn->check_conn_outlook_Account($email);
            // }
            // echo $imap_conn['success'];
            // echo $imap_conn['message'];
            // dd(Auth::user());
            $file = $request->file('bulk_file');
            $spreadsheet = IOFactory::load($file->getPathname());
            $sheet = $spreadsheet->getActiveSheet()->toArray();

            $is_service_account = true;
            // Validate header
            $headers = $sheet[0];
            if ($is_service_account) {
                $expectedHeaders = ['First Name', 'Last Name', 'Email Id'];
            } else {
                $expectedHeaders = ['First Name', 'Last Name', 'Email Id', 'Email App Password'];
            }
            // echo "<pre>";
            // print_r($headers);
            // print_r($expectedHeaders);
            // die;
            $match = true;
            foreach ($expectedHeaders as $index => $expectedColumn) {
                if (!isset($headers[$index]) || strtolower(trim($headers[$index])) !== strtolower(trim($expectedColumn))) {
                    $match = false;
                    break;
                }
            }
            if (!$match) {
                $expectedList = '';
                foreach ($expectedHeaders as $index => $column) {
                    $expectedList .= ($index + 1) . '. ' . $column . "\n";
                }

                return back()->with(
                    'excel_error_column',
                    "Invalid file format! The uploaded Excel file does not match the required starting columns.\n" .
                        "Found: " . implode(', ', $headers) . "\n" .
                        "Expected first columns (in order):\n$expectedList"
                );
            }
            //Check Column name Is Proper or Not
            // if ($headers !== $expectedHeaders) {
            //     $expectedList = '';
            //     foreach ($expectedHeaders as $index => $column) {
            //         $expectedList .= ($index + 1) . '. ' . $column . "\n";
            //     }

            //     return back()->with(
            //         'excel_error_column',
            //         "Invalid file format ! The uploaded Excel file does not match the expected column structure . " .
            //             " Found :- " . implode(', ', $headers) .
            //             " ! Expected column order :- $expectedList"
            //     );
            // }
            // Parse and collect data
            $excel_data = [];
            // echo "sheet count";
            // dd($sheet);
            if ($is_service_account) {
                for ($i = 1; $i < count($sheet); $i++) {
                    $row = $sheet[$i];
                    $excel_data[] = [
                        'first_name' => $row[0],
                        'last_name' => $row[1],
                        'email' => $row[2],
                        'app_password' => isset($row[3]) && !empty($row[3]) ? $row[3] : '123456' . $i,
                        'created_at' => now(),
                        'updated_at' => now(),
                    ];
                }
            } else {
                for ($i = 1; $i < count($sheet); $i++) {
                    $row = $sheet[$i];
                    $excel_data[] = [
                        'first_name' => $row[0],
                        'last_name' => $row[1],
                        'email' => $row[2],
                        'app_password' => $row[3],
                        'created_at' => now(),
                        'updated_at' => now(),
                    ];
                }
            }

            $totalCount = 0;
            $emptyCount = 0;
            $duplicateCount = 0;
            $errorCount = 0;
            $validCount = 0;
            $detectedCount = 0;
            $insertedCount = 0;

            if ($is_service_account) {
                $heading_app = "Uniqe No";
            } else {
                $heading_app = "App Password";
            }

            // <table class="table table-bordered" id="status-table">
            $table_data = '<br/>
            <div class="bg-white">
            <table class="table table-bordered" id="status-table">
                <thead>
                    <tr>
                        <th class="bg-primary text-white">ID</th>
                        <th class="bg-primary text-white">First Name</th>
                        <th class="bg-primary text-white">Last Name</th>
                        <th class="bg-primary text-white">Email</th>
                        <th class="bg-primary text-white">' . $heading_app . '</th>
                        <th class="bg-primary text-white">Group</th>
                        <th class="bg-primary text-white">Status</th>
                    </tr>
                </thead>
                <tbody>
            ';
            // echo "<pre>";
            // print_r($excel_data);
            $totalCount = count($excel_data);
            if (empty($excel_data) || count($excel_data) == 0) {
                return back()->with(
                    'excel_error_column',
                    "Empty Excel file detected ! Please upload a file with at least one row of data. "
                );
            }
            // echo "total count :- ".$totalCount ." ."; 
            // dd($totalCount);

            $admin_user = Auth::id();
            $departments = Department::where('user_id', $admin_user)
                ->orderBy('id', 'Asc')
                ->get();
            // echo $admin_user;
            $validData = [];

            $blankData = [];

            $errorData = [];

            $duplicateData = [];

            for ($i = 0; $i < $totalCount; $i++) {
                $row = $excel_data[$i];
                $id = $i + 1;
                $first = trim($row['first_name']);
                $last = trim($row['last_name']);
                $email = trim($row['email']);
                $App_pass = trim($row['app_password']);

                $label = -1;
                $group_lable = 'Not Group';
                // print_r($departments);
                // dd($departments);
                foreach ($departments as $department) {
                    // echo $department->department_lable . "<br>";
                    if (str_contains(strtolower($email), strtolower(trim($department->department_lable))) !== false) {
                        $label = $department->id;
                        $group_lable = $department->department_name;
                        // echo $email;
                        // echo $group_lable . "<br>";
                        // if ($i == 2) {
                        //     dd($group_lable);
                        // }
                        break;
                    }
                }
                $empty_check = false;
                $is_service_account_value = 1;
                $account_type = 0; //0 means workspace or 1 means outlook 
                if ($is_service_account) {
                    $empty_check = empty($first) && empty($last) && empty($email);
                } else {
                    $is_service_account_value = 0;
                    $empty_check = empty($first) && empty($last) && empty($email) && empty($App_pass);
                }

                if ($empty_check) {
                    continue;
                }
                $insertData[] = [
                    'email' => trim($row['email']),
                    'app_email_pass' => encrypt(trim($row['app_password'])),
                    'password' => Hash::make('123456'),
                    'login_password' => Hash::make('123456'),
                    'fname' => trim($row['first_name']),
                    'lname' => trim($row['last_name']),
                    'auth_id' => Auth::id(), // current logged-in user ID
                    'group_by' => $label,
                    'group_lable' => $group_lable,
                    'user_level' => 0, //level wise,
                    'is_service_account' => $is_service_account_value,
                    'account_type' => 0
                ];

                // Check if any required field is empty
                $empty = false;
                if ($is_service_account) {
                    $empty = empty($id) || empty($first) || empty($last) || empty($email);
                } else {
                    $empty = empty($id) || empty($first) || empty($last) || empty($email) || empty($App_pass);
                }

                if ($empty) {
                    $blankData[] = ['first_name' => $first, 'last_name' => $last, 'email' => $email];
                    $emptyCount++;
                    $detectedCount++;
                    $table_data .= "<tr class='table-warning'>";
                    $table_data .= "<td>{$id}</td>";
                    $table_data .= "<td>{$first}</td>";
                    $table_data .= "<td>{$last}</td>";
                    $table_data .= "<td>{$email}</td>";
                    $table_data .= "<td>{$App_pass}-{$is_service_account_value}</td>";
                    $table_data .= "<td>{$group_lable}-{$label}</td>";
                    $table_data .= "<td>Blank </td>";
                    $table_data .= "</tr>";
                    continue;
                }

                if (User::where('email', $email)->exists()) {
                    $duplicateData[] = ['first_name' => $first, 'last_name' => $last, 'email' => $email];
                    //duplicate Entry
                    $duplicateCount++;
                    $detectedCount++;
                    $table_data .= "<tr class='table-success'>";
                    $table_data .= "<td>{$id}</td>";
                    $table_data .= "<td>{$first}</td>";
                    $table_data .= "<td>{$last}</td>";
                    $table_data .= "<td>{$email}</td>";
                    $table_data .= "<td>{$App_pass}-{$is_service_account_value}</td>";
                    $table_data .= "<td>{$group_lable}</td>";
                    $table_data .= "<td>Duplicate </td>";
                    $table_data .= "</tr>";
                    continue;
                }
                if (!empty($email) || !empty($App_pass)) {
                    $detectedCount++;
                    if ($is_service_account) {
                        $check_conn = new AuthController();
                        if (Auth::user()->account_type == 0) {
                            $imap_conn = $check_conn->check_conn_service_Account($email);
                        } else {
                            $imap_conn = $check_conn->check_conn_outlook_Account($email);
                            $account_type = 1;
                        }
                    } else {
                        $check_conn = new AuthController();
                        $imap_conn = $check_conn->check_conn($email, $App_pass);
                    }

                    if (isset($imap_conn['success']) && $imap_conn['success'] === false) {
                        $errorData[] = ['first_name' => $first, 'last_name' => $last, 'email' => $email];
                        // incoorect app passowrd or email id not matched
                        $errorCount++;
                        $table_data .= "<tr class='table-danger'>";
                        $table_data .= "<td>{$id}</td>";
                        $table_data .= "<td>{$first}</td>";
                        $table_data .= "<td>{$last}</td>";
                        $table_data .= "<td>{$email}</td>";
                        $table_data .= "<td>{$App_pass}-{$is_service_account_value}</td>";
                        $table_data .= "<td>{$group_lable}</td>";
                        $table_data .= "<td>Error </td>";
                        $table_data .= "</tr>";
                        continue;
                    } else {
                        $validData[] = ['first_name' => $first, 'last_name' => $last, 'email' => $email];
                        //valid data 
                        if (!User::where('email', $email)->exists()) {
                            $record = User::create([
                                'email' => trim($row['email']),
                                'app_email_pass' => encrypt(trim($row['app_password'])),
                                'password' => Hash::make('123456'),
                                'login_password' => Hash::make('123456'),
                                'fname' => trim($row['first_name']),
                                'lname' => trim($row['last_name']),
                                'auth_id' => Auth::id(), // current logged-in user ID
                                'group_by' => $label,
                                'group_lable' => $group_lable,
                                'user_level' => 0,
                                'is_service_account' => $is_service_account_value,
                                'account_type' => $account_type
                            ]);
                            $insertedCount++;
                        }
                        $validCount++;
                        // $insertedCount++;
                        $table_data .= "<tr>";
                        $table_data .= "<td class='bg-success text-white'>{$id}</td>";
                        $table_data .= "<td class='bg-success text-white'>{$first}</td>";
                        $table_data .= "<td class='bg-success text-white'>{$last}</td>";
                        $table_data .= "<td class='bg-success text-white'>{$email}</td>";
                        $table_data .= "<td class='bg-success text-white'>{$App_pass}-{$is_service_account_value}</td>";
                        $table_data .= "<td class='bg-success text-white'>{$group_lable}</td>";
                        $table_data .= "<td class='bg-success text-white'>Valid </td>";
                        $table_data .= "</tr>";
                        continue;
                    }
                }
            }
            // echo"insertd data";
            // dd($insertData);
            $table_data .= '</tbody></table></div>';
            // Add DataTables initialization script 
            $table_data .= '
            <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
            <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
            <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">

            <script>
                $(document).ready(function () {
                    $("#status-table").DataTable({
                        responsive: true
                    });
                });
            </script>';

            if ($validCount == $detectedCount) {
                if (!empty($insertData)) {
                    // if ($emptyCount > 0) {
                    // return back()->with('excel_error', [
                    //     'message' => "Some rows contain missing data. Please fix and re-upload.",
                    //     'table' => $table_data,
                    //     'emptyCount' => $emptyCount,
                    //     'duplicateCount' => $duplicateCount,
                    //     'errorCount' => $errorCount,
                    //     'detectedCount' => $detectedCount,
                    //     'validCount' => $validCount,
                    //     // 'total_count' => $totalCount,
                    //     'total_count' => $detectedCount
                    // ]);

                    foreach ($insertData as $data) {
                        if ($is_service_account) {
                            $data['is_service_account'] = 1;
                        } else {
                            $data['is_service_account'] = 0;
                            $email_name = $data['email'];
                            $app_pass = decrypt($data['app_email_pass']);
                            $sent_all_count = 0;
                            $all_mail_count = 0;

                            try {
                                $hostname = '{imap.gmail.com:993/imap/ssl}[Gmail]/All Mail';
                                $inbox = imap_open($hostname, $email_name, $app_pass);
                                $inbox_emails = imap_search($inbox, 'ALL');
                                $inbox_json = json_encode($inbox_emails);
                                $all_mail_count = is_array($inbox_emails) ? count($inbox_emails) : 0;
                                imap_close($inbox);
                            } catch (\Exception $e) {
                                return [
                                    'success' => false,
                                    'message' => "Please send valid email or app password. Exception: " . $e->getMessage()
                                ];
                            }

                            try {
                                $sent_hostname = '{imap.gmail.com:993/imap/ssl}[Gmail]/Sent Mail';
                                $sentbox = imap_open($sent_hostname, $email_name, $app_pass) or die('Cannot connect to Gmail Sent Mail: ' . imap_last_error());
                                $sent_emails = imap_search($sentbox, 'ALL');
                                $sent_json = json_encode($sent_emails);
                                $sent_all_count = is_array($sent_emails) ? count($sent_emails) : 0;
                                imap_close($sentbox);
                            } catch (\Exception $e) {
                                return [
                                    'success' => false,
                                    'message' => "Please send valid email or app password. Exception: " . $e->getMessage()
                                ];
                            }
                        }
                        // User Create,
                        //level wise
                        $data['user_level'] = 0;
                        if (Auth::user()->account_type == 0) {
                            $data['account_type'] = 0;
                        } else {
                            $data['account_type'] = 1;
                        }
                        if (!User::where('email', $data['email'])->exists()) {
                            $record = User::create($data);
                            $insertedCount++;
                        }
                        // $record = User::create($data);
                        if ($is_service_account) {
                        } else {
                            $inboxInsertall = UserEmailsIdData::create([
                                'user_id' => $record->id,
                                'email_ids' => $inbox_json,
                                'is_sent_mail' => 0,
                            ]);
                            $sentInsertall = UserEmailsIdData::create([
                                'user_id' => $record->id,
                                'email_ids' => $sent_json,
                                'is_sent_mail' => 1,
                            ]);
                        }
                    }
                    if ($insertedCount) {
                        return back()->with('excel_inserted_success', [
                            'message' => "Successfully inserted records.",
                            'insertedCount' => $insertedCount
                        ]);
                    } else {
                        return back()->with('excel_inserted_error', [
                            'message' => "Insertion failed !",
                            'insertedCount' => $insertedCount
                        ]);
                    }
                    // $status = User::insert($insertData);

                    // if ($status) {
                    //     $insertedCount = count($insertData);
                    //     return back()->with('excel_inserted_success', [
                    //         'message' => "Successfully inserted records.",
                    //         'insertedCount' => $insertedCount
                    //     ]);
                    //     // echo "Successfully inserted $insertedCount records.";
                    // } else {
                    //     return back()->with('excel_inserted_error', [
                    //         'message' => "Insertion failed !",
                    //         'insertedCount' => $insertedCount
                    //     ]);
                    //     // echo "Insert failed!";
                    // }
                }
                // All entries are valid
            } else {

                // // if ($emptyCount > 0) {
                // return back()->with('excel_error', [
                //     'message' => "Some rows contain missing data. Please fix and re-upload.",
                //     'table' => $table_data,
                //     'emptyCount' => $emptyCount,
                //     'duplicateCount' => $duplicateCount,
                //     'errorCount' => $errorCount,
                //     'detectedCount' => $detectedCount,
                //     'validCount' => $validCount,
                //     // 'total_count' => $totalCount
                //     'total_count' => $detectedCount
                // ]);
                return back()->with([
                    'excel_inserted_success' => [
                        'message' => "Successfully inserted records.",
                        'insertedCount' => $insertedCount,
                    ],
                    'excel_error' => [
                        'message' => "Some rows contain missing data. Please fix and re-upload.",
                        'table' => $table_data,
                        'emptyCount' => $emptyCount,
                        'duplicateCount' => $duplicateCount,
                        'errorCount' => $errorCount,
                        'detectedCount' => $detectedCount,
                        'validCount' => $validCount,
                        'total_count' => $detectedCount,
                        'validData' => $validData,
                        'blankData' => $blankData,
                        'errorData' => $errorData,
                        'duplicateData' => $duplicateData,
                    ]
                ]);
            }
            dd($excel_data);
            return back()->with('excel_success', 'File uploaded and data inserted successfully.');
        } catch (\Exception $e) {
            return back()->with('excel_error_catch', 'Upload failed: ' . $e->getMessage());
        }
    }

Declaration:
I hereby declare that the enclosed source code is an original work created by me/us.
It does not contain any confidential information, passwords, or third-party proprietary code.
Signed:
Name:
Date: