<?php
// ==========================================
// BACKEND: FETCH EMAILS DIRECTLY FROM MICROSOFT
// ==========================================
if (isset($_GET['action']) && $_GET['action'] === 'fetch') {
   header('Content-Type: application/json');
   $input = json_decode(file_get_contents('php://input'), true);
   
   if (!$input || !isset($input['email'], $input['refresh_token'], $input['client_id'])) {
       echo json_encode(['status' => false, 'content' => 'Invalid input parameters. Please check your credentials format.']);
       exit;
   }

   $refresh_token = trim($input['refresh_token']);
   $client_id = trim($input['client_id']);

   // ---------------------------------------------------------
   // ADVANCED TOKEN EXCHANGE FUNCTION (v2.0)
   // ---------------------------------------------------------
   function getAccessToken($ref_token, $c_id, $scope = null) {
       $token_url = "https://login.microsoftonline.com/common/oauth2/v2.0/token";
       
       $params = [
           'client_id' => $c_id,
           'refresh_token' => $ref_token,
           'grant_type' => 'refresh_token'
       ];
       
       // Only append scope if it's explicitly provided
       if ($scope !== null) {
           $params['scope'] = $scope;
       }

       $token_data = http_build_query($params);

       $ch = curl_init($token_url);
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
       curl_setopt($ch, CURLOPT_POST, true);
       curl_setopt($ch, CURLOPT_POSTFIELDS, $token_data);
       curl_setopt($ch, CURLOPT_TIMEOUT, 15);
       curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
       curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
       $token_response = curl_exec($ch);
       curl_close($ch);

       return json_decode($token_response, true);
   }

   // ---------------------------------------------------------
   // PRIORITY CLIENT ID HIERARCHY
   // ---------------------------------------------------------
   $client_ids_to_try = [
       $client_id,                             // User's provided Client ID (Highest Priority)
       'a2204928-e097-418b-a0f1-5062a342b2f3', // Native Client (Primary FOCI - Best for Graph API)
       '04b07795-8ddb-461a-bbee-02f9e1bf7b46', // Azure CLI
       '29d9ed98-a469-4536-ade2-f981bc1d605e', // Minecraft
       '1b730954-1685-4b74-9bfd-dac224a7b894', // Xbox
       'd3590ed6-52b3-4102-aeff-aad2292ab01c', // Office
       '1950a258-227b-4e31-a9cf-717495945fc2'  // PowerShell
   ];
   
   $client_ids_to_try = array_unique($client_ids_to_try);

   $valid_access_token = null;
   $opaque_access_token = null;
   $best_error = "Unknown Error";
   $graph_scope = 'offline_access https://graph.microsoft.com/Mail.Read';

   foreach ($client_ids_to_try as $cid) {
       $token_json = getAccessToken($refresh_token, $cid, $graph_scope);
       
       // SMART SCOPE BYPASS: If Microsoft complains about unauthorized scopes, retry WITHOUT requesting a scope!
       if (!isset($token_json['access_token']) && isset($token_json['error_description']) && strpos($token_json['error_description'], 'scopes requested are unauthorized') !== false) {
           $token_json = getAccessToken($refresh_token, $cid, null);
       }

       if (isset($token_json['access_token'])) {
           // Check if we got a valid JWT (must contain a dot '.')
           if (strpos($token_json['access_token'], '.') !== false) {
               $valid_access_token = $token_json['access_token'];
               break;
           } else {
               // We got an Opaque token (no dots). We save it as a backup!
               $opaque_access_token = $token_json['access_token'];
           }
       } else {
           // Capture the error
           $current_error = isset($token_json['error_description']) ? $token_json['error_description'] : (isset($token_json['error']) ? $token_json['error'] : "");
           
           if ($current_error) {
               // Classify fallback client mismatch / unsupported account errors
               $client_mismatch_codes = ['AADSTS70000', 'AADSTS70002', 'AADSTS9002339', 'AADSTS50020'];
               
               $is_client_error = false;
               foreach ($client_mismatch_codes as $code) {
                   if (strpos($current_error, $code) !== false) {
                       $is_client_error = true;
                       break;
                   }
               }

               $best_is_client_error = false;
               foreach ($client_mismatch_codes as $code) {
                   if (strpos($best_error, $code) !== false) {
                       $best_is_client_error = true;
                       break;
                   }
               }
               
               if ($best_error === "Unknown Error") {
                   $best_error = $current_error;
               } else if (!$is_client_error && $best_is_client_error) {
                   // Overwrite client mismatch with a REAL token error (like Expired)
                   $best_error = $current_error;
               }
           }
       }
   }

   $use_outlook_api = false;

   // Final check: Determine which API to use or throw error
   if (!$valid_access_token) {
       if ($opaque_access_token) {
           // Graph API will reject Opaque tokens. Try explicitly requesting an Outlook API token as a final fallback.
           $outlook_scope = 'offline_access https://outlook.office.com/Mail.Read';
           $outlook_token_json = getAccessToken($refresh_token, $client_id, $outlook_scope);
           
           // Scope Bypass for Outlook API as well
           if (!isset($outlook_token_json['access_token']) && isset($outlook_token_json['error_description']) && strpos($outlook_token_json['error_description'], 'scopes requested are unauthorized') !== false) {
               $outlook_token_json = getAccessToken($refresh_token, $client_id, null);
           }

           if (isset($outlook_token_json['access_token'])) {
               $valid_access_token = $outlook_token_json['access_token'];
           } else {
               $valid_access_token = $opaque_access_token; // Fallback to original opaque token
           }
           $use_outlook_api = true;
       } else {
           $clean_error = explode("\r\n", $best_error)[0]; 
           echo json_encode(['status' => false, 'content' => 'Token Error: ' . $clean_error]);
           exit;
       }
   }

   $access_token = $valid_access_token;

   // STEP 3: Fetch Emails from Microsoft (With Auto-Fallback)
   function fetchEmails($url, $token) {
       $ch = curl_init($url);
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
       curl_setopt($ch, CURLOPT_HTTPHEADER, [
           'Authorization: Bearer ' . $token,
           'Content-Type: application/json'
       ]);
       curl_setopt($ch, CURLOPT_TIMEOUT, 20);
       curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
       curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
       $response = curl_exec($ch);
       $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
       curl_close($ch);
       return [$code, $response];
   }

   $graph_url = 'https://graph.microsoft.com/v1.0/me/messages?$top=25&$orderby=receivedDateTime%20desc';
   $outlook_url = 'https://outlook.office.com/api/v2.0/me/messages?$top=25&$orderby=ReceivedDateTime%20desc';

   $primary_url = $use_outlook_api ? $outlook_url : $graph_url;
   $secondary_url = $use_outlook_api ? $graph_url : $outlook_url;

   list($http_code, $msgs_response) = fetchEmails($primary_url, $access_token);

   // Auto-Fallback: If primary API rejects token (401) or mailbox not found (404/403), test the secondary API
   if ($http_code !== 200 && in_array($http_code, [401, 403, 404])) {
       list($fallback_code, $fallback_response) = fetchEmails($secondary_url, $access_token);
       if ($fallback_code === 200) {
           $http_code = $fallback_code;
           $msgs_response = $fallback_response;
       }
   }

   $msgs_json = json_decode($msgs_response, true);

   // Strict check for HTTP Status to prevent silent failure
   if ($http_code !== 200) {
       $err_msg = "Unknown Error";
       if (isset($msgs_json['error']['message'])) {
           $err_msg = $msgs_json['error']['message'];
       } elseif (isset($msgs_json['Message'])) { // Outlook API error format
           $err_msg = $msgs_json['Message'];
       } elseif (is_string($msgs_response) && $msgs_response !== '') {
           $err_msg = explode("\n", strip_tags($msgs_response))[0]; // Take just the first line
       }
       
       if (strlen($err_msg) > 80) $err_msg = substr($err_msg, 0, 80) . '...';
       
       echo json_encode(['status' => false, 'content' => 'API Error (' . $http_code . '): ' . $err_msg]);
       exit;
   }

   if (isset($msgs_json['error'])) {
       $err_msg = isset($msgs_json['error']['message']) ? $msgs_json['error']['message'] : json_encode($msgs_json['error']);
       echo json_encode(['status' => false, 'content' => 'API Error (' . $http_code . '): ' . $err_msg]);
       exit;
   }

   // STEP 4: Format the JSON Response for the Frontend UI
   $formatted_messages = [];
   $latest_code = "";

   if (isset($msgs_json['value']) && is_array($msgs_json['value'])) {
       foreach ($msgs_json['value'] as $msg) {
           // Outlook API uses PascalCase (Subject), Graph uses camelCase (subject).
           $subject = $msg['subject'] ?? $msg['Subject'] ?? '';
           $bodyPreview = $msg['bodyPreview'] ?? $msg['BodyPreview'] ?? '';
           $bodyContent = $msg['body']['content'] ?? $msg['Body']['Content'] ?? '';
           
           $from = $msg['from']['emailAddress']['address'] ?? $msg['From']['EmailAddress']['Address'] ?? 'Unknown';
           $dateStr = $msg['receivedDateTime'] ?? $msg['ReceivedDateTime'] ?? '';
           
           // Extract OTP Code (5 to 8 digits) from subject or preview
           $code = "";
           if (preg_match('/\b\d{5,8}\b/', $subject, $matches)) {
               $code = $matches[0];
           } elseif (preg_match('/\b\d{5,8}\b/', $bodyPreview, $matches)) {
               $code = $matches[0];
           }

           if (empty($latest_code) && !empty($code)) {
               $latest_code = $code;
           }

           $formatted_messages[] = [
               'subject' => $subject,
               'from' => $from,
               'date' => $dateStr ? date('Y-m-d H:i:s', strtotime($dateStr)) : '',
               'message' => $bodyContent, 
               'code' => $code
           ];
       }
   }

   echo json_encode([
       'status' => true,
       'code' => $latest_code,
       'messages' => $formatted_messages
   ]);
   exit;
}

// ==========================================
// IP LOGGING
// ==========================================
function getUserIP() {
   if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
       return $_SERVER['HTTP_CLIENT_IP'];
   } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
       return $_SERVER['HTTP_X_FORWARDED_FOR'];
   } else {
       return $_SERVER['REMOTE_ADDR'];
   }
}

$ip_file = __DIR__ . '/user.json';
$ip_data = [];
if (file_exists($ip_file)) {
   $ip_data = json_decode(file_get_contents($ip_file), true);
   if (!is_array($ip_data)) $ip_data = [];
}

$current_ip = getUserIP();
if (!empty($current_ip) && !in_array($current_ip, $ip_data)) {
   $ip_data[] = $current_ip;
   file_put_contents($ip_file, json_encode($ip_data, JSON_PRETTY_PRINT));
}

$total_users = count($ip_data);
?>
<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
   <title>MailSell Bot - Verification Codes</title>
   
   <meta name="description" content="MailSell Bot - Securely and quickly retrieve email verification codes for Hotmail, Outlook, and Live accounts. Optimized for Telegram Web App.">
   <meta name="keywords" content="MailSell Bot, Verification Codes, Outlook OTP, Hotmail OTP, Email Extractor, Telegram Web App">
   <meta name="author" content="MailSell Bot">
   <meta name="robots" content="index, follow">
   
   <script src="https://telegram.org/js/telegram-web-app.js"></script>
   
   <style>
       :root {
           --bg-color: var(--tg-theme-bg-color, #f4f4f4);
           --text-color: var(--tg-theme-text-color, #111111);
           --hint-color: var(--tg-theme-hint-color, #555555);
           --border-color: #dddddd;
           --card-bg: var(--tg-theme-secondary-bg-color, #ffffff);
           --button-bg: var(--tg-theme-button-color, #111111);
           --button-text: var(--tg-theme-button-text-color, #ffffff);
           --table-header-bg: #e9e9e9;
           --radius: 8px;
           --font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
       }

       @media (prefers-color-scheme: dark) {
           :root {
               --bg-color: var(--tg-theme-bg-color, #121212);
               --text-color: var(--tg-theme-text-color, #f4f4f4);
               --hint-color: var(--tg-theme-hint-color, #aaaaaa);
               --border-color: #333333;
               --card-bg: var(--tg-theme-secondary-bg-color, #1e1e1e);
               --button-bg: var(--tg-theme-button-color, #f4f4f4);
               --button-text: var(--tg-theme-button-text-color, #111111);
               --table-header-bg: #2a2a2a;
           }
       }

       * { box-sizing: border-box; margin: 0; padding: 0; }

       body {
           font-family: var(--font-family);
           background-color: var(--bg-color);
           color: var(--text-color);
           line-height: 1.5;
           padding: 16px;
           min-height: 100vh;
           -webkit-tap-highlight-color: transparent;
       }

       .app-container {
           max-width: 1000px;
           margin: 0 auto;
           padding-bottom: 40px;
       }

       .header {
           display: flex;
           align-items: center;
           justify-content: space-between;
           margin-bottom: 24px;
           padding-bottom: 12px;
           border-bottom: 2px solid var(--text-color);
       }
       .header h1 { font-size: 1.3rem; font-weight: 800; text-transform: uppercase; letter-spacing: 1px; }
       .user-greeting { font-size: 0.9rem; color: var(--hint-color); font-weight: 600;}

       @keyframes rgb-border-anim {
           0% { background-position: 0% 0%, 0% 50%; }
           50% { background-position: 0% 0%, 100% 50%; }
           100% { background-position: 0% 0%, 0% 50%; }
       }

       .rgb-border {
           --inner-bg: var(--card-bg);
           border: 2px solid transparent !important;
           background: linear-gradient(var(--inner-bg), var(--inner-bg)) padding-box,
                       linear-gradient(45deg, #ff0000, #ff7300, #fffb00, #48ff00, #00ffd5, #002bff, #7a00ff, #ff00c8, #ff0000) border-box !important;
           background-size: 100% 100%, 400% 400% !important;
           animation: rgb-border-anim 8s linear infinite !important;
           border-radius: var(--radius);
       }

       .card {
           background: var(--card-bg);
           padding: 20px;
           margin-bottom: 20px;
           box-shadow: 0 2px 8px rgba(0,0,0,0.05);
       }

       .card h2 { font-size: 1.1rem; margin-bottom: 16px; font-weight: 700; border-bottom: 1px solid var(--border-color); padding-bottom: 8px; text-transform: uppercase; }

       .instruction-card { 
           --inner-bg: var(--card-bg);
           padding: 15px; 
           margin-bottom: 20px; 
       }
       .instruction-card h4 { margin-bottom: 10px; font-size: 0.95rem; text-transform: uppercase;}
       .instruction-card ul { padding-left: 20px; font-size: 0.85rem; color: var(--hint-color); }
       .instruction-card li { margin-bottom: 6px; }

       .form-group { margin-bottom: 16px; }
       .form-group label { display: block; font-size: 0.85rem; color: var(--hint-color); margin-bottom: 6px; font-weight: 600; text-transform: uppercase;}
       
       .form-input {
           width: 100%;
           background: var(--bg-color);
           border: 1px solid var(--border-color);
           color: var(--text-color);
           padding: 14px 16px;
           border-radius: var(--radius);
           font-size: 16px;
           outline: none;
           transition: border-color 0.2s;
       }
       .form-input:focus { border-color: var(--text-color); }
       .form-input.rgb-border { --inner-bg: var(--bg-color); }

       .extracted-container {
           display: none; 
           justify-content: space-between; 
           align-items: center; 
           background: var(--bg-color); 
           border: 1px dashed var(--hint-color); 
           padding: 12px 15px; 
           border-radius: var(--radius); 
           margin-top: 15px;
           flex-wrap: wrap;
           gap: 10px;
       }
       .extracted-text {
           font-size: 0.95rem;
           font-weight: 700;
           color: var(--text-color);
           word-break: break-all;
       }

       .submit-btn {
           width: 100%;
           background: var(--button-bg);
           color: var(--button-text);
           border: none;
           padding: 15px;
           border-radius: var(--radius);
           font-size: 16px;
           font-weight: 700;
           text-transform: uppercase;
           cursor: pointer;
           transition: opacity 0.2s;
           margin-top: 10px;
       }
       .submit-btn:active { opacity: 0.8; transform: scale(0.99); }
       .submit-btn.rgb-border { --inner-bg: var(--button-bg); }

       .results-top-bar {
           --inner-bg: var(--bg-color);
           display: flex;
           flex-wrap: wrap;
           justify-content: space-between;
           align-items: center;
           gap: 12px;
           margin-bottom: 20px;
           padding: 12px 15px;
       }
       .otp-compact { display: flex; align-items: center; flex-wrap: wrap; gap: 10px; }
       .otp-compact .label { font-size: 0.85rem; font-weight: 600; color: var(--hint-color); text-transform: uppercase; }
       .otp-compact strong { font-size: 1.4rem; letter-spacing: 2px; }
       
       .action-group { display: flex; gap: 8px; flex-wrap: wrap; }
       .small-btn {
           background: var(--button-bg);
           color: var(--button-text);
           border: none;
           padding: 8px 14px;
           border-radius: var(--radius);
           font-size: 0.85rem;
           font-weight: 600;
           cursor: pointer;
           text-transform: uppercase;
       }
       .small-btn.outline {
           background: transparent;
           color: var(--text-color);
           border: 1px solid var(--border-color);
       }

       .table-container { 
           width: 100%;
           overflow-x: auto; 
           -webkit-overflow-scrolling: touch;
           border: 1px solid var(--border-color);
           border-radius: var(--radius);
           background: var(--bg-color);
       }
       .inbox-table {
           width: 100%;
           border-collapse: collapse;
           font-size: 0.9rem;
           min-width: 800px;
       }
       .inbox-table th, .inbox-table td {
           padding: 14px 12px;
           text-align: left;
           border-bottom: 1px solid var(--border-color);
           vertical-align: middle;
       }
       .inbox-table th {
           font-weight: 700;
           text-transform: uppercase;
           color: var(--text-color);
           background: var(--table-header-bg);
           position: sticky;
           top: 0;
           z-index: 10;
       }
       .inbox-table tbody tr:hover { background: var(--table-header-bg); }
       .td-code { text-align: center; }
       .td-code .code-val { font-weight: 800; font-size: 1.15rem; margin-bottom: 8px; display: block;}
       .td-content .snippet { color: var(--hint-color); margin-right: 5px; line-height: 1.4; display: block; margin-top: 4px; }
       .td-content .details-link { color: var(--button-bg); font-weight: 700; text-decoration: underline; cursor: pointer; white-space: nowrap; display: inline-block; margin-top: 6px; }

       @media (max-width: 600px) {
           .results-top-bar { flex-direction: column; align-items: flex-start; }
           .action-group { width: 100%; }
           .action-group .small-btn { flex: 1; text-align: center; }
       }

       .modal {
           display: none;
           position: fixed; z-index: 3000; left: 0; top: 0; width: 100%; height: 100%;
           background-color: rgba(0,0,0,0.7);
           align-items: center; justify-content: center;
           padding: 15px;
       }
       .modal.show { display: flex; }
       .modal-content {
           background-color: #ffffff;
           color: #000000;
           width: 100%; max-width: 800px; height: 85vh;
           border-radius: var(--radius);
           display: flex; flex-direction: column;
           box-shadow: 0 10px 30px rgba(0,0,0,0.5);
           overflow: hidden;
           animation: popIn 0.3s ease;
       }
       @keyframes popIn { from { transform: scale(0.95); opacity: 0;} to { transform: scale(1); opacity: 1;} }
       
       .modal-header {
           padding: 16px 20px;
           border-bottom: 1px solid #ddd;
           display: flex; justify-content: space-between; align-items: center;
           background: #f4f4f4;
       }
       .modal-header h3 { font-size: 1.1rem; margin: 0; color: #111; font-weight: 700; text-transform: uppercase; }
       .close-modal {
           font-size: 28px;
           font-weight: bold; cursor: pointer; color: #555; line-height: 1;
       }
       .modal-body { flex-grow: 1; padding: 0; position: relative; background: #fff; }
       .modal-iframe { width: 100%; height: 100%; border: none; display: block; }

       .loading-overlay {
           position: fixed;
           top: 0; left: 0; right: 0; bottom: 0;
           background: var(--bg-color);
           display: none; flex-direction: column; align-items: center; justify-content: center;
           z-index: 4000;
           opacity: 0.95;
       }
       .spinner {
           width: 45px;
           height: 45px; border: 4px solid var(--border-color);
           border-top: 4px solid var(--text-color); border-radius: 50%;
           animation: spin 1s linear infinite; margin-bottom: 20px;
       }
       @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }

       .toast {
           position: fixed;
           bottom: -80px; left: 50%; transform: translateX(-50%);
           background: var(--text-color); color: var(--bg-color);
           padding: 14px 28px; border-radius: 30px; font-size: 0.95rem; font-weight: 700;
           box-shadow: 0 4px 15px rgba(0,0,0,0.2);
           transition: bottom 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275); z-index: 5000;
       }
       .toast.show { bottom: 30px; }
   </style>
</head>
<body>

<div class="app-container">

   <div class="header">
       <h1>MailSell Bot</h1>
       <div class="user-greeting" id="user-greeting">Total Users: <?php echo $total_users; ?></div>
   </div>

   <div class="card rgb-border" id="input-section">
       <h2>Get Code</h2>
       
       <div class="instruction-card rgb-border">
           <h4>Instructions</h4>
           <ul>
               <li>Enter data format: <strong>email|password|refresh_token|client_id</strong></li>
               <li>Supported: @hotmail.com, @outlook.com, @live.com</li>
               <li>Fields must be separated by the pipe (|) character.</li>
           </ul>
       </div>

       <div class="form-group">
           <label>Enter Your Hotmail/ Outlook </label>
           <input type="text" id="hotmail-credentials" placeholder="email|pass|token|client" class="form-input rgb-border" autocomplete="off" autocorrect="off" spellcheck="false">
           
           <div class="extracted-container" id="extracted-email-container">
               <span class="extracted-text" id="extracted-email-text"></span>
               <button class="small-btn outline" onclick="copyExtractedEmail()" style="white-space: nowrap;">Copy Email</button>
           </div>
       </div>
       
       <button class="submit-btn rgb-border" onclick="getHotmailCode()">Get Codes</button>
   </div>

   <div class="card rgb-border" id="results-section" style="display: none;">
       <h2>Inbox Results</h2>
       
       <div class="results-top-bar rgb-border">
           <div class="otp-compact">
               <span class="label">Latest Code:</span>
               <strong id="otp-code">------</strong>
               <button class="small-btn" onclick="copyOTP()">Copy</button>
           </div>
           <div class="action-group">
               <button class="small-btn outline" onclick="refreshMessages()">Refresh</button>
               <button class="small-btn outline" onclick="clearResults()">Close</button>
           </div>
       </div>

       <div class="table-container">
           <table class="inbox-table">
               <thead>
                   <tr>
                       <th style="width: 18%;">Mail</th>
                       <th style="width: 5%;">STT</th>
                       <th style="width: 15%;">From</th>
                       <th style="width: 17%;">Time</th>
                       <th style="width: 35%;">Content</th>
                       <th style="width: 10%; text-align: center;">Code</th>
                   </tr>
               </thead>
               <tbody id="messages-list">
               </tbody>
           </table>
       </div>
   </div>

</div>

<div id="email-modal" class="modal">
   <div class="modal-content">
       <div class="modal-header">
           <h3>Email Content</h3>
           <span class="close-modal" onclick="closeModal()">×</span>
       </div>
       <div class="modal-body">
           <iframe id="modal-iframe" class="modal-iframe" sandbox=""></iframe>
       </div>
   </div>
</div>

<div class="loading-overlay" id="loading-overlay">
   <div class="spinner"></div>
   <p style="font-weight: 700; font-size: 1.1rem; text-transform: uppercase;">Getting Code...</p>
</div>
<div class="toast" id="toast">Notification</div>

<script>
const tg = window.Telegram.WebApp;
tg.expand();
tg.ready();

document.addEventListener("DOMContentLoaded", () => {
   const totalUsersCount = "<?php echo $total_users; ?>";
   if (tg.initDataUnsafe && tg.initDataUnsafe.user) {
       document.getElementById('user-greeting').innerHTML = "Hi, " + tg.initDataUnsafe.user.first_name + " • Users: " + totalUsersCount;
   }
});

let currentEmailAddress = "";
window.emailHtmlContents = [];

function showLoading() { document.getElementById('loading-overlay').style.display = 'flex'; }
function hideLoading() { document.getElementById('loading-overlay').style.display = 'none'; }
function showToast(msg) {
   if (tg.HapticFeedback) tg.HapticFeedback.notificationOccurred('success');
   const toast = document.getElementById('toast');
   toast.textContent = msg;
   toast.classList.add('show');
   setTimeout(() => toast.classList.remove('show'), 3000);
}

document.getElementById('hotmail-credentials').addEventListener('input', function(e) {
    const val = e.target.value.trim();
    const container = document.getElementById('extracted-email-container');
    const emailText = document.getElementById('extracted-email-text');
    
    if (val.includes('|')) {
        const parts = val.split('|');
        const possibleEmail = parts[0].trim();
        
        if (possibleEmail.includes('@')) {
            emailText.textContent = possibleEmail;
            container.style.display = 'flex';
        } else {
            container.style.display = 'none';
        }
    } else {
        container.style.display = 'none';
    }
});

function copyExtractedEmail() {
    const email = document.getElementById('extracted-email-text').textContent;
    copySpecificCode(email);
}

async function getHotmailCode() {
   const creds = document.getElementById('hotmail-credentials').value.trim();
   if (creds.split('|').length !== 4) return showToast('Error: Use email|pass|token|client format');
   
   const [email, password, refresh_token, client_id] = creds.split('|');
   currentEmailAddress = email;
   
   showLoading();
   try {
       const response = await fetch('?action=fetch', {
           method: 'POST',
           headers: { 'Content-Type': 'application/json' },
           body: JSON.stringify({ email, password, refresh_token, client_id })
       });
       const data = await response.json();
       hideLoading();
       
       if (data.status) {
           renderTable(data);
           showToast('Inbox Loaded');
       } else {
           showToast(data.content || 'Password Changed / Token Error');
       }
   } catch (error) {
       hideLoading();
       console.error('Fetch error:', error);
       showToast('Server connection error');
   }
}

function extractTextSnippet(html) {
   if (!html) return "";
   const tmp = document.createElement("div");
   tmp.innerHTML = html;
   let text = tmp.textContent || tmp.innerText || "";
   text = text.replace(/\s+/g, ' ').trim();
   return text.length > 60 ? text.substring(0, 60) + '...' : text;
}

function renderTable(data) {
   let displayCode = "------";
   if (data.code && data.code.trim() !== "") {
       displayCode = data.code;
   } else if (data.messages && data.messages.length > 0 && data.messages[0].code) {
       displayCode = data.messages[0].code;
   }
   document.getElementById('otp-code').textContent = displayCode;
   
   const list = document.getElementById('messages-list');
   list.innerHTML = '';
   window.emailHtmlContents = [];
   
   if (data.messages && data.messages.length > 0) {
       data.messages.forEach((msg, index) => {
           const stt = index + 1;
           const snippet = extractTextSnippet(msg.message);
           
           let displayCodeRow = '-';
           if (msg.code) {
               displayCodeRow = `
                   <span class="code-val">${msg.code}</span>
                   <button class="small-btn outline" onclick="copySpecificCode('${msg.code}')">Copy</button>
               `;
           }
           
           window.emailHtmlContents[index] = msg.message || '';
           const subjectPrefix = msg.subject ? `<strong>${msg.subject}</strong>` : '';
           
           list.innerHTML += `
               <tr>
                   <td data-label="Mail"><strong>${currentEmailAddress}</strong></td>
                   <td data-label="STT">${stt}</td>
                   <td data-label="From">${msg.from || '-'}</td>
                   <td data-label="Time">${msg.date || '-'}</td>
                   <td data-label="Content" class="td-content">
                       ${subjectPrefix}
                       <span class="snippet">${snippet}</span>
                       <a onclick="openModal(${index})" class="details-link">Read Full Email >></a>
                   </td>
                   <td data-label="Code" class="td-code">${displayCodeRow}</td>
               </tr>
           `;
       });
   } else {
       list.innerHTML = `<tr><td colspan="6" style="text-align:center; padding: 30px; color: var(--hint-color); font-weight: 600;">No messages found in inbox.</td></tr>`;
   }
   
   document.getElementById('results-section').style.display = 'block';
   setTimeout(() => { document.getElementById('results-section').scrollIntoView({ behavior: 'smooth' }); }, 100);
}

function openModal(index) {
   const htmlContent = window.emailHtmlContents[index];
   const iframe = document.getElementById('modal-iframe');
   iframe.srcdoc = htmlContent;
   document.getElementById('email-modal').classList.add('show');
}

function closeModal() {
   document.getElementById('email-modal').classList.remove('show');
   document.getElementById('modal-iframe').srcdoc = '';
}

window.onclick = function(event) {
   const modal = document.getElementById('email-modal');
   if (event.target == modal) {
       closeModal();
   }
}

function copyOTP() {
   const otp = document.getElementById('otp-code').textContent;
   copySpecificCode(otp);
}

function copySpecificCode(code) {
   if (!code || code === "------") return showToast('No code to copy');
   if (navigator.clipboard && window.isSecureContext) {
       navigator.clipboard.writeText(code).then(() => showToast('Copied to clipboard'));
   } else {
       const ta = document.createElement("textarea"); ta.value = code;
       document.body.appendChild(ta); ta.focus(); ta.select();
       try { document.execCommand('copy'); showToast('Copied'); } catch(e){}
       document.body.removeChild(ta);
   }
}

function refreshMessages() { getHotmailCode(); }

function clearResults() {
   document.getElementById('hotmail-credentials').value = '';
   document.getElementById('extracted-email-container').style.display = 'none';
   document.getElementById('results-section').style.display = 'none';
   showToast('Data Cleared');
}
</script>

</body>
</html>