@extends('layouts.app')

@section('content')
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-8">
                {{-- <h2>{{ $email_id }} or {{ Auth::id() }}</h2> --}}
                @php
                    $spamLabels = [
                        0 => 'Negative',
                        1 => 'Positive',
                        2 => 'Reply-Mail',
                        3 => 'Neutral',
                        4 => 'Promotion',
                        5 => 'Sales',
                        6 => 'AMC',
                        100 => 'Unknown',
                    ];
                @endphp

                <h2><?php
                // echo $is_sent;
                // dd($mail);
                if ($is_sent) {
                    echo "Pending Reply Mail Answer</h2>";
                }else{
                    
                ?>
                    {{ $mail->action_required == 1 && $mail->sent_mail_id == '-1' ? 'Pending Reply / ' : '' }}
                    {{ $mail->sent_mail_id != '-1' ? 'Replied Mail / ' : '' }}
                    {{ $mail->is_promotion == 1 ? 'Promotion Mail / ' : '' }}
                    {{ ucfirst($mail->is_spam_value) }} / Group By :-
                    {{ ucfirst($mail->is_category_value) }} </h2>
                <?php
                }?><p>Welcome to your single Mail Dashboard</p>
            </div>

        </div>
    </div>
    <!-- Add more content as needed -->
    <div class="container-fluid mt-2 mb-4 p-4 border rounded shadow" style="height: 340px; overflow: auto;">

        <?php
        if (true) {
                $msg_id = $email_id;
                $is_emp=0;
            if ($employee) {
                $username = $employee->email;
                $is_emp=1;
                $password = decrypt($employee->app_email_pass);
            } else {
                $username = Auth::user()->email;
                $password = decrypt(Auth::user()->app_email_pass);
            }
            // $sent = new DateTime($mail->sent_date, new DateTimeZone('Asia/Kolkata'));
            $sent = new DateTime($mail->sent_date); // Let it parse the actual timezone
            $sent->setTimezone(new DateTimeZone('Asia/Kolkata')); 
            $sent =$sent->format('d M Y h:i A');
            ?>
        <div class="container-fluid mt-4">
            {{-- <h2>Employee Email ( {{ $username }})</h2> --}}
            @if ($is_emp == 1)
                <h2>
                    Employee Email:- {{ $username }}
                    {{-- ({{ $msg_id }}) --}}
                </h2>
            @endif
            <!-- Displaying the Message HTML in a card style -->
            <div class="card">
                <div class="card-header">
                    <!-- Using the details tag to show summary and body when expanded -->
                    <details>
                        <summary><strong>Basic Info </strong> </summary>
                        <ul>
                            {{-- <li><strong>Sent Date:</strong> {{ htmlentities($sent->format('d M Y H:i A')) }}</li> --}}
                            <li><strong>Sent Date:</strong> {{ htmlentities($sent) }}</li>
                            <li><strong>Subject:</strong> {{ htmlentities($mail->subject) }}</li>
                            <li><strong>Sender Name:</strong> {{ htmlentities($mail->sender_name) }}</li>
                            <li><strong>Sender Email:</strong> {{ htmlentities($mail->sender_email) }}</li>
                        </ul>
                    </details>
                </div>
                <div class="card-body">
                    <!-- Render HTML message body -->
                    {{-- <div>{!! $data->message_with_html !!}</div> --}}
                    {{-- @php
                            if (!empty($mail->message_with_html) && $mail->message_with_html !== 'no data') {
                                echo $mail->message_with_html;
                            } else {
                                echo $mail->message;
                            }
                        @endphp --}}
                    <div>
                        <?php
                        // if (!empty($mail->message_with_html) && $mail->message_with_html !== 'no data') {
                        //     echo $mail->message_with_html;
                        // } else {
                        //     echo $mail->message;
                        // }
                        try {
                            require base_path('vendor/autoload.php');
                        
                            $SERVICE_ACCOUNT_FILE = storage_path('app/email/service-account.json'); // ✅ corrected path
                            $IMPERSONATED_EMAIL = $username;
                        
                            if (!file_exists($SERVICE_ACCOUNT_FILE)) {
                                throw new Exception("Service account file not found at: $SERVICE_ACCOUNT_FILE");
                            }
                        
                            $data = json_decode(file_get_contents($SERVICE_ACCOUNT_FILE), true);
                            $client_email = $data['client_email'] ?? null;
                            $private_key = $data['private_key'] ?? null;
                        
                            if (!$client_email || !$private_key) {
                                throw new Exception('Missing client_email or private_key in service account file.');
                            }
                        
                            $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,
                            ];
                        
                            $jwt = \Firebase\JWT\JWT::encode($payload, $private_key, 'RS256');
                        
                            $ch = curl_init('https://oauth2.googleapis.com/token');
                            curl_setopt_array($ch, [
                                CURLOPT_RETURNTRANSFER => true,
                                CURLOPT_POSTFIELDS => http_build_query([
                                    'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
                                    'assertion' => $jwt,
                                ]),
                                CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'],
                            ]);
                            $response = curl_exec($ch);
                            curl_close($ch);
                        
                            $token_data = json_decode($response, true);
                            $access_token = $token_data['access_token'] ?? null;
                        
                            if (!$access_token) {
                                throw new Exception('Failed to get access token. Response: ' . json_encode($token_data));
                            }
                        
                            // $msg_id = 'YOUR_MESSAGE_ID_HERE'; // 🔁 Replace this with actual message ID dynamically
                            $msg_id = $email_id;
                            $msg_url = "https://gmail.googleapis.com/gmail/v1/users/me/messages/{$msg_id}?format=full";
                            $ch = curl_init($msg_url);
                            curl_setopt_array($ch, [
                                CURLOPT_RETURNTRANSFER => true,
                                CURLOPT_HTTPHEADER => ["Authorization: Bearer $access_token"],
                            ]);
                            $msg_response = curl_exec($ch);
                            curl_close($ch);
                        
                            $msg_data = json_decode($msg_response, true);
                        
                            if (!isset($msg_data['payload'])) {
                                throw new Exception('Email payload is missing. Response: ' . json_encode($msg_data));
                            }
                        
                            // $html = '';
                            // $plain = '';
                            // $parts = $msg_data['payload']['parts'] ?? [$msg_data['payload']];
                        
                            // foreach ($parts as $part) {
                            //     $mime = $part['mimeType'] ?? '';
                            //     $data = $part['body']['data'] ?? '';
                            //     if ($data) {
                            //         $decoded = base64_decode(strtr($data, '-_', '+/'));
                            //         if ($mime === 'text/html' && !$html) {
                            //             $html = $decoded;
                            //         }
                            //         if ($mime === 'text/plain' && !$plain) {
                            //             $plain = nl2br(htmlspecialchars($decoded));
                            //         }
                            //     }
                            // }
                        
                            // echo !empty($html) ? $html : $plain;
                            // if (!empty($html)) {
                            //     echo $html;
                            // } elseif (!empty($plain)) {
                            //     echo $plain;
                            // } elseif (!empty($mail->message_with_html)) {
                            //     echo $mail->message_with_html;
                            // } else {
                            //     echo $mail->message;
                            // }
                            $plain_data = '';
                            $html_data = '';
                            $payload_data = $msg_data['payload'];
                            $mimeType = $payload_data['mimeType'];
                            if ($mimeType == 'text/plain') {
                                $extract_data = $payload_data['body']['data'] ?? '';
                                $plain_data = base64_decode(strtr($extract_data, '-_', '+/'));
                                // echo "get plain text<br>";
                            } elseif ($mimeType == 'text/html') {
                                $extract_data = $payload_data['body']['data'] ?? '';
                                $html_data = base64_decode(strtr($extract_data, '-_', '+/'));
                                $clean_text = preg_replace('/<[^>]*>/', '', $html_data);
                                $plain_data = $clean_text;
                                // echo "get Html text<br>";
                            } elseif ($mimeType == 'multipart/alternative') {
                                $parts = $payload_data['parts'];
                                foreach ($parts as $part) {
                                    $mimeTypes = $part['mimeType'];
                                    $data = $part['body']['data'] ?? null;
                                    if ($data) {
                                        $decoded = base64_decode(strtr($data, '-_', '+/'));
                        
                                        if ($mimeTypes === 'text/plain') {
                                            $plain_data = $decoded;
                                        } elseif ($mimeTypes === 'text/html') {
                                            $html_data = $decoded;
                                        }
                                    }
                                }
                                // echo "get multipart/alternative <br>";
                            } elseif ($mimeType == 'multipart/related') {
                                $parts_related = $payload_data['parts'];
                                $realted_mimetype = [];
                                foreach ($parts_related as $part) {
                                    $realted_mimetype[] = $part['mimeType'];
                        
                                    if ($part['mimeType'] == 'multipart/alternative') {
                                        $parts = $part['parts'];
                                        foreach ($parts as $part) {
                                            $mimeTypes = $part['mimeType'];
                                            $data = $part['body']['data'] ?? null;
                                            if ($data) {
                                                $decoded = base64_decode(strtr($data, '-_', '+/'));
                        
                                                if ($mimeTypes === 'text/plain') {
                                                    $plain_data = $decoded;
                                                    // echo "enter in plain body";
                                                } elseif ($mimeTypes === 'text/html') {
                                                    $html_data = $decoded;
                                                }
                                            }
                                        }
                                    }
                                }
                                // print_r($realted_mimetype);echo  " <= multipart/related <br>";echo "get multipart/related <br>";
                            } elseif ($mimeType == 'multipart/mixed') {
                                $mixed_parts = $payload_data['parts'];
                                $mixed_mimetype = [];
                                foreach ($mixed_parts as $part) {
                                    $mixed_mimetype[] = $part['mimeType'];
                        
                                    if ($part['mimeType'] == 'multipart/related') {
                                        $related_child_parts = $part['parts'];
                                        $related_child_parts_mimetype = [];
                                        // print_r($alternative_child_parts);
                                        // echo " <br>enter in related_child_parts <br>";
                        
                                        foreach ($related_child_parts as $part_child) {
                                            $related_child_parts_mimetype[] = $part_child['mimeType'];
                                            if ($part_child['mimeType'] == 'multipart/alternative') {
                                                $alternative_child_parts = $part_child['parts'];
                                                $alternative_child_parts_mimetype = [];
                                                foreach ($alternative_child_parts as $part_grand_child) {
                                                    $alternative_child_parts_mimetype[] = $part_grand_child['mimeType'];
                                                    $alternative_child_grand_mimetype = $part_grand_child['mimeType'];
                                                    $data = $part_grand_child['body']['data'] ?? null;
                                                    if ($data) {
                                                        $decoded = base64_decode(strtr($data, '-_', '+/'));
                        
                                                        if ($alternative_child_grand_mimetype === 'text/plain') {
                                                            $plain_data = $decoded;
                                                            // echo "enter in plain body";
                                                        } elseif ($alternative_child_grand_mimetype === 'text/html') {
                                                            $html_data = $decoded;
                                                        }
                                                    }
                                                }
                                                // echo " <br>enter in alternative_child_parts <br>";
                                            }
                                        }
                                    }
                                }
                                // print_r($mixed_mimetype); //echo  " <= multipart/related <br>";echo "get multipart/related <br>";
                                // print_r($related_child_parts_mimetype);
                                // print_r($alternative_child_parts_mimetype);
                                // echo "get multipart/mixed <br>";
                            } else {
                                $plain_data = 'get different memtype';
                                $html_data = 'get different memtype';
                                // echo 'get different memtype <br>';
                            }
                            // echo $mimeType . '<br>';
                            echo !empty($html_data) ? $html_data : $plain_data;
                        } catch (Throwable $e) {
                            echo '<div style="color:red; padding:10px; border:1px solid #f00; background:#fee;">                                                                                                                                                                                                                                                                                                                                                                                                                                                                <strong>Error:</strong> ' . htmlspecialchars($e->getMessage()) . '</div>';
                        }
                        ?>
                    </div>

                </div>
            </div>
            <?php
            // echo '<strong>Sender Name:</strong> ' . htmlentities($mail->sender_name) . '<br>';
            // echo '<strong>Sender Email:</strong> ' . htmlentities($mail->sender_email) . '<br>';
            // echo '<strong>Subject:</strong> ' . htmlentities($mail->subject) . '<br>';
            // // echo '<strong>Sent Date:</strong> ' . htmlentities($mail->sent_date) . '<br>';
            // $sent = new DateTime($mail->sent_date, new DateTimeZone('Asia/Kolkata'));
            // echo '<strong>Sent Date:</strong> ' . htmlentities($sent->format('d M Y H:i A')) . '<br>';
        
            // if (!empty($mail->message_with_html) && $mail->message_with_html !== 'no data') {
            //     echo $mail->message_with_html;
            // } else {
            //     echo $mail->message;
            // }

            // echo $mail->message_with_html;
        } else {
            //email fetching code
            try {
                //  exit;
                // dd($mail->id);
                // $hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
                $hostname = '{imap.gmail.com:993/imap/ssl}[Gmail]/All Mail';
                if ($is_sent) {
                    $hostname = '{imap.gmail.com:993/imap/ssl}[Gmail]/Sent Mail';
                }
                if ($employee) {
                    $username = $employee->email;
                    $password = decrypt($employee->app_email_pass);
                } else {
                    $username = Auth::user()->email;
                    $password = decrypt(Auth::user()->app_email_pass);
                }
                // echo $username;
                // echo $password;
                // $password = Auth::user()->app_email_pass;
                // dd();
                ($inbox = imap_open($hostname, $username, $password)) or die('Cannot connect to Gmail: ' . imap_last_error());
        
                $emails = imap_search($inbox, 'ALL');
                $email_number = $email_id;
                // $email_number=91;
                // ✅ Extract Email Body
                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);
                }
        
                $header = imap_headerinfo($inbox, $email_number); //echo "<pre>"; print_r($header);
                $subject = isset($header->subject) ? imap_utf8($header->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 'Subject: ' . $subject . '<br><br/>';
                $senderName = $header->from[0]->personal ?? 'Unknown';
                $senderEmail = ($header->from[0]->mailbox ?? '') . '@' . ($header->from[0]->host ?? '');
                $sentDate = $header->date ?? 'Unknown Date';
                $emailSubject = $subject ?? 'No Subject';
                $fullDetails = "From: $senderName <$senderEmail> |   Sent On: $sentDate ";
                echo '<details>';
                echo '<summary><strong>Email Info</strong></summary>';
                echo '<p>' . htmlspecialchars($fullDetails) . '</p>Subject:- ' . $emailSubject;
                echo '</details><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 = 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)) {
                    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);
                        $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";
                    }
                    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
                    // $htmlMessage = strip_tags($htmlMessage);
                    // echo $htmlMessage;
                } 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(.*)/s', $htmlMessage, $matches)) {
                        $filteredContent = trim($matches[1]);
                        echo $filteredContent;
                        // $filteredContent= strip_tags($filteredContent);
                        // echo $filteredContent ;
                        // echo htmlentities($filteredContent);
                    } else {
                        echo $htmlMessage;
                        // echo "No matching content found!";
                    }
                    // echo "<br>";
                    echo 'here have attachment file';
                }
                //email fetching code
        
                // exit;
                //databse code
                // Database Connection
                // $conn = new mysqli('localhost', 'root', '', 'email', '3307');
        
                // // Check Connection
                // if ($conn->connect_error) {
                //     die('Connection failed: ' . $conn->connect_error);
                // }
        
                // Update Query
                // $sql = 'UPDATE messages SET message_status = 1 WHERE email_id = ? AND user_id = ?';
        
                // Prepare and Bind
                // $stmt = $conn->prepare($sql);
                // $user_id = Auth::id();
                // $stmt->bind_param('si', $email_id, $user_id); // "s" for string, "i" for integer
        
                // Execute Query
                // if ($stmt->execute()) {
                //     echo 'Record updated successfully!';
                // } else {
                //     echo 'Error updating record: ' . $conn->error;
                // }
        
                // Close Connection
                // $stmt->close();
                // $conn->close();
                //databse code
            } catch (\Exception $e) {
                // Handle any exception (decryption or IMAP)
                echo "<h2 style='color:red; text-align:center; margin-top:20px;'>
                                                                                                                                                                                                Unable to connect to your email account.<br>
                                                                                                                                                                                                Please contact your technical team or the Service provider.
                                                                                                                                                                                            </h2>";
                echo "<h2 style='color:red; text-align:center; margin-top:20px;'>" . $e->getMessage() . '</h2>';
            }
        }
        ?>
        </div>
    @endsection


    @push('scripts')
    @endpush
