<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Message;
use App\Models\PromotionMail;
use Illuminate\Support\Facades\DB;
use App\Models\Prompt;
use App\Models\SentMail;
use App\Models\User;
use App\Http\Controllers\AuthController;
use Firebase\JWT\JWT;

class MailController extends Controller
{
    //
    public function show($employee_id = null)
    {
        if (!Auth::check()) {
            header('Location: ' . route('login'));
            exit();
        }
        // return $employee_id;
        $counts = $this->common($employee_id);
        $prompts = Prompt::where('user_id', Auth::id())
            ->orderBy('created_at', 'desc')
            ->get();
        // Default: Auth user
        $email = Auth::user()->email;


        // Try employee fetch only if $employee_id is passed
        if ($employee_id) {
            $employee = User::where('id', $employee_id);
            //  $employee->where('auth_id', Auth::id());
            // ->first();
            //level wise
            $user_level = DB::table('users')->where('id', Auth::id())
                ->first();
            if ($user_level->user_level == 2) {
                $employee->where('auth_id', Auth::id());
            } elseif ($user_level->user_level == 1) {
                $employee->where('Department_head_id', Auth::id());
            } elseif ($user_level->user_level == 0) {
            } else {
            }

            $employee = $employee->first();
            // dd($employee);
            if ($employee) {
                return view('mailinfo', compact('counts', 'prompts', 'employee'));
            }
        }
        // dd($email);
        return view('mailinfo', compact('counts', 'prompts', 'email'));
    }
    public function common($employee_id = null)
    {
        $userId = $employee_id ?? Auth::id();

        $admin = \App\Models\User::where('id', $userId)
            ->where('auth_id', 0)
            ->select('id', 'email')
            ->first();
        $emailArray = [];
        if ($admin) {
            // echo "ID: " . $admin->id . "<br>";
            // echo "Email: " . $admin->email;
            $relatedUsers = User::where('auth_id', $admin->id)
                ->get();

            foreach ($relatedUsers as $relatedUser) {
                $emailArray[] = [
                    'id' => $relatedUser->id,
                    'email' => $relatedUser->email,
                ];
            }
            // Print email array
            // print_r($emailArray);
        }
        // die('<br>ee');


        if (is_null($userId)) {
            abort(403, 'Unauthorized action. Please first Login common function Error', ['Content-Type' => 'text/html']);
        }
        // $userId = Auth::id(); // Get logged-in user ID
        // $userId = 1;
        if (true) {
        } else {
            $sentMails = DB::table('sent_mails')
                ->where('user_id', $userId)
                ->where('matched_subject', '0')
                // ->where('sent_mail_id','21')
                ->get();
            // dd($sentMails);
            foreach ($sentMails as $mail) {
                // return;
                // echo $mail->id."<br>";
                if ($mail->sent_mail_id) {
                    $message = DB::table('messages')
                        ->where('user_id', $userId)
                        ->where('clean_subject', $mail->clean_subject)
                        ->where('sender_email', $mail->receiver_email)
                        ->where('sent_mail_id', '-1')
                        ->first();
                    // ->get();
                    // dd( $message);
                    if ($message) {
                        // 2. Update the message to attach it with sent_mail_id
                        $update_messages = DB::table('messages')
                            ->where('id', $message->id)
                            ->update([
                                'sent_mail_id' => $mail->sent_mail_id,
                                'sent_date_s' => $mail->sent_date_s,
                                'message_status' => '1'
                            ]);
                        // echo "1";
                        // echo $update_messages;
                        // dd($update_messages);
                        // 3. Update matched_subject = 1 in current sent_mail row
                        $update_sent_mails = DB::table('sent_mails')
                            ->where('id', $mail->id)
                            ->update([
                                'matched_subject' => 1
                            ]);
                        // echo "2";
                        // echo $update_sent_mails;
                        // dd($update_sent_mails);
                    }
                    // dd("heello");
                }
            }
        }
        // dd("heello");
        // Return data as an associative array
        $user_data = DB::table('users')->where('id', $userId)->first();
        if ($user_data) {
            // $email=null;
            $email = $user_data->email;
            // $query->where('sender_email', '!=',$email );
        }

        if (true) {
            // echo "Related Users:<br>";
            // print_r($emailArray);
            return [
                'employee_data' => $emailArray,

                'countAll' => Message::where('user_id', $userId)->where('sender_email', '!=', $email)->distinct('email_id')->count('id'), // Total unique messages
                'countUnread' => Message::where('user_id', $userId)->where('sender_email', '!=', $email)->where('message_status', 0)->distinct('email_id')->count('id'), // Unread messages
                'countRead' => Message::where('user_id', $userId)->where('sender_email', '!=', $email)->where('message_status', 1)->distinct('email_id')->count('id'), // Read messages

                'countis_not_spam' => Message::where('user_id', $userId)->where('sender_email', '!=', $email)->where('is_spam', 1)->where('is_promotion', '=', '0')->where('message_status', 0)->distinct('email_id')->count('id'),
                'countis_spam' => Message::where('user_id', $userId)->where('sender_email', '!=', $email)->where('is_spam', 0)->where('is_promotion', '=', '0')->where('message_status', 0)->distinct('email_id')->count('id'),
                'neutral' => Message::where('user_id', $userId)->where('sender_email', '!=', $email)->where('is_spam', 3)->where('is_promotion', '=', '0')->where('message_status', 0)->distinct('email_id')->count('id'),

                'promotion' => Message::where('user_id', $userId)->where('is_promotion', '!=', '0')->where('sender_email', '!=', $email)->where('message_status', 0)->distinct('email_id')->count('id'),

                'send-mail' => Message::where('user_id', $userId)->where('sender_email', '!=', $email)->where('is_promotion', '=', '0')->where('track_reply_email', '0')->where('action_required', 1)->distinct('email_id')->count('id'),
                'replied_mail' => Message::where('user_id', $userId)->where('sender_email', '!=', $email)->where('sent_mail_id', '!=', '-1')->distinct('email_id')->where('action_required', 1)->count('id'),

                // 'track_mail' => Message::where('user_id', $userId)->where('is_spam', 2)->where('root_email_id', '!=', 0)->where('message_status', 0)->distinct('email_id')->count('id'),
                // 'track_mail' => Message::where('user_id', $userId)->where('is_spam', 2)->where('root_email_id', '!=', 0)->where('track_reply_email', 0)->where('message_status', 0)->distinct('email_id')->count('id'),            

                'sales' => Message::where('user_id', $userId)->where('sender_email', '!=', $email)->where('category', 1)->where('is_promotion', '=', '0')->where('message_status', 0)->distinct('email_id')->count('id'),
                'amc' => Message::where('user_id', $userId)->where('sender_email', '!=', $email)->where('category', 2)->where('is_promotion', '=', '0')->where('message_status', 0)->distinct('email_id')->count('id'),

                'countis_not_spam_heading' => Prompt::where('user_id', $userId)->where('status', 0)->pluck('keywords')->first(),
            ];
        } else {
            // echo "Related Users:<br>";
            // print_r($emailArray);
            return [
                'employee_data' => $emailArray,

                'countAll' => Message::where('user_id', $userId)->where('sender_email', '!=', $email)->distinct('email_id')->count('id'), // Total unique messages
                'countUnread' => Message::where('user_id', $userId)->where('sender_email', '!=', $email)->where('message_status', 0)->distinct('email_id')->count('id'), // Unread messages
                'countRead' => Message::where('user_id', $userId)->where('sender_email', '!=', $email)->where('message_status', 1)->distinct('email_id')->count('id'), // Read messages

                'countis_not_spam' => Message::where('user_id', $userId)->where('sender_email', '!=', $email)->where('is_spam', 1)->where('is_promotion', '=', '0')->where('message_status', 0)->distinct('email_id')->count('id'),
                'countis_spam' => Message::where('user_id', $userId)->where('sender_email', '!=', $email)->where('is_spam', 0)->where('is_promotion', '=', '0')->where('message_status', 0)->distinct('email_id')->count('id'),
                'neutral' => Message::where('user_id', $userId)->where('sender_email', '!=', $email)->where('is_spam', 3)->where('is_promotion', '=', '0')->where('message_status', 0)->distinct('email_id')->count('id'),

                'promotion' => Message::where('user_id', $userId)->where('is_promotion', '!=', '0')->where('sender_email', '!=', $email)->where('message_status', 0)->distinct('email_id')->count('id'),

                'send-mail' => Message::where('user_id', $userId)->where('sender_email', '!=', $email)->where('sent_mail_id', '-1')->where('action_required', 1)->distinct('email_id')->count('id'),
                'replied_mail' => Message::where('user_id', $userId)->where('sender_email', '!=', $email)->where('sent_mail_id', '!=', '-1')->distinct('email_id')->count('id'),

                // 'track_mail' => Message::where('user_id', $userId)->where('is_spam', 2)->where('root_email_id', '!=', 0)->where('message_status', 0)->distinct('email_id')->count('id'),
                // 'track_mail' => Message::where('user_id', $userId)->where('is_spam', 2)->where('root_email_id', '!=', 0)->where('track_reply_email', 0)->where('message_status', 0)->distinct('email_id')->count('id'),            

                'sales' => Message::where('user_id', $userId)->where('sender_email', '!=', $email)->where('category', 1)->where('message_status', 0)->distinct('email_id')->count('id'),
                'amc' => Message::where('user_id', $userId)->where('sender_email', '!=', $email)->where('category', 2)->where('message_status', 0)->distinct('email_id')->count('id'),

                'countis_not_spam_heading' => Prompt::where('user_id', $userId)->where('status', 0)->pluck('keywords')->first(),
            ];
        }
    }

    public function filterMails($type, $employee_id = null)
    {
        // $counts_not_use = $this->common($employee_id);//its not use anywhere 
        $userId = $employee_id ?? Auth::id();
        // $userId = Auth::id();
        // dd($userId);
        $query = Message::where('user_id', $userId)
            ->distinct('email_id');
        // ->orderBy('id', 'desc');
        // ->orderBy('email_id', 'desc');
        // dd($query);
        $user = DB::table('users')->where('id', $userId)->first();
        if ($user) {
            $email = $user->email;
            $query->where('sender_email', '!=', $email);
        }
        if (true) {
            // $type = "All Mail";
            if ($type == 'all') {
                //if is true they get all mail 
                $type = "All Mail";
            } elseif ($type == 'read') {
                $query->where('message_status', 1);
                $type = "Read Mail";
            } elseif ($type == 'unread') {
                $query->where('message_status', 0);
                $type = "Un-Read Mail";
            } elseif ($type == 'is_spam') {
                $query->where('is_spam', 0)
                    ->where('is_promotion', '=', '0')
                    ->where('message_status', 0); // Only spam emails
                // $type = "Is Not Spam";
                $type = "Negative Mail";
            } elseif ($type == 'is_not_spam') {
                $query->where('is_spam', 1)
                    ->where('is_promotion', '=', '0')
                    ->where('message_status', 0); // Only non-spam emails
                // $type = "Is Spam";
                $type = "Positive Mail";
            } elseif ($type == 'send-mail') {
                // Only send-mail emails
                $query->where('action_required', 1)
                    ->where('is_promotion', '=', '0')
                    ->where('track_reply_email', '0')
                    ->where('message_status', 0);
                $type = 'Reply pending mail';
            } elseif ($type == 'neutral') {
                $query->where('is_spam', 3)
                    ->where('is_promotion', '=', '0')
                    ->where('message_status', 0); // Only neutral emails
                $type = "Neutral Mail";
            } elseif ($type == 'promotion') {
                $query->where('message_status', 0)->where('is_promotion', '!=', '0'); // Only promotion emails
                $type = "Promotion Mail";
            } elseif ($type == 'sales') {
                $query->where('category', 1)
                    ->where('is_promotion', '=', '0')
                    ->where('message_status', 0); // Only sales emails
                $type = "Sales";
            } elseif ($type == 'amc') {
                $query->where('category', 2)
                    ->where('is_promotion', '=', '0')
                    ->where('message_status', 0); // Only amc emails
                $type = "AMC";
            } elseif ($type == 'replied_mail') {
                // $query->where('track_reply_email', '!=', '0');
                $query->where('action_required', 1)
                    ->where('track_reply_email', '!=', '0')
                    ->where('is_promotion', '=', '0')
                    ->whereNotNull('track_reply_email');
                $type = "Replied Mail";
            }
        } else {

            // $type = "All Mail";
            if ($type == 'all') {
                //if is true they get all mail 
                $type = "All Mail";
            } elseif ($type == 'read') {
                $query->where('message_status', 1);
                $type = "Read Mail";
            } elseif ($type == 'unread') {
                $query->where('message_status', 0);
                $type = "Un-Read Mail";
            } elseif ($type == 'is_spam') {
                $query->where('is_spam', 0)->where('message_status', 0); // Only spam emails
                // $type = "Is Not Spam";
                $type = "Negative Mail";
            } elseif ($type == 'is_not_spam') {
                $query->where('is_spam', 1)->where('message_status', 0); // Only non-spam emails
                // $type = "Is Spam";
                $type = "Positive Mail";
            } elseif ($type == 'send-mail') {
                // Only send-mail emails
                $query->where('action_required', 1)
                    ->where('sent_mail_id', '-1')
                    ->where('message_status', 0);
                //         $query->addSelect([
                //             'messages.*',
                //             DB::raw('(
                //         SELECT m2.email_id
                //         FROM messages AS m2
                //         WHERE 
                //             m2.root_email_id = messages.email_id
                //             AND m2.user_id = messages.user_id
                //             AND m2.is_spam = 2
                //             AND m2.track_reply_email = 0
                //         LIMIT 1
                //     ) AS related_email_id'),

                //             DB::raw('(
                //     SELECT m3.message_status
                //     FROM messages AS m3
                //     WHERE 
                //         m3.root_email_id = messages.email_id
                //         AND m3.user_id = messages.user_id
                //         AND m3.is_spam = 2
                //         AND m3.track_reply_email = 0
                //     LIMIT 1
                // ) AS related_message_status'),

                //             DB::raw('(
                //     SELECT m3.created_at
                //     FROM messages AS m3
                //     WHERE 
                //         m3.root_email_id = messages.email_id
                //         AND m3.user_id = messages.user_id
                //         AND m3.is_spam = 2
                //         AND m3.track_reply_email = 0
                //         AND m3.message_status=0
                //     LIMIT 1
                // ) AS new_inserted_date')

                //         ])
                //             ->where('is_spam', 2)
                //             ->where('root_email_id', 0)
                //             ->orderByRaw('new_inserted_date desc');

                // $type = "Replay Mail This all mails are mandatory for reply";
                // $type = 'send-mail';
                $type = 'Reply pending mail';
            } elseif ($type == 'neutral') {
                $query->where('is_spam', 3)->where('message_status', 0); // Only neutral emails
                $type = "Neutral Mail";
            } elseif ($type == 'promotion') {
                $query->where('message_status', 0)->where('is_promotion', '!=', '0'); // Only promotion emails
                $type = "Promotion Mail";
            } elseif ($type == 'sales') {
                $query->where('category', 1)->where('message_status', 0); // Only sales emails
                $type = "Sales";
            } elseif ($type == 'amc') {
                $query->where('category', 2)->where('message_status', 0); // Only amc emails
                $type = "AMC";
            } elseif ($type == 'replied_mail') {
                $query->where('sent_mail_id', '!=', '-1');
                $type = "Replied Mail";
            }
        }

        // $mails = $query->paginate(30);
        // DB::enableQueryLog();
        $mails = $query->orderBy('id', 'desc')->get(); //dd($query->orderBy('id', 'desc')->toSql());
        // dd(DB::getQueryLog());
        $mails = $mails->unique('email_id')->values();
        $counts = $this->common($employee_id);
        // dd($mails);
        if ($employee_id) {
            // $employee = User::where('id', $employee_id)
            //     ->where('auth_id', Auth::id())
            //     ->first();

            $data = User::where('id', $employee_id);
            //level wise
            $user_level = DB::table('users')->where('id', Auth::id())
                ->first();
            if ($user_level->user_level == 2) {
                $data->where('auth_id', Auth::id());
            } elseif ($user_level->user_level == 1) {
                $data->where('Department_head_id', Auth::id());
            } elseif ($user_level->user_level == 0) {
            } else {
            }
            // $data->where('auth_id', Auth::id());
            $employee = $data->first();
            // dd($employee);

            if ($employee) {
                return view('mail.index', compact('mails', 'type', 'counts', 'employee'));
            }
        }
        return view('mail.index', compact('mails', 'type', 'counts'));
    }

    public function single_mail($mail_id, $is_sent = 0, $employee_id = null)
    {
        $email_id = $mail_id;
        // $userId = Auth::id();
        // dd($employee_id);
        $userId = $employee_id ?? Auth::id();
        // Fetch Single Mail Data
        $mail = Message::where('email_id', $mail_id)
            ->where('user_id', $userId)
            ->first(); // Fetch only one record
        if (true) {
        } else {
            if ($is_sent) {
                $mail = SentMail::where('sent_mail_id', $mail_id)
                    ->where('user_id', $userId)
                    ->first();
            }
        }
        // else {
        //     if ($mail) {
        //         $mail->message_status = 1;
        //         $mail->save();
        //     }
        // }
        // dd($mail->id);
        // Check if Mail Exists
        if (!$mail) {
            return 'Mail Not Found Here Mail id not found please chek code';
            return abort(404, 'Mail Not Found Here Mail id not found please chek code'); // Show 404 if not found
        }
        // Function to clean the message content
        function cleanText($text)
        {
            return preg_replace('/[\x{200C}\x{2007}\x{AD}\x{FEFF}]/u', '', $text);
        }
        $mail->message = cleanText($mail->message);
        // dd($mail);
        $counts = $this->common($employee_id);
        if ($employee_id) {
            // $employee = User::where('id', $employee_id)
            //     ->where('auth_id', Auth::id())
            //     ->first();
            $data = User::where('id', $employee_id);
            //level wise
            $user_level = DB::table('users')->where('id', Auth::id())
                ->first();
            if ($user_level->user_level == 2) {
                $data->where('auth_id', Auth::id());
            } elseif ($user_level->user_level == 1) {
                $data->where('Department_head_id', Auth::id());
            } elseif ($user_level->user_level == 0) {
            } else {
            }
            // $data->where('auth_id', Auth::id());
            $employee = $data->first();
            // dd($employee);
            if ($employee) {
                return view('mail.single', compact('email_id', 'counts', 'mail', 'employee', 'is_sent'));
            }
        }
        $employee = Null;
        return view('mail.single', compact('email_id', 'counts', 'mail', 'employee', 'is_sent'));
    }

    public function states(Request $request)
    { //is this use for api 

        $userId = $request->query('user_id');
        $user = User::where('id', $userId)->first();
        if (empty($userId)) {
            return response()->json([
                'status' => false,
                'message' => 'Please send user_id'
            ], 400);
        }
        // Check if user is authenticated
        if (!$userId) {
            return response()->json([
                'status' => false,
                'message' => 'Unauthorized Access',
            ], 401);
        }

        // Fetch Statistics
        if (true) {

            $data = [
                'countAll' => Message::where('user_id', $userId)->where('sender_email', '!=', $user->email)->distinct('email_id')->count('id'),
                'countUnread' => Message::where('user_id', $userId)->where('sender_email', '!=', $user->email)->where('message_status', 0)->distinct('email_id')->count('id'),
                'countRead' => Message::where('user_id', $userId)->where('sender_email', '!=', $user->email)->where('message_status', 1)->distinct('email_id')->count('id'),

                'countis_spam' => Message::where('user_id', $userId)->where('is_promotion', '0')->where('sender_email', '!=', $user->email)->where('is_spam', 0)->where('message_status', 0)->distinct('email_id')->count('id'),
                'countis_not_spam' => Message::where('user_id', $userId)->where('is_promotion', '0')->where('sender_email', '!=', $user->email)->where('is_spam', 1)->where('message_status', 0)->distinct('email_id')->count('id'),

                'promotion' => Message::where('user_id', $userId)->where('is_promotion', '!=', '0')->where('sender_email', '!=', $user->email)->where('message_status', 0)->distinct('email_id')->count('id'),

                'neutral' => Message::where('user_id', $userId)->where('sender_email', '!=', $user->email)->where('is_promotion', '0')->where('is_spam', 3)->where('message_status', 0)->distinct('email_id')->count('id'),
                'send_mail' => Message::where('user_id', $userId)->where('sender_email', '!=', $user->email)->where('is_promotion', '0')->where('action_required', 1)->where('track_reply_email', '0')->distinct('email_id')->count('id'),
                'replied_mail' => Message::where('user_id', $userId)->where('sender_email', '!=', $user->email)->where('is_promotion', '0')->where('action_required', 1)->where('sent_mail_id', '!=', '-1')->distinct('email_id')->count('id'),
                'sales' => Message::where('user_id', $userId)->where('sender_email', '!=', $user->email)->where('is_promotion', '0')->where('category', 1)->where('message_status', 0)->distinct('email_id')->count('id'),
                'amc' => Message::where('user_id', $userId)->where('sender_email', '!=', $user->email)->where('category', 2)->where('message_status', 0)->distinct('email_id')->count('id'),

            ];
        } else {
            $data = [
                'countAll' => Message::where('user_id', $userId)->where('sender_email', '!=', $user->email)->distinct('email_id')->count('id'),
                'countUnread' => Message::where('user_id', $userId)->where('sender_email', '!=', $user->email)->where('message_status', 0)->distinct('email_id')->count('id'),
                'countRead' => Message::where('user_id', $userId)->where('sender_email', '!=', $user->email)->where('message_status', 1)->distinct('email_id')->count('id'),

                'countis_spam' => Message::where('user_id', $userId)->where('sender_email', '!=', $user->email)->where('is_spam', 0)->where('message_status', 0)->distinct('email_id')->count('id'),
                'countis_not_spam' => Message::where('user_id', $userId)->where('sender_email', '!=', $user->email)->where('is_spam', 1)->where('message_status', 0)->distinct('email_id')->count('id'),

                'promotion' => Message::where('user_id', $userId)->where('is_promotion', '!=', '0')->where('sender_email', '!=', $user->email)->where('message_status', 0)->distinct('email_id')->count('id'),

                'neutral' => Message::where('user_id', $userId)->where('sender_email', '!=', $user->email)->where('is_spam', 3)->where('message_status', 0)->distinct('email_id')->count('id'),
                'send_mail' => Message::where('user_id', $userId)->where('sender_email', '!=', $user->email)->where('action_required', 1)->where('sent_mail_id', '-1')->distinct('email_id')->count('id'),
                'sales' => Message::where('user_id', $userId)->where('sender_email', '!=', $user->email)->where('category', 1)->where('message_status', 0)->distinct('email_id')->count('id'),
                'amc' => Message::where('user_id', $userId)->where('sender_email', '!=', $user->email)->where('category', 2)->where('message_status', 0)->distinct('email_id')->count('id'),

            ];
        }
        // $data = [
        //     'countAll' => rand(10, 100), 
        //     'countUnread' => rand(1, 50), 
        //     'countRead' => rand(1, 50), 
        //     'countis_not_spam' => rand(1, 30),
        //     'countis_spam' => rand(1, 20),
        // ];

        return response()->json([
            'status' => true,
            'message' => 'Mail statistics fetched successfully',
            'data' => $data
        ], 200);
    }

    public function sendMailPy($id)
    {
        // ID validation: Check if it's empty or not a valid number
        if (empty($id) || !is_numeric($id)) {
            return response()->json(['error' => 'Please provide a valid ID'], 400);
        }
        $message = Message::find($id);

        if (!$message) {
            return response()->json(['error' => 'Message not found'], 404);
        }

        // `send_py` is update 0 to 1
        Message::where('id', $id)->update(['send_py' => 1]);

        return response()->json(['success' => 'Message updated successfully']);
    }

    function extractTextAndHtml($payload)
    {
        $plainText = '';
        $htmlText = '';

        if (isset($payload['parts'])) {
            foreach ($payload['parts'] as $part) {
                if ($part['mimeType'] === 'text/plain' && isset($part['body']['data'])) {
                    $plainText = base64_decode(strtr($part['body']['data'], '-_', '+/'));
                }

                if ($part['mimeType'] === 'text/html' && isset($part['body']['data'])) {
                    $htmlText = base64_decode(strtr($part['body']['data'], '-_', '+/'));
                }

                // In case of nested parts
                if (isset($part['parts'])) {
                    foreach ($part['parts'] as $subpart) {
                        if ($subpart['mimeType'] === 'text/plain' && isset($subpart['body']['data'])) {
                            $plainText = base64_decode(strtr($subpart['body']['data'], '-_', '+/'));
                        }
                        if ($subpart['mimeType'] === 'text/html' && isset($subpart['body']['data'])) {
                            $htmlText = base64_decode(strtr($subpart['body']['data'], '-_', '+/'));
                        }
                    }
                }
            }
        } else {
            // Fallback when no parts present
            if ($payload['mimeType'] === 'text/plain' && isset($payload['body']['data'])) {
                $plainText = base64_decode(strtr($payload['body']['data'], '-_', '+/'));
            }

            if ($payload['mimeType'] === 'text/html' && isset($payload['body']['data'])) {
                $htmlText = base64_decode(strtr($payload['body']['data'], '-_', '+/'));
            }
        }

        return [$plainText, $htmlText];
    }


    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');
        if (true) {

            // without app password
            $time = date('H:i:s');        // Hour:Minute:Second
            $date = date('d/m/y');
            $logFile =  storage_path('logs/MailController_log.txt');

            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
            ];
            $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');
            // ---------------- 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' => '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'];
            // ---------------- 4. Call Gmail API to List Emails ----------------
            $url = 'https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=30&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);

            // 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);
                foreach ($reversedEmails as $msg_id) {
                    if ($count >= 5) break;
                    $count++;
                    // $msg_id = '19836fe64c58a32a';
                    // echo $msg_id . "<br>";
                    $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);

                    $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'];
                    $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']);

                    $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';


                    $result = $this->callFlaskAPI($send_body);
                    // $resultArray = json_decode($result, true);
                    if (isset($result['code']) && $result['code'] == 250) {
                        $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);

                        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);

                        return response()->json([
                            'message' => 'The model is overloaded. Please try again later. Ai is For some time UNAVAILABLE',
                            '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);
                    $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);

                        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;
                    }

                    $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;
                    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);
                    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"],
                            '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"],
                        "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']
                    ];
                    // echo "<pre>";
                    // print_r($data);
                    // break;
                    // continue;
                    $message = Message::create($data);
                    if ($message) {
                        $store_data++;
                        $insert_messgae = "Get New Mail";
                        // echo "Message inserted successfully!";
                    } else {
                        echo "Error inserting message!";
                    }
                }
                // $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);
        } else {

            $time = date('H:i:s');        // Hour:Minute:Second
            $date = date('d/m/y');
            $logFile =  storage_path('logs/MailController_log.txt');

            // $email_name = "krishna0530mukesoft@gmail.com";  // ?email=xyz@example.com
            // $app_pass = "kmhi qubb pzez mxti"; // ?app_pass=12345
            // $user_id = 7;
            $prompt = Prompt::where('user_id', $user_id)
                ->where('status', 0)
                ->orderBy('id')
                ->first();
            $Categorization = '';
            $ai_Prompt = '';
            if ($prompt) {
                $Categorization = $prompt->keywords;
                $ai_Prompt = $prompt->ai_prompt;
            }
            // echo $Categorization;
            // Validate input (optional)
            if (!$email_name || !$app_pass || !$user_id) {
                return response()->json(['error' => 'user_id and email and app_pass are required'], 400);
            }
            $app_pass = decrypt($request->query('app_pass')); // ?app_pass=12345

            $check_conn = new AuthController();
            $imap_conn = $check_conn->check_conn($email_name, $app_pass);

            if (isset($imap_conn['success']) && $imap_conn['success'] === false) {
                $updated = User::where('id', $user_id)->update([
                    'is_login' => 1
                ]);
                $logMessage = "[$date $time] Email: $email_name | User ID: $user_id | Message: App Password is Expire Please Provide a App Appasword For This Mail ' . $email_name" . PHP_EOL;
                file_put_contents($logFile, $logMessage, FILE_APPEND);
                // Handle failure
                return response()->json([
                    'message' => 'App Password is Expire Please Provide a App Appasword For This Mail ' . $email_name,
                    'status' => false,
                    'code' => 430 //"code": 429 this belongs to handle request is | *Requests per minute (RPM)*   | *15 requests* per minute   
                ], 200);
            }
            // return $imap_conn;

            $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
            ];
            $id = intval($dummyData['id']);
            //all previous sent email IDs 
            $p_inbox_record = DB::table('user_emails_id_data')->where('user_id', $id)->where('is_sent_mail', '0')->first();
            $p_inbox_email_ids = [];

            // if ($p_inbox_record && !empty($p_inbox_record->email_ids)) {
            //     $p_inbox_email_ids = json_decode($p_inbox_record->email_ids, true);
            // }
            // $p_inbox_email_ids = json_decode($p_inbox_record->email_ids, true);
            $p_inbox_email_ids = json_decode($p_inbox_record->email_ids ?? '[]', true);

            $emailIds = $p_inbox_email_ids;
            // dd($p_sent_email_ids);
            //all previous sent 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);
            }

            // echo "<pre>";
            // print_r($emailIds);
            // echo "</pre>";
            // Gmail IMAP credentials
            // $hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
            $hostname = '{imap.gmail.com:993/imap/ssl}[Gmail]/All Mail';
            $username = $email_name; // User ka email (jo GET request se aaya)
            $password = $app_pass; // User ka app password (jo GET request se aaya)

            // IMAP Connection Try-Catch
            try {
                // $hostname = '{imap.gmail.com:993/imap/ssl}';
                // $inbox = imap_open($hostname, $username, $password);
                // $folders = imap_list($inbox, $hostname, '*');
                // imap_close($inbox);
                // dd($folders);

                //sent mail code
                $sent_messages = SentMail::where('user_id', $id)
                    ->select('sent_mail_id', 'user_id')
                    ->get();
                //all previous sent email IDs 
                $p_sent_record = DB::table('user_emails_id_data')->where('user_id', $id)->where('is_sent_mail', '1')->first();
                // $p_sent_email_ids = json_decode($p_sent_record->email_ids, true);
                $p_sent_email_ids = json_decode($p_sent_record->email_ids ?? '[]', true);
                $merged_sent_email_ids = $p_sent_email_ids;
                // dd($p_sent_email_ids);
                //all previous sent email IDs 

                // Check if sent mail data exists
                $sent_emailIds = [];
                if ($sent_messages->isNotEmpty()) {
                    $sent_data = $sent_messages->toArray();
                    $sent_emailIds = collect($sent_data)->pluck('sent_mail_id')->toArray();
                } else {
                    // $sent_data = ["error" => "No sent record found for ID: " . $id];
                }

                $senthostname = '{imap.gmail.com:993/imap/ssl}[Gmail]/Sent Mail';
                ($sentinbox = imap_open($senthostname, $username, $password)) or die('Cannot connect to Gmail: ' . imap_last_error());
                if (!$sentinbox) {
                    return response()->json([
                        "status" => false,
                        'message' => 'please provide a valid mail id or app_password for sent',
                        'error' => 'Cannot connect to Gmail',
                        'imap_error' => imap_last_error()
                    ], 400);
                }
                $sentemails = imap_search($sentinbox, 'ALL');

                // Merge both all previous sent email id(user_emails_id_data table) our database mail id(SentMail table)
                if (!empty($sentemails)) {
                    $merged_sent_email_ids = array_merge($p_sent_email_ids, $sent_emailIds);
                }
                // dd($merged_sent_email_ids);
                // Merge both all previous sent email id(user_emails_id_data table) or our database mail id(SentMail table)

                $sent_subject = '';
                $sent_date_s = '';
                if ($sentemails !== false || !empty($sentemails)) {
                    $sent_matchedEmails = [];
                    $sent_nonMatchedEmails = [];
                    foreach ($sentemails as $email) {
                        if (in_array($email, $merged_sent_email_ids)) {
                            $sent_matchedEmails[] = $email; // If matched, store here
                        } else {
                            $sent_nonMatchedEmails[] = $email; // If not matched, store here
                        }
                    }
                    // dd($sent_nonMatchedEmails);
                    if ($sent_nonMatchedEmails) {
                        // dd($sent_nonMatchedEmails);
                        foreach ($sent_nonMatchedEmails as $sent_email_number) {
                            if ($sent_email_number == -1) {
                                continue; // skip this iteration if email is -1
                            }
                            // $count--;

                            $sent_header = imap_headerinfo($sentinbox, $sent_email_number); //echo "<pre>"; print_r($header);
                            $sent_subject = isset($sent_header->subject) ? imap_utf8($sent_header->subject) : "";
                            $sent_cleanSubject = preg_replace('/^(Re:|Fwd:)\s*/i', '', $sent_subject);
                            $sent_date_s = $sent_header->date ?? 'Unknown Date';
                            //  Receiver (To:)
                            $receiver_email = isset($sent_header->to[0]->mailbox)
                                ? $sent_header->to[0]->mailbox . '@' . $sent_header->to[0]->host
                                : 'Unknown';

                            $receiver_name = isset($sent_header->to[0]->personal)
                                ? imap_utf8($sent_header->to[0]->personal)
                                : 'Unknown Receiver';
                            // Fetch the email structure
                            // get sent mail structure
                            $sent_structure = imap_fetchstructure($sentinbox, $sent_email_number);
                            // echo "<pre>";
                            // print_r($structure); 
                            $sent_plain_text_body = "";
                            $sent_html_body = "";
                            $sent_attachments = [];

                            $sent_ifattchment = 0;
                            $sent_ifimg = 0;

                            if (isset($sent_structure->parts) && count($sent_structure->parts)) {
                                foreach ($sent_structure->parts as $sent_part_number => $sent_part) {
                                    $sent_part_number += 1;

                                    // Extract Attachments
                                    if (isset($sent_part->disposition) && strtolower($sent_part->disposition) == "attachment") {
                                        // echo "partnumer :- " . $part_number;
                                        $sent_ifattchment++;
                                        $sent_attachment_body = $this->extract_body($sentinbox, $sent_email_number, $sent_part, $sent_part_number);
                                        // echo  $attachment_body;
                                        $sent_filename = $sent_part->dparameters[0]->value ?? "attachment_" . time();

                                        $sent_attachments[] = [
                                            'data' => base64_encode($sent_attachment_body),
                                            'filename' => $sent_filename,
                                            'mime' => "application/octet-stream"
                                        ];
                                    }
                                    if (isset($sent_part->disposition) && strtolower($sent_part->disposition) == "inline") {
                                        // echo "get one img";
                                        $sent_ifimg++;
                                    }
                                }
                            }
                            //         echo "<style>
                            //     .pdf-list { cursor: pointer; color: blue; text-decoration: underline; margin-bottom: 5px; }
                            //     .pdf-preview { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.8); }
                            //     .pdf-preview iframe { width: 80%; height: 80%; margin: 5% auto; display: block; background: white; }
                            //     .close-preview { color: white; font-size: 20px; position: absolute; top: 10px; right: 20px; cursor: pointer; }
                            // </style>";

                            //         echo "<script>
                            //     function showPdfPreview(pdfData) {
                            //         document.getElementById('pdf-frame').src = 'data:application/pdf;base64,' + pdfData;
                            //         document.getElementById('pdf-preview').style.display = 'block';
                            //     }
                            //     function closePdfPreview() {
                            //         document.getElementById('pdf-preview').style.display = 'none';
                            //     }
                            // </script>";

                            //     echo "<div id='pdf-preview' class='pdf-preview'>
                            //     <span class='close-preview' onclick='closePdfPreview()'>✖ Close</span>
                            //     <iframe id='pdf-frame'></iframe>
                            //   </div>";

                            if (!empty($sent_attachments)) {
                                $dummyData['sent_attachment_status'] = $sent_ifattchment;
                                // echo "<h3>📎 Attachments:</h3>";
                                foreach ($sent_attachments as $file) {

                                    // echo "<p><a href='data:" . $file['mime'] . ";base64," . $file['data'] . "' download='" . $file['filename'] . "'>📂 " . $file['filename'] . "</a></p>";
                                    // echo "<p>open new tab:- <a href='data:" . $file['mime'] . ";base64," . $file['data'] . "' target='_blank''>📂 " . $file['filename'] . "</a></p>";

                                    // Show Image Attachments in Browser
                                    if (preg_match('/\.(jpg|jpeg|png|gif)$/i', $file['filename'])) {
                                        // echo "<img src='data:image/jpeg;base64," . $file['data'] . "' style='max-width:300px;'><br>";
                                    }
                                    // **Show PDF Preview in Browser**
                                    // if (preg_match('/\.(pdf)$/i', $file['filename'])) {
                                    //     echo "<h3>📄 PDF Preview:</h3>";
                                    //     echo "<iframe src='data:application/pdf;base64," . $file['data'] . "' width='100%' height='600px'></iframe>";
                                    // }
                                    // **Click to Show PDF Preview**
                                    if (preg_match('/\.(pdf)$/i', $file['filename'])) {
                                        // echo "<div class='pdf-list' onclick='showPdfPreview(\"" . $file['data'] . "\")'>📄 " . $file['filename'] . "</div>";
                                    }
                                }
                            }
                            if ($sent_ifimg != 0) {
                                // echo "img found";
                                $sent_imageData = imap_fetchbody($sentinbox, $sent_email_number, 2, FT_PEEK);
                                $sent_imageData = base64_decode($sent_imageData);

                                // Convert to Base64 for HTML display
                                $sent_base64Image = 'data:image/jpeg;base64,' . base64_encode($sent_imageData);

                                $sent_htmlMessage = imap_fetchbody($sentinbox, $sent_email_number, 1.1, FT_PEEK);
                                // Check if it's Base64 encoded

                                // echo "<br>";
                                // echo $htmlMessage;
                                // echo "<br>";
                                // echo "here image file";
                                // Show image in HTML
                                // echo '<img src="' . $base64Image . '" alt="Email Image" style="max-width: 500px; display: block; margin-bottom: 10px;">';
                            } elseif ($sent_ifattchment == 0) {
                                $sent_htmlMessage = imap_fetchbody($sentinbox, $sent_email_number, 2, FT_PEEK);
                                // $htmlMessage = imap_body($inbox, $email_number);
                                $sent_htmlMessage = quoted_printable_decode($sent_htmlMessage);
                                if (empty($sent_htmlMessage)) {
                                    // Try fetching from another part (plain text version)
                                    $sent_htmlMessage = imap_fetchbody($sentinbox, $sent_email_number, 1, FT_PEEK);
                                    $sent_htmlMessage = quoted_printable_decode($sent_htmlMessage);
                                    if (preg_match('/Content-Type:\s*text\/html;.*?\r?\n\r?\n(.*)<\/html>/s', $sent_htmlMessage, $sent_matches)) {
                                        $sent_filteredContent = trim($sent_matches[1]) . "</html>";
                                        $sent_htmlMessage = $sent_filteredContent;
                                        // echo "done";
                                        // echo $htmlMessage;
                                        // $filteredContent= strip_tags($filteredContent);
                                        // echo $filteredContent ;
                                        // echo htmlentities($filteredContent);
                                    } else {
                                        // echo $htmlMessage;
                                        // echo "No matching content found!";
                                    }
                                    // echo "null";
                                }
                                // $dummyData['message_with_html']=htmlentities($htmlMessage);
                                $dummyData['sent_message_with_html'] = $sent_htmlMessage;
                                // echo $htmlMessage;
                                // echo "<b>HTML Messages:</b> ";
                                // CSS aur style tags remove karne ke liye
                                $sent_htmlMessage = preg_replace('/<style\b[^>]*>(.*?)<\/style>/is', '', $sent_htmlMessage);
                                // $htmlMessage=htmlentities($htmlMessage);//print as it is html
                                $sent_htmlMessages = strip_tags($sent_htmlMessage);
                                $sent_htmlMessages = str_replace(["\r\n", "\r", "\n"], ' ', $sent_htmlMessages); // Newline को Space से Replace करें
                                $sent_htmlMessages = preg_replace('/\s+/', ' ', trim($sent_htmlMessages)); // Extra Spaces को Single Space में बदलें

                                // echo htmlentities($htmlMessages);
                                $dummyData['sent_message'] = $sent_htmlMessages;
                            } else {
                                $sent_htmlMessage = imap_fetchbody($sentinbox, $sent_email_number, 1.1, FT_PEEK);
                                // Check if it's Base64 encoded

                                // echo "<br>
                                // here use a 1.1";
                                // echo quoted_printable_decode($htmlMessage);
                                // Extract content after "Content-Transfer-Encoding:"
                                $sent_htmlMessage = quoted_printable_decode($sent_htmlMessage);

                                // Extract only the body content
                                if (preg_match('/Content-Type:\s*text\/html;.*?\r?\n\r?\n(.*)<\/html>/s', $sent_htmlMessage, $sent_matches)) {
                                    $sent_filteredContent = trim($sent_matches[1]) . "</html>";
                                    // echo $filteredContent;

                                    $dummyData['sent_message_with_html'] = $sent_filteredContent;

                                    $sent_filteredContent = strip_tags($sent_filteredContent);
                                    $dummyData['sent_message'] = $sent_filteredContent;
                                    // echo $filteredContent ;

                                } else {
                                    $dummyData['sent_message'] = $sent_htmlMessage;
                                    // echo $htmlMessage."No matching content found!";
                                }
                                // echo $sent_htmlMessage;
                                // echo "<br>";
                                // echo "here have attachment file";
                            }
                            //  echo $sent_htmlMessage;
                            // echo $dummyData['sent_message'];
                            // dd('extract body');
                            SentMail::create([
                                'user_id'         => $dummyData['user_id'],
                                'sent_mail_id'    => $sent_email_number ?? null, // message index/id
                                'matched_subject' => 0, // 0 = not matched
                                'subject'         => $sent_subject,
                                'clean_subject'   => $sent_cleanSubject,
                                'receiver_email'  => $receiver_email,
                                'receiver_name'   => $receiver_name,
                                'sent_htmlMessage' => $dummyData['sent_message'],
                                'sent_date_s' => $sent_date_s
                            ]);
                        }
                    }
                }
                //sent mail code

                $inbox = @imap_open($hostname, $username, $password);

                if (!$inbox) {
                    return response()->json([
                        "status" => false,
                        'message' => 'please provide a valid mail id or app_password',
                        'error' => 'Cannot connect to Gmail',
                        'imap_error' => imap_last_error()
                    ], 400);
                }

                $emails = imap_search($inbox, 'ALL');
                // $emails = imap_search($inbox, 'UNSEEN');
                if ($emails === false || empty($emails)) {
                    return response()->json([
                        'message' => 'No have unseen email.',
                        'status' => false,
                        'code' => 200
                    ], 200);
                }
                $matchedEmails = [];
                $nonMatchedEmails = [];
                // $nonMatchedEmails = [195]; //171
                // $nonMatchedEmails = [50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100];
                // $nonMatchedEmails = [50, 51,52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70];
                // Loop through IMAP fetched emails and compare with database emails
                foreach ($emails as $email) {

                    if (in_array($email, $emailIds)) {
                        $matchedEmails[] = $email; // If matched, store here
                    } else {
                        $nonMatchedEmails[] = $email; // If not matched, store here
                    }
                }
                $store_data = 0;
                $insert_messgae = "No have new mail";
                // dd($nonMatchedEmails);
                if ($nonMatchedEmails) {
                    // rsort($emails);

                    // echo "<h2>📬 Your Latest Emails:</h2>";

                    $count = 0;
                    foreach ($nonMatchedEmails as $email_number) {
                        if ($count >= 5) break;
                        $count++;
                        $header = imap_headerinfo($inbox, $email_number); //echo "<pre>"; print_r($header);
                        $dummyData['email_id'] = $email_number;
                        $dummyData['sender_name'] = ($header->from[0]->personal ?? 'Unknown');
                        $message_id = $header->message_id ?? '';
                        $dummyData['message_id_uniqe'] = $message_id;
                        // echo $message_id;
                        // echo bin2hex($message_id); 
                        // var_dump($message_id);
                        // var_dump(trim($message_id)); 
                        // if (!empty($message_id)) {
                        //     $dummyData['is_promotion'] = $message_id;
                        // } else {
                        // Agar message_id null ya nahi mila to fallback value
                        // $dummyData['is_promotion'] = 0; // ya null, ya skip bhi kar sakte ho
                        // }
                        $message_id_safe = htmlspecialchars($message_id);


                        // echo "<br>".$dummyData['is_promotion']."<br>" ;
                        // var_dump($dummyData['is_promotion']);
                        $dummyData['sender_email'] = ($header->from[0]->mailbox . "@" . $header->from[0]->host);
                        // $dummyData['subject'] = imap_utf8($header->subject);
                        // $dummyData['subject'] = isset($header->subject) ? imap_utf8($header->subject):null;
                        $dummyData['subject'] = isset($header->subject) ? imap_utf8($header->subject) : "";
                        $dummyData['sent_date'] = $header->date;
                        // $dummyData['message_id'] = $header->message_id ?? '';

                        // if ($username == $dummyData['sender_email']) {
                        //     $count--;
                        //     break;
                        // }

                        if (preg_match('/@mail\.gmail\.com>$/', $message_id)) {
                            $dummyData['is_promotion'] = 0;
                            // echo 'F<br>';
                        } else {
                            $dummyData['is_promotion'] = 1;
                            if ($dummyData['sender_email'] === 'drive-shares-dm-noreply@google.com') {
                                $dummyData['is_promotion'] = 0;
                            }
                            // echo $message_id_safe . '<br>';
                        }
                        $cleanSubject = preg_replace('/^(Re:|Fwd:)\s*/i', '', $dummyData['subject']);
                        $dummyData['clean_subject'] = $cleanSubject;
                        $root_email = DB::table('messages')
                            ->where('subject', 'LIKE', "%$cleanSubject%")
                            ->first();

                        if ($root_email) {
                            $dummyData['root_email_id'] = $root_email->email_id;
                            // echo $dummyData['root_email_id'];
                            // dd($root_email);
                        }
                        $track_reply_email = DB::table('messages')
                            ->where('subject', 'LIKE', "%$cleanSubject%")
                            ->orderBy('id', 'desc')
                            ->first();

                        if ($track_reply_email) {
                            $updated_track_reply_email = DB::table('messages')
                                ->where('id', $track_reply_email->id)
                                ->update(['track_reply_email' => 1]);
                            // if ($updated_track_reply_email) {
                            //     echo "Update successful. Rows affected: $updated_track_reply_email";
                            // } else {
                            //     echo "No update performed.";
                            // }
                            // dd($track_reply_email);
                        }
                        // dd($root_email);
                        // $subject = isset($header->subject) ? imap_utf8($header->subject) : Null;
                        $subject = isset($header->subject) ? imap_utf8($header->subject) : "No Subject";
                        $from = isset($header->from[0]->mailbox) ? $header->from[0]->mailbox . "@" . $header->from[0]->host : "Unknown";
                        $from_name = isset($header->from[0]->personal) ? imap_utf8($header->from[0]->personal) : "Unknown Sender";

                        // echo "Sender Name: " . ($header->from[0]->personal ?? 'Unknown') . "<br>";
                        // echo "Sender Email: " . ($header->from[0]->mailbox . "@" . $header->from[0]->host) . "<br>";
                        // echo "Sent Date: " . $header->date . "<br>";
                        // echo "Subject: " . imap_utf8($header->subject) . "<br>";

                        // echo "<hr>";
                        // echo "<b>📌 Email Number:</b> $email_number<br>";
                        // echo "<b>📌 Subject:</b> " . htmlentities($subject) . "<br>";
                        // echo "<b>✉️ From:</b> " . htmlentities($from) . "<br>";
                        // echo "<strong>📌 Email Person Name:</strong> " . htmlentities($from_name) . "<br>";


                        // get mail structure
                        $structure = imap_fetchstructure($inbox, $email_number);
                        // echo "<pre>";
                        // print_r($structure); 
                        $plain_text_body = "";
                        $html_body = "";
                        $attachments = [];

                        $ifattchment = 0;
                        $ifimg = 0;

                        if (isset($structure->parts) && count($structure->parts)) {
                            foreach ($structure->parts as $part_number => $part) {
                                $part_number += 1;

                                // Extract Attachments
                                if (isset($part->disposition) && strtolower($part->disposition) == "attachment") {
                                    // echo "partnumer :- " . $part_number;
                                    $ifattchment++;
                                    $attachment_body = $this->extract_body($inbox, $email_number, $part, $part_number);
                                    // echo  $attachment_body;
                                    $filename = $part->dparameters[0]->value ?? "attachment_" . time();

                                    $attachments[] = [
                                        'data' => base64_encode($attachment_body),
                                        'filename' => $filename,
                                        'mime' => "application/octet-stream"
                                    ];
                                }
                                if (isset($part->disposition) && strtolower($part->disposition) == "inline") {
                                    // echo "get one img";
                                    $ifimg++;
                                }
                            }
                        }
                        //         echo "<style>
                        //     .pdf-list { cursor: pointer; color: blue; text-decoration: underline; margin-bottom: 5px; }
                        //     .pdf-preview { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.8); }
                        //     .pdf-preview iframe { width: 80%; height: 80%; margin: 5% auto; display: block; background: white; }
                        //     .close-preview { color: white; font-size: 20px; position: absolute; top: 10px; right: 20px; cursor: pointer; }
                        // </style>";

                        //         echo "<script>
                        //     function showPdfPreview(pdfData) {
                        //         document.getElementById('pdf-frame').src = 'data:application/pdf;base64,' + pdfData;
                        //         document.getElementById('pdf-preview').style.display = 'block';
                        //     }
                        //     function closePdfPreview() {
                        //         document.getElementById('pdf-preview').style.display = 'none';
                        //     }
                        // </script>";

                        //     echo "<div id='pdf-preview' class='pdf-preview'>
                        //     <span class='close-preview' onclick='closePdfPreview()'>✖ Close</span>
                        //     <iframe id='pdf-frame'></iframe>
                        //   </div>";

                        if (!empty($attachments)) {
                            $dummyData['attachment_status'] = $ifattchment;
                            // echo "<h3>📎 Attachments:</h3>";
                            foreach ($attachments as $file) {

                                // echo "<p><a href='data:" . $file['mime'] . ";base64," . $file['data'] . "' download='" . $file['filename'] . "'>📂 " . $file['filename'] . "</a></p>";
                                // echo "<p>open new tab:- <a href='data:" . $file['mime'] . ";base64," . $file['data'] . "' target='_blank''>📂 " . $file['filename'] . "</a></p>";

                                // Show Image Attachments in Browser
                                if (preg_match('/\.(jpg|jpeg|png|gif)$/i', $file['filename'])) {
                                    // echo "<img src='data:image/jpeg;base64," . $file['data'] . "' style='max-width:300px;'><br>";
                                }
                                // **Show PDF Preview in Browser**
                                // if (preg_match('/\.(pdf)$/i', $file['filename'])) {
                                //     echo "<h3>📄 PDF Preview:</h3>";
                                //     echo "<iframe src='data:application/pdf;base64," . $file['data'] . "' width='100%' height='600px'></iframe>";
                                // }
                                // **Click to Show PDF Preview**
                                if (preg_match('/\.(pdf)$/i', $file['filename'])) {
                                    // echo "<div class='pdf-list' onclick='showPdfPreview(\"" . $file['data'] . "\")'>📄 " . $file['filename'] . "</div>";
                                }
                            }
                        }
                        if ($ifimg != 0) {
                            // echo "img found";
                            $imageData = imap_fetchbody($inbox, $email_number, 2, FT_PEEK);
                            $imageData = base64_decode($imageData);

                            // Convert to Base64 for HTML display
                            $base64Image = 'data:image/jpeg;base64,' . base64_encode($imageData);

                            $htmlMessage = imap_fetchbody($inbox, $email_number, 1.1, FT_PEEK);
                            // Check if it's Base64 encoded

                            // echo "<br>";
                            // echo $htmlMessage;
                            // echo "<br>";
                            // echo "here image file";
                            // Show image in HTML
                            // echo '<img src="' . $base64Image . '" alt="Email Image" style="max-width: 500px; display: block; margin-bottom: 10px;">';
                        } elseif ($ifattchment == 0) {
                            $htmlMessage = imap_fetchbody($inbox, $email_number, 2, FT_PEEK);
                            // $htmlMessage = imap_body($inbox, $email_number);
                            $htmlMessage = quoted_printable_decode($htmlMessage);
                            if (empty($htmlMessage)) {
                                // Try fetching from another part (plain text version)
                                $htmlMessage = imap_fetchbody($inbox, $email_number, 1, FT_PEEK);
                                $htmlMessage = quoted_printable_decode($htmlMessage);
                                if (preg_match('/Content-Type:\s*text\/html;.*?\r?\n\r?\n(.*)<\/html>/s', $htmlMessage, $matches)) {
                                    $filteredContent = trim($matches[1]) . "</html>";
                                    $htmlMessage = $filteredContent;
                                    // echo "done";
                                    // echo $htmlMessage;
                                    // $filteredContent= strip_tags($filteredContent);
                                    // echo $filteredContent ;
                                    // echo htmlentities($filteredContent);
                                } else {
                                    // echo $htmlMessage;
                                    // echo "No matching content found!";
                                }
                                // echo "null";
                            }
                            // $dummyData['message_with_html']=htmlentities($htmlMessage);
                            $dummyData['message_with_html'] = $htmlMessage;
                            // echo $htmlMessage;
                            // echo "<b>HTML Messages:</b> ";
                            // CSS aur style tags remove karne ke liye
                            $htmlMessage = preg_replace('/<style\b[^>]*>(.*?)<\/style>/is', '', $htmlMessage);
                            // $htmlMessage=htmlentities($htmlMessage);//print as it is html
                            $htmlMessages = strip_tags($htmlMessage);
                            $htmlMessages = str_replace(["\r\n", "\r", "\n"], ' ', $htmlMessages); // Newline को Space से Replace करें
                            $htmlMessages = preg_replace('/\s+/', ' ', trim($htmlMessages)); // Extra Spaces को Single Space में बदलें

                            // echo htmlentities($htmlMessages);
                            $dummyData['message'] = $htmlMessages;
                        } else {
                            $htmlMessage = imap_fetchbody($inbox, $email_number, 1.1, FT_PEEK);
                            // Check if it's Base64 encoded

                            // echo "<br>
                            // here use a 1.1";
                            // echo quoted_printable_decode($htmlMessage);
                            // Extract content after "Content-Transfer-Encoding:"
                            $htmlMessage = quoted_printable_decode($htmlMessage);

                            // Extract only the body content
                            if (preg_match('/Content-Type:\s*text\/html;.*?\r?\n\r?\n(.*)<\/html>/s', $htmlMessage, $matches)) {
                                $filteredContent = trim($matches[1]) . "</html>";
                                // echo $filteredContent;

                                $dummyData['message_with_html'] = $filteredContent;

                                $filteredContent = strip_tags($filteredContent);
                                $dummyData['message'] = $filteredContent;
                                // echo $filteredContent ;

                            } else {
                                $dummyData['message'] = $htmlMessage;
                                // echo $htmlMessage."No matching content found!";
                            }


                            // echo $htmlMessage;
                            // echo "<br>";
                            // echo "here have attachment file";
                        }
                        $existingMessage = Message::where('user_id', $dummyData["user_id"])
                            ->where('email_id', $dummyData["email_id"])
                            ->where('email_id', '!=', -1)
                            ->first();

                        if ($existingMessage) {
                            return response()->json([
                                'message' => 'Meassage already exists for this user and email ID.',
                                'status' => false,
                                'code' => 250
                            ], 200);
                        }
                        // echo $dummyData["email_id"] . "<br>";
                        // echo $dummyData["message"];
                        // dd($dummyData);
                        // $result = $this->callFlaskAPI("http://127.0.0.1:5000/predict", $dummyData["message"]);
                        // echo "start gemini api calling";

                        //it`s remove all content On Mon, 14 Jul 2025 at 13:07, Prerana Shinde <prerana.mukesoft@gmail.com> wrote:
                        $dummyData["message"] = preg_replace('/(?:On\s.+?wrote:|[\w\s]+<[^>]+>\swrote:).*$/s', '', $dummyData["message"]);
                        $dummyData["message"] = trim($dummyData["message"]);

                        $result = $this->callFlaskAPI($dummyData["message"], $Categorization, $ai_Prompt);
                        // $resultArray = json_decode($result, true);
                        if (isset($result['code']) && $result['code'] == 250) {
                            $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);

                            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);

                            return response()->json([
                                'message' => 'The model is overloaded. Please try again later. Ai is For some time UNAVAILABLE',
                                '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);
                        $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);

                            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($subject, 'FW:') === 0 || stripos($subject, 'Fwd:') === 0 || stripos($subject, 'RE:') === 0 || stripos($subject, 'Re:') === 0) {
                            } else {
                                // $store_data--;
                                $dummyData["is_spam"] = 100;
                                $dummyData["category"] = 100;
                            }
                        }
                        // if($result==2){
                        //     $dummyData["is_spam"] = 2;//here gemini api not categorised a email
                        // }else
                        // if ($result) {
                        //     $dummyData["is_spam"] = 1;
                        // } else {
                        //     $dummyData["is_spam"] = 0;
                        // }
                        // Classification logic
                        // if (strtolower(trim($result)) === "positive") {  
                        //     $dummyData["is_spam"] = 1;
                        // } elseif (strtolower(trim($result)) === "negative") {
                        //     $dummyData["is_spam"] = 0;
                        // } elseif (strtolower(trim($result)) === "send-mail") {
                        //     $dummyData["is_spam"] = 2;
                        // } elseif (strtolower(trim($result)) === "neutral") {
                        //     $dummyData["is_spam"] = 3;
                        // } elseif (strtolower(trim($result)) === "promotion") {
                        //     $dummyData["is_spam"] = 4;
                        // } else {
                        //     $dummyData["is_spam"] = 100;
                        // }
                        // if ($normalizedResult === "positive") {
                        //     $dummyData["is_spam"] = 1;
                        // } elseif ($normalizedResult === "negative") {
                        //     $dummyData["is_spam"] = 0;
                        // } elseif ($normalizedResult === "send-mail") {
                        //     $dummyData["is_spam"] = 2;
                        // } elseif ($normalizedResult === "neutral") {
                        //     $dummyData["is_spam"] = 3;
                        // } elseif ($normalizedResult === "promotion") {
                        //     $dummyData["is_spam"] = 4;
                        // } elseif ($normalizedResult === "sales") {
                        //     $dummyData["is_spam"] = 5;
                        // } elseif ($normalizedResult === "amc") {
                        //     $dummyData["is_spam"] = 6;
                        // } else {
                        //     $dummyData["is_spam"] = 100;
                        // }

                        // var_dump($dummyData["is_spam"]);
                        // echo"heoo ".$result;
                        // die($dummyData["is_spam"]);
                        // if ($result === 1) {
                        //     $dummyData["is_spam"] = 1;
                        // } elseif ($result === 0) {
                        //     $dummyData["is_spam"] = 0;
                        // } elseif ($result === 2) {
                        //     $dummyData["is_spam"] = 2;
                        // } elseif ($result === 100) {
                        //     $dummyData["is_spam"] = 100;
                        // }
                        // $sql = "INSERT INTO messages 
                        // (user_id, email_id, sender_name, sender_email, subject, sent_date, 
                        // attachment_status, message, message_with_html, message_status,is_spam, created_at, updated_at) 
                        // VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?)";
                        // echo $sql;
                        // // **Prepared Statement बनाएँ**
                        // $stmt = $conn->prepare($sql);
                        $created_at = date('Y-m-d H:i:s');
                        $updated_at = date('Y-m-d H:i:s');
                        // $stmt->bind_param(
                        //     "issssssssssss",
                        //     $dummyData["user_id"],
                        //     $dummyData["email_id"],
                        //     $dummyData["sender_name"],
                        //     $dummyData["sender_email"],
                        //     $dummyData["subject"],
                        //     $dummyData["sent_date"],
                        //     $dummyData["attachment_status"],
                        //     $dummyData["message"],
                        //     $dummyData["message_with_html"],
                        //     $dummyData["message_status"],
                        //     $dummyData["is_spam"],
                        //     $created_at,
                        //     $updated_at
                        // );
                        // **Query Execute करें**
                        // if ($stmt->execute()) {
                        //     $store_data++;
                        //     echo "Message inserted successfully!";
                        // } else {
                        //     echo "Error: " . $stmt->error;
                        // }
                        // dd($dummyData);
                        $impmail = DB::table('impmail')
                            ->where('user_id', $dummyData["user_id"])
                            ->where('sender_email', $dummyData["sender_email"])
                            ->first();

                        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"],
                                'created_at' => now(),
                                'updated_at' => now(),
                            ]);
                        }
                        $data = [
                            "user_id" => $dummyData["user_id"],
                            "email_id" => $dummyData["email_id"],
                            "sender_name" => $dummyData["sender_name"],
                            "sender_email" => $dummyData["sender_email"],
                            "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']
                        ];

                        // if ($dummyData['is_promotion'] == 1) {
                        //     $store_data--;
                        // }
                        // $message = Message::create($data);
                        if ($message) {
                            $store_data++;
                            $insert_messgae = "Get New Mail";
                            // echo "Message inserted successfully!";
                        } else {
                            // echo "Error inserting message!";
                        }
                    }
                }

                // if ($store_data <= 0) {
                //     echo "Data not inserted!";
                // } else {
                //     echo $store_data . " records inserted successfully!";
                // }
                // Connection Successful
                // echo $email_name;
                imap_close($inbox); // Connection close karna zaroori hai
                $counts_not_use = $this->common($dummyData["user_id"]); //its not use anywhere 
                return response()->json([
                    'message' => 'IMAP Connection Established Successfully! or close!',
                    'email' => $email_name,
                    'store_data' => $store_data,
                    'insert messgae' => $insert_messgae
                ], 200);
            } catch (\Exception $e) {
                return response()->json([
                    'error' => 'Exception Occurred In store new mail function: ' . $e->getMessage()
                ], 500);
            }
        }
    }

    function extract_body($inbox, $email_number, $structure, $part_number = "1")
    {
        $body = imap_fetchbody($inbox, $email_number, $part_number, FT_PEEK);
        if ($structure->encoding == 3) { // Base64
            $body = base64_decode($body);
        } elseif ($structure->encoding == 4) { // Quoted-printable
            $body = quoted_printable_decode($body);
        }
        return trim($body);
    }
    function callFlaskAPI($value, $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 = 'AIzaSyB8DemBKum-O_pE_-56OUjOuPSr0cB8Xic'; //krishna api key
        // $apiKey = 'AIzaSyBYl_4WaFNlBVnZptTJgUHrzE9M5UdfmTg'; //Hari api key
        // $apiKey = "AIzaSyDYO_Ktu1sm4A_TpAuAwbWBnTLsNep2Jwo"; //vatsal api key
        // $apiKey = 'AIzaSyBLW4S5bdXLXaxesf0vh6SiakDfhxkvuu4'; // Replace with your Gemini API key
        $apiKey = env('GEMINI_API_KEY'); //paid api key
        $endpoint = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=' . $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);


        curl_close($ch); // cURL Close Karein

        // HTTP Status Code Handling
        if ($httpCode == 404) {
            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) {
            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 == 503) {
            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;
        }

        // JSON Response Decode Karna
        $data = json_decode($response, true);
        // 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 ;
            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;
        }
    }
    //kmhi qubb pzez mxti  jcnn ujnz lcav ltya

    // function callFlaskAPI($endpoint, $value)
    // {
    //     // Base API URL
    //     $url = $endpoint;
    //     $val = strval($value);

    //     // ✅ Function Call
    //     $data = array("text" => $val);

    //     // cURL Initialize
    //     $ch = curl_init($url);

    //     // cURL Options Set Karein
    //     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //     curl_setopt($ch, CURLOPT_POST, true);
    //     curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
    //     curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    //     curl_setopt($ch, CURLOPT_VERBOSE, true); // Debug mode

    //     // API Request Send Karein Aur Response Le
    //     $response = curl_exec($ch);

    //     // HTTP Response Code Check Karein
    //     $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    //     // Agar cURL Error Hai to Print Karein
    //     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
    //     }

    //     curl_close($ch); // cURL Close Karein

    //     // HTTP Status Code Handling
    //     if ($httpCode == 404) {
    //         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) {
    //         return [
    //             'message' => 'Predict Api not working ...! please check this api 500',
    //             'status' => false,
    //             'code' => 250
    //         ];
    //         echo "<br>Error 500: Server Error. Check Flask API logs." . $response;
    //         die("<br>API Not Working: Error 500 - Server Error. Check Flask API logs.");
    //         return false;
    //     }

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

    //     if (isset($decodedResponse['predicted_category'])) {
    //         $category = $decodedResponse['predicted_category'];
    //         // echo "Predicted Category: " . $category;

    //         // ✅ "Good" ho to true, "Bad" ho to false return karega
    //         return strtolower($category) === "good";
    //     } else {
    //         echo "Invalid API Response: " . $response;
    //         return false;
    //     }
    // }

    public function mail_conn($email, $app_pass)
    {
        $hostname = '{imap.gmail.com:993/imap/ssl}INBOX';

        try {
            // Try to connect to Gmail IMAP
            $inbox = imap_open($hostname, $email, $app_pass);

            if (!$inbox) {
                // If connection fails, get the error message
                $errorMessage = imap_last_error();
                return [
                    'success' => false,
                    'message' => "IMAP Connection Failed: " . $errorMessage
                ];
            }

            return [
                'success' => true,
                'message' => "IMAP Connection Established Successfully!",
                "inbox" => $inbox
            ];
        } catch (\Exception $e) {
            // Handle any unexpected exceptions
            return [
                'success' => false,
                'message' => "Please send valid email or app password Exception: " . $e->getMessage()
            ];
        }
    }

    public function close_mail($inbox)
    {
        imap_close($inbox);
    }
}
