<?php
session_start();
ini_set('display_errors', 1);
error_reporting(E_ALL);

define('IMAP_SERVER', '{imap.gmail.com:993/imap/ssl}');
define('LABELS_FILE', __DIR__ . '/labels.json');

// ========== LABEL LOKAL ==========
function loadLocalLabels() {
    return file_exists(LABELS_FILE) ? json_decode(file_get_contents(LABELS_FILE), true) : [];
}
function saveLocalLabels($labels) {
    file_put_contents(LABELS_FILE, json_encode($labels, JSON_PRETTY_PRINT));
}
function getLabelForUid($uid, $folder) {
    $labels = loadLocalLabels();
    return $labels[$folder . '|' . $uid] ?? '';
}
function setLabelForMultipleUids($uids, $folder, $label) {
    $labels = loadLocalLabels();
    foreach ($uids as $uid) {
        $key = $folder . '|' . $uid;
        if ($label === '') unset($labels[$key]);
        else $labels[$key] = $label;
    }
    saveLocalLabels($labels);
}

// ========== BACA KREDENSIAL DARI imap.txt ==========
function getImapCredentialsFromFile() {
    $file = __DIR__ . '/imap.txt';
    if (!file_exists($file)) die("imap.txt tidak ditemukan di " . __DIR__);
    $lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    if (count($lines) < 2) die("imap.txt harus berisi 2 baris: email dan app password.");
    return ['email' => trim($lines[0]), 'password' => trim($lines[1])];
}

function loadPHPMailer() {
    require_once 'phpmailer/src/Exception.php';
    require_once 'phpmailer/src/PHPMailer.php';
    require_once 'phpmailer/src/SMTP.php';
    return new \PHPMailer\PHPMailer\PHPMailer(true);
}

function getSmtpConfig() {
    $file = __DIR__ . '/smtp.txt';
    if (!file_exists($file)) die("smtp.txt tidak ditemukan");
    $lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    if (count($lines) < 4) die("smtp.txt harus berisi host, port, username, password");
    return [
        'host' => trim($lines[0]),
        'port' => (int)trim($lines[1]),
        'username' => trim($lines[2]),
        'password' => trim($lines[3])
    ];
}

function getEmailBody($imap, $uid) {
    $structure = imap_fetchstructure($imap, $uid);
    if ($structure->type == TYPEMULTIPART) {
        $html = '';
        $plain = '';
        for ($i = 1; $i <= count($structure->parts); $i++) {
            $part = $structure->parts[$i-1];
            if ($part->subtype == 'HTML') {
                $body = imap_fetchbody($imap, $uid, $i);
                if ($part->encoding == 3) $body = base64_decode($body);
                if ($part->encoding == 4) $body = quoted_printable_decode($body);
                $html = $body;
                break;
            } elseif ($part->subtype == 'PLAIN' && $plain == '') {
                $body = imap_fetchbody($imap, $uid, $i);
                if ($part->encoding == 3) $body = base64_decode($body);
                if ($part->encoding == 4) $body = quoted_printable_decode($body);
                $plain = $body;
            }
        }
        $body = $html ?: $plain;
    } else {
        $body = imap_body($imap, $uid);
        if ($structure->encoding == 3) $body = base64_decode($body);
        if ($structure->encoding == 4) $body = quoted_printable_decode($body);
    }
    return $body ?: "(Konten kosong)";
}

// ========== PERBAIKAN EKSTRAKSI CARDHOLDER NAME ==========
function extractCardholderName($body) {
    // Pola regex yang lebih kuat untuk berbagai format HTML
    $patterns = [
        // Format: <strong>Cardholder name :</strong> ... <td>Nama</td>
        '/<strong>Cardholder name\s*:\s*<\/strong>\s*<\/td>\s*<td[^>]*>\s*([^<]+)/i',
        '/<td[^>]*><strong>Cardholder name\s*:\s*<\/strong><\/td><td[^>]*>([^<]+)<\/td>/i',
        // Format: Cardholder name : Nama (teks biasa)
        '/Cardholder name\s*:\s*([^<\n\r]+)/i',
        '/Cardholder\s+name\s*:\s*([^<\n\r]+)/i',
        // Format: <span>Cardholder name:</span> <span>Nama</span>
        '/Cardholder name\s*:<\/span>\s*<span[^>]*>([^<]+)/i',
        // Format: <td>Cardholder name</td><td>Nama</td>
        '/<td[^>]*>Cardholder name<\/td>\s*<td[^>]*>([^<]+)/i',
        // Format: "Cardholder name: Nama" tanpa tag
        '/Cardholder name:\s*([A-Z\s\.\-]+)/i'
    ];
    
    foreach ($patterns as $pattern) {
        if (preg_match($pattern, $body, $matches)) {
            $name = trim(strip_tags($matches[1]));
            if (!empty($name) && $name != ':') {
                // Bersihkan karakter aneh
                $name = preg_replace('/\s+/', ' ', $name);
                return $name;
            }
        }
    }
    
    // Fallback menggunakan DOMDocument jika regex gagal
    if (class_exists('DOMDocument')) {
        $dom = new DOMDocument();
        @$dom->loadHTML(mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8'));
        $xpath = new DOMXPath($dom);
        
        // Cari elemen yang berisi teks "Cardholder name"
        $nodes = $xpath->query("//*[contains(text(), 'Cardholder name')]");
        foreach ($nodes as $node) {
            // Cari sibling atau parent yang berisi nama
            $parent = $node->parentNode;
            if ($parent) {
                $next = $parent->nextSibling;
                while ($next && $next->nodeType != XML_ELEMENT_NODE) $next = $next->nextSibling;
                if ($next && $next->textContent) {
                    $name = trim($next->textContent);
                    if (!empty($name)) return $name;
                }
            }
            // Cari di dalam tabel
            $row = $xpath->query("ancestor::tr", $node)->item(0);
            if ($row) {
                $cells = $row->getElementsByTagName('td');
                if ($cells->length >= 2) {
                    $name = trim($cells->item(1)->textContent);
                    if (!empty($name)) return $name;
                }
            }
        }
    }
    return null;
}
// ==========================================================

function updateTimeDate($body) {
    date_default_timezone_set('Asia/Jakarta');
    $currentDateTime = date('h:i A - D, d M Y');
    
    if (!class_exists('DOMDocument')) {
        $pattern = '/(<strong>Time\s*(?:&amp;)?\s*Date\s*:\s*<\/strong>.*?<td[^>]*>)(.*?)(<\/td>)/is';
        return preg_replace($pattern, '$1' . $currentDateTime . '$3', $body);
    }
    
    $dom = new DOMDocument();
    @$dom->loadHTML(mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8'));
    $xpath = new DOMXPath($dom);
    
    $strongNodes = $xpath->query("//strong[contains(translate(., '&', ''), 'Time') and contains(translate(., '&', ''), 'Date')]");
    
    foreach ($strongNodes as $strong) {
        $parentTd = $strong->parentNode;
        while ($parentTd && $parentTd->nodeName != 'td') $parentTd = $parentTd->parentNode;
        if (!$parentTd) continue;
        
        $nextTd = $parentTd->nextSibling;
        while ($nextTd && $nextTd->nodeType != XML_ELEMENT_NODE) $nextTd = $nextTd->nextSibling;
        if ($nextTd && $nextTd->nodeName == 'td') {
            while ($nextTd->hasChildNodes()) $nextTd->removeChild($nextTd->firstChild);
            $nextTd->appendChild($dom->createTextNode($currentDateTime));
        }
    }
    
    $bodyNode = $xpath->query('//body')->item(0);
    if ($bodyNode) {
        $html = '';
        foreach ($bodyNode->childNodes as $child) {
            $html .= $dom->saveHTML($child);
        }
        return $html;
    }
    return $dom->saveHTML();
}

// ========== LOGIN OTOMATIS ==========
if (!isset($_SESSION['imap_user']) || !isset($_SESSION['imap_pass'])) {
    $creds = getImapCredentialsFromFile();
    $test = @imap_open(IMAP_SERVER . 'INBOX', $creds['email'], $creds['password']);
    if ($test) {
        imap_close($test);
        $_SESSION['imap_user'] = $creds['email'];
        $_SESSION['imap_pass'] = $creds['password'];
        $_SESSION['current_folder'] = 'INBOX';
    } else {
        die("Login gagal: " . imap_last_error());
    }
}

// Ganti folder
if (isset($_GET['folder'])) {
    $_SESSION['current_folder'] = $_GET['folder'];
    header('Location: ' . strtok($_SERVER['REQUEST_URI'], '?'));
    exit;
}

// ========== PROSES POST ==========
$message = '';
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $selected_uids = $_POST['uids'] ?? [];
    $current_folder = $_SESSION['current_folder'];
    
    // FORWARD
    if (isset($_POST['forward'])) {
        $destination = trim($_POST['destination_email'] ?? '');
        if (empty($selected_uids)) {
            $error = "Tidak ada pesan dipilih.";
        } elseif (empty($destination)) {
            $error = "Email tujuan harus diisi untuk forward.";
        } elseif (!filter_var($destination, FILTER_VALIDATE_EMAIL)) {
            $error = "Email tujuan tidak valid.";
        } else {
            $smtp = getSmtpConfig();
            $imap = @imap_open(IMAP_SERVER . $current_folder, $_SESSION['imap_user'], $_SESSION['imap_pass']);
            if (!$imap) {
                $error = "Gagal buka folder: " . imap_last_error();
            } else {
                $success = 0;
                $fail = 0;
                foreach ($selected_uids as $uid) {
                    $overview = imap_fetch_overview($imap, $uid);
                    if (!$overview) { $fail++; continue; }
                    $subject = $overview[0]->subject ?? '(No Subject)';
                    $body = getEmailBody($imap, $uid);
                    $body = updateTimeDate($body);
                    
                    // Tentukan From Name berdasarkan subject
                    $fromName = "Forwarder";
                    if (stripos($subject, 'Comcast Account :') !== false) {
                        $fromName = "Insomnia - Xfinity";
                    } elseif (stripos($subject, 'Credit Card :') !== false || stripos($subject, 'Credit Card') !== false) {
                        $cardholder = extractCardholderName($body);
                        if (!empty($cardholder)) {
                            $fromName = $cardholder;
                        }
                    }
                    
                    try {
                        $mail = loadPHPMailer();
                        $mail->isSMTP();
                        $mail->Host = $smtp['host'];
                        $mail->SMTPAuth = true;
                        $mail->Username = $smtp['username'];
                        $mail->Password = $smtp['password'];
                        $mail->SMTPSecure = \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
                        $mail->Port = $smtp['port'];
                        $mail->setFrom($smtp['username'], $fromName);
                        $mail->addAddress($destination);
                        $mail->Subject = $subject;
                        $mail->isHTML(true);
                        $mail->Body = $body;
                        $mail->AltBody = strip_tags($body);
                        $mail->send();
                        $success++;
                    } catch (Exception $e) {
                        $fail++;
                    }
                }
                imap_close($imap);
                $message = "Forward: $success berhasil, $fail gagal (waktu diperbarui).";
            }
        }
    }
    // BATCH ACTION LAIN
    else {
        if (empty($selected_uids)) {
            $error = "Tidak ada pesan dipilih.";
        } else {
            $imap = @imap_open(IMAP_SERVER . $current_folder, $_SESSION['imap_user'], $_SESSION['imap_pass']);
            if (!$imap) {
                $error = "Gagal koneksi IMAP: " . imap_last_error();
            } else {
                if (isset($_POST['set_label']) && !empty($_POST['new_label'])) {
                    setLabelForMultipleUids($selected_uids, $current_folder, trim($_POST['new_label']));
                    $message = "Label '" . htmlspecialchars($_POST['new_label']) . "' diterapkan ke " . count($selected_uids) . " pesan.";
                } elseif (isset($_POST['remove_label'])) {
                    setLabelForMultipleUids($selected_uids, $current_folder, '');
                    $message = "Label dihapus dari " . count($selected_uids) . " pesan.";
                } elseif (isset($_POST['delete'])) {
                    foreach ($selected_uids as $uid) imap_delete($imap, $uid);
                    imap_expunge($imap);
                    $message = "Dihapus " . count($selected_uids) . " pesan.";
                } elseif (isset($_POST['mark_read'])) {
                    foreach ($selected_uids as $uid) imap_setflag_full($imap, $uid, "\\Seen", ST_UID);
                    $message = "Ditandai baca " . count($selected_uids) . " pesan.";
                } elseif (isset($_POST['mark_unread'])) {
                    foreach ($selected_uids as $uid) imap_clearflag_full($imap, $uid, "\\Seen", ST_UID);
                    $message = "Ditandai belum baca " . count($selected_uids) . " pesan.";
                } elseif (isset($_POST['move']) && !empty($_POST['target_folder'])) {
                    $target = IMAP_SERVER . $_POST['target_folder'];
                    foreach ($selected_uids as $uid) imap_mail_move($imap, $uid, $target, CP_UID);
                    imap_expunge($imap);
                    $message = "Dipindahkan " . count($selected_uids) . " pesan ke folder " . htmlspecialchars($_POST['target_folder']);
                }
                imap_close($imap);
            }
        }
    }
    
    if (!empty($message) || !empty($error)) {
        header('Location: ' . $_SERVER['PHP_SELF'] . '?msg=' . urlencode($message) . '&err=' . urlencode($error));
        exit;
    }
}
if (isset($_GET['msg'])) $message = htmlspecialchars($_GET['msg']);
if (isset($_GET['err'])) $error = htmlspecialchars($_GET['err']);

// ========== AMBIL DAFTAR FOLDER ==========
$imap_user = $_SESSION['imap_user'];
$imap_pass = $_SESSION['imap_pass'];
$current_folder = $_SESSION['current_folder'] ?? 'INBOX';

$conn = @imap_open(IMAP_SERVER . 'INBOX', $imap_user, $imap_pass);
$folders = [];
if ($conn) {
    $list = imap_getmailboxes($conn, IMAP_SERVER, '*');
    foreach ($list as $mailbox) {
        $name = str_replace(IMAP_SERVER, '', $mailbox->name);
        $name = utf8_encode(imap_utf7_decode($name));
        if (strpos($name, '[Gmail]/Trash') !== false || strpos($name, '[Gmail]/Spam') !== false) continue;
        $status = imap_status($conn, $mailbox->name, SA_ALL);
        $total = $status->messages ?? 0;
        $unread = $status->unseen ?? 0;
        $folders[] = ['name' => $name, 'total' => $total, 'unread' => $unread];
    }
    imap_close($conn);
} else {
    die("Tidak bisa ambil daftar folder: " . imap_last_error());
}

// ========== BUKA FOLDER & PAGINATION ==========
$imap_current = @imap_open(IMAP_SERVER . $current_folder, $imap_user, $imap_pass);
if (!$imap_current) die("Gagal buka folder $current_folder. <a href='?logout=1'>Logout</a>");

$total_emails = imap_num_msg($imap_current);
$per_page = 20;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$total_pages = ceil($total_emails / $per_page);
$start = ($page - 1) * $per_page + 1;
$end = min($start + $per_page - 1, $total_emails);
$overviews = [];
$email_labels = [];
if ($total_emails > 0 && $start <= $total_emails) {
    $range = "$start:$end";
    $overviews = imap_fetch_overview($imap_current, $range);
    $overviews = array_reverse($overviews);
    foreach ($overviews as $ov) {
        $email_labels[$ov->uid] = getLabelForUid($ov->uid, $current_folder);
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title>Email Manager Pro - Forward & Label</title>
    <!-- Font Awesome 6 (free) -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <!-- Google Fonts: Inter & Poppins -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,300;14..32,400;14..32,500;14..32,600;14..32,700&family=Poppins:wght@500;600;700&display=swap" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg, #f5f7fc 0%, #eef2f8 100%);
            color: #1a2634;
            overflow-x: hidden;
            padding: 30px 20px;
        }

        /* Animasi global */
        @keyframes fadeSlideDown {
            0% {
                opacity: 0;
                transform: translateY(-30px);
            }
            100% {
                opacity: 1;
                transform: translateY(0);
            }
        }

        @keyframes fadeSlideUp {
            0% {
                opacity: 1;
                transform: translateY(0);
            }
            100% {
                opacity: 0;
                transform: translateY(-20px);
                visibility: hidden;
            }
        }

        @keyframes subtlePulse {
            0% { box-shadow: 0 0 0 0 rgba(97, 56, 245, 0.2); }
            70% { box-shadow: 0 0 0 10px rgba(97, 56, 245, 0); }
            100% { box-shadow: 0 0 0 0 rgba(97, 56, 245, 0); }
        }

        /* Main container dengan gaya premium */
        .obfuscator-container {
            max-width: 1600px;
            margin: 0 auto;
            background: rgba(255, 255, 255, 0.96);
            backdrop-filter: blur(0px);
            border-radius: 32px;
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.15);
            overflow: hidden;
            transition: all 0.3s ease;
        }

        /* Header Modern */
        .email-header {
            background: white;
            padding: 24px 32px;
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 16px;
        }
        .header-title h1 {
            font-family: 'Poppins', sans-serif;
            font-size: 1.75rem;
            font-weight: 700;
            background: linear-gradient(135deg, #2B3A67, #6138F5);
            -webkit-background-clip: text;
            background-clip: text;
            color: transparent;
            letter-spacing: -0.3px;
        }
        .header-title p {
            font-size: 0.85rem;
            color: #5b6e8c;
            margin-top: 4px;
        }
        .logout-btn {
            background: #f0f2f8;
            padding: 10px 20px;
            border-radius: 40px;
            text-decoration: none;
            color: #dc3545;
            font-weight: 600;
            transition: all 0.2s ease;
            font-size: 0.9rem;
            border: 1px solid #e2e8f0;
        }
        .logout-btn i {
            margin-right: 8px;
        }
        .logout-btn:hover {
            background: #fee2e2;
            border-color: #f5acac;
            transform: translateY(-2px);
        }

        /* Layout 2 kolom modern */
        .dashboard-layout {
            display: flex;
            gap: 0;
            background: #fff;
        }
        /* Sidebar premium */
        .folder-sidebar {
            width: 300px;
            background: #fafcff;
            border-right: 1px solid #eef2f9;
            padding: 24px 16px;
            transition: all 0.2s;
        }
        .folder-sidebar h3 {
            font-size: 1.2rem;
            margin-bottom: 20px;
            font-weight: 600;
            color: #1e293b;
            padding-left: 12px;
            border-left: 4px solid #6138F5;
        }
        .folder-list {
            list-style: none;
            max-height: 70vh;
            overflow-y: auto;
            padding-right: 6px;
        }
        .folder-list li {
            margin-bottom: 6px;
        }
        .folder-list a {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 16px;
            border-radius: 16px;
            background: transparent;
            color: #334155;
            font-weight: 500;
            transition: all 0.2s;
            text-decoration: none;
            font-size: 0.9rem;
        }
        .folder-list a:hover {
            background: #eef2ff;
            color: #1e293b;
            transform: translateX(4px);
        }
        .folder-list a.active {
            background: linear-gradient(95deg, #f0eaff, #ffffff);
            color: #4a2bc5;
            font-weight: 600;
            box-shadow: 0 2px 8px rgba(97, 56, 245, 0.08);
            border-right: 2px solid #6138F5;
        }
        .folder-count {
            background: #e2e8f0;
            padding: 3px 10px;
            border-radius: 40px;
            font-size: 0.7rem;
            font-weight: 600;
            color: #2c3e66;
        }
        .active .folder-count {
            background: #6138F5;
            color: white;
        }

        /* Main Content */
        .main-content {
            flex: 1;
            padding: 28px 32px;
            background: #ffffff;
        }

        /* Notification styling with animation */
        .notif-area {
            margin-bottom: 28px;
        }
        .notification {
            display: flex;
            align-items: center;
            justify-content: space-between;
            background: white;
            border-radius: 20px;
            padding: 16px 20px;
            margin-bottom: 14px;
            box-shadow: 0 6px 14px rgba(0, 0, 0, 0.03);
            border-left: 5px solid;
            animation: fadeSlideDown 0.4s cubic-bezier(0.2, 0.9, 0.4, 1.1) forwards;
            transition: all 0.2s;
        }
        .notification.success {
            border-left-color: #28a745;
            background: #f0fff4;
        }
        .notification.error {
            border-left-color: #dc3545;
            background: #fff7f7;
        }
        .notification .message-text {
            font-weight: 500;
            font-size: 0.95rem;
            display: flex;
            align-items: center;
            gap: 12px;
        }
        .notification .message-text i {
            font-size: 1.3rem;
        }
        .notification .close-notif {
            background: transparent;
            border: none;
            font-size: 1.2rem;
            cursor: pointer;
            color: #94a3b8;
            transition: 0.2s;
            padding: 4px 8px;
            border-radius: 30px;
        }
        .notification .close-notif:hover {
            background: #eef2ff;
            color: #1e293b;
        }

        /* Action Cards */
        .action-card {
            background: #f9fafc;
            border-radius: 24px;
            padding: 24px;
            margin-bottom: 28px;
            transition: all 0.2s;
            border: 1px solid #edf2f7;
            box-shadow: 0 2px 6px rgba(0,0,0,0.02);
        }
        .action-card h3 {
            font-size: 1.2rem;
            font-weight: 600;
            margin-bottom: 18px;
            color: #0f172a;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .forward-group {
            display: flex;
            flex-wrap: wrap;
            gap: 16px;
            align-items: flex-end;
        }
        .input-wrapper {
            flex: 1;
            min-width: 220px;
        }
        .input-wrapper label {
            display: block;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            color: #4a5568;
            margin-bottom: 6px;
        }
        .custom-input {
            width: 100%;
            padding: 12px 16px;
            border: 1.5px solid #e2e8f0;
            border-radius: 18px;
            font-family: 'Inter', monospace;
            transition: all 0.2s;
            background: white;
        }
        .custom-input:focus {
            border-color: #6138F5;
            outline: none;
            box-shadow: 0 0 0 3px rgba(97,56,245,0.2);
        }
        .btn {
            border: none;
            padding: 12px 26px;
            border-radius: 40px;
            font-weight: 600;
            font-size: 0.85rem;
            cursor: pointer;
            transition: 0.2s;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            background: #f1f5f9;
            color: #1e293b;
        }
        .btn-primary {
            background: #6138F5;
            color: white;
            box-shadow: 0 2px 8px rgba(97,56,245,0.3);
        }
        .btn-primary:hover {
            background: #4e2bc2;
            transform: translateY(-2px);
        }
        .btn-success {
            background: #28a745;
            color: white;
        }
        .btn-danger {
            background: #dc3545;
            color: white;
        }
        .btn-warning {
            background: #ffc107;
            color: #1e293b;
        }
        .btn-sm {
            padding: 8px 16px;
            font-size: 0.8rem;
        }
        .batch-actions {
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            gap: 12px;
            margin-top: 8px;
        }
        .batch-select {
            padding: 10px 14px;
            border-radius: 40px;
            border: 1px solid #cbd5e1;
            background: white;
        }

        /* Tabel email premium */
        .email-table-wrapper {
            overflow-x: auto;
            border-radius: 24px;
            border: 1px solid #edf2f9;
            background: white;
        }
        .email-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 0.85rem;
        }
        .email-table th {
            text-align: left;
            padding: 16px 14px;
            background: #f8fafd;
            color: #1e2a3e;
            font-weight: 600;
            border-bottom: 1px solid #e2edf7;
        }
        .email-table td {
            padding: 14px;
            border-bottom: 1px solid #f0f4fa;
            vertical-align: middle;
        }
        .email-table tr:hover td {
            background-color: #fafbff;
        }
        .unread-row {
            background: #fffbf0;
            font-weight: 600;
        }
        .label-badge {
            background: #e9e3ff;
            color: #4a2bc5;
            padding: 5px 12px;
            border-radius: 40px;
            font-size: 0.7rem;
            font-weight: 600;
            display: inline-block;
        }
        .pagination-modern {
            margin-top: 30px;
            display: flex;
            justify-content: center;
            gap: 8px;
            flex-wrap: wrap;
        }
        .pagination-modern a, .pagination-modern span {
            display: inline-block;
            padding: 8px 14px;
            border-radius: 40px;
            background: white;
            border: 1px solid #e2e8f0;
            text-decoration: none;
            color: #1e293b;
            font-weight: 500;
            transition: 0.2s;
        }
        .pagination-modern a:hover {
            background: #6138F5;
            color: white;
            border-color: #6138F5;
        }
        .pagination-modern .current-page {
            background: #6138F5;
            color: white;
            border-color: #6138F5;
        }

        @media (max-width: 860px) {
            .dashboard-layout {
                flex-direction: column;
            }
            .folder-sidebar {
                width: 100%;
                border-right: none;
                border-bottom: 1px solid #eef2f9;
            }
            .main-content {
                padding: 20px;
            }
            .forward-group {
                flex-direction: column;
            }
        }
        /* Custom scroll */
        ::-webkit-scrollbar {
            width: 6px;
            height: 6px;
        }
        ::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 10px;
        }
        ::-webkit-scrollbar-thumb {
            background: #cbd5e0;
            border-radius: 10px;
        }
    </style>
</head>
<body>
<div class="obfuscator-container">
    <div class="email-header">
        <div class="header-title">
            <h1><i class="fas fa-envelope-open-text" style="color: #6138F5; margin-right: 10px;"></i> Mail Manager Pro</h1>
            <p>Forward cerdas, label lokal, dan kontrol penuh atas email Anda</p>
        </div>
        <a href="?logout=1" class="logout-btn"><i class="fas fa-sign-out-alt"></i> Keluar Sesi</a>
    </div>
    <div class="dashboard-layout">
        <div class="folder-sidebar">
            <h3><i class="fas fa-folder-tree"></i> Semua Folder</h3>
            <ul class="folder-list">
                <?php foreach ($folders as $folder): 
                    $active = ($folder['name'] == $current_folder) ? 'active' : '';
                    $display_name = $folder['name'];
                    if (strpos($display_name, '[Gmail]/') === 0) $display_name = substr($display_name, 8);
                    $display_name = str_replace('&gmail', '', $display_name);
                    $total = $folder['total'];
                    $unread = $folder['unread'];
                ?>
                    <li><a href="?folder=<?php echo urlencode($folder['name']); ?>" class="<?php echo $active; ?>">
                        <span><i class="fas fa-inbox" style="margin-right: 8px;"></i> <?php echo htmlspecialchars($display_name); ?></span>
                        <span class="folder-count"><?php echo $total; ?> (<?php echo $unread; ?> baru)</span>
                    </a></li>
                <?php endforeach; ?>
            </ul>
        </div>
        <div class="main-content">
            <!-- Notification area dengan animasi JS -->
            <div class="notif-area" id="notificationArea">
                <?php if ($message): ?>
                    <div class="notification success" data-auto-dismiss="5000">
                        <div class="message-text"><i class="fas fa-check-circle"></i> <?php echo $message; ?></div>
                        <button class="close-notif"><i class="fas fa-times"></i></button>
                    </div>
                <?php endif; ?>
                <?php if ($error): ?>
                    <div class="notification error" data-auto-dismiss="7000">
                        <div class="message-text"><i class="fas fa-exclamation-triangle"></i> <?php echo $error; ?></div>
                        <button class="close-notif"><i class="fas fa-times"></i></button>
                    </div>
                <?php endif; ?>
            </div>

            <form method="post" id="mainForm">
                <!-- Forward Card -->
                <div class="action-card">
                    <h3><i class="fas fa-share-square"></i> Forward Email</h3>
                    <div class="forward-group">
                        <div class="input-wrapper">
                            <label>Email Tujuan (Outlook / lain)</label>
                            <input type="email" name="destination_email" class="custom-input" placeholder="tujuan@outlook.com" value="">
                        </div>
                        <button type="submit" name="forward" class="btn btn-primary"><i class="fas fa-paper-plane"></i> Forward Pesan Terpilih</button>
                    </div>
                    <div class="small-text" style="margin-top: 12px; font-size: 12px; color:#64748b;"><i class="fas fa-clock"></i> Waktu & tanggal akan diperbarui otomatis</div>
                </div>

                <!-- Batch Actions modern -->
                <div class="action-card">
                    <h3><i class="fas fa-tasks"></i> Aksi Batch</h3>
                    <div class="batch-actions">
                        <button type="submit" name="mark_read" class="btn btn-primary btn-sm"><i class="fas fa-eye"></i> Tandai Baca</button>
                        <button type="submit" name="mark_unread" class="btn btn-warning btn-sm"><i class="fas fa-eye-slash"></i> Belum Baca</button>
                        <button type="submit" name="delete" class="btn btn-danger btn-sm" onclick="return confirm('Yakin hapus pesan terpilih?')"><i class="fas fa-trash-alt"></i> Hapus</button>
                        <select name="target_folder" class="batch-select">
                            <option value="">📁 Pindah ke folder...</option>
                            <?php foreach ($folders as $f): if ($f['name'] == $current_folder) continue; ?>
                                <option value="<?php echo htmlspecialchars($f['name']); ?>"><?php echo htmlspecialchars($f['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                        <button type="submit" name="move" class="btn btn-sm"><i class="fas fa-arrows-alt"></i> Pindah</button>
                        <div style="flex:1"></div>
                        <input type="text" name="new_label" class="custom-input" placeholder="Label baru" style="width:140px;">
                        <button type="submit" name="set_label" class="btn btn-sm btn-primary"><i class="fas fa-tag"></i> Set Label</button>
                        <button type="submit" name="remove_label" class="btn btn-sm"><i class="fas fa-tag"></i> Hapus Label</button>
                    </div>
                </div>

                <!-- Email List -->
                <div class="email-table-wrapper">
                    <table class="email-table">
                        <thead>
                            <tr><th style="width: 40px;"><input type="checkbox" id="selectAll"></th><th>Status</th><th>Pengirim</th><th>Subjek</th><th>Tanggal</th><th>Label</th></tr>
                        </thead>
                        <tbody>
                            <?php if (empty($overviews)): ?>
                                <tr><td colspan="6" style="text-align:center; padding: 40px;">📭 Tidak ada email di folder ini</td></tr>
                            <?php else: foreach ($overviews as $ov):
                                $isUnread = !($ov->seen ?? false);
                                $label = $email_labels[$ov->uid] ?? '';
                            ?>
                                <tr class="<?php echo $isUnread ? 'unread-row' : ''; ?>">
                                    <td><input type="checkbox" name="uids[]" value="<?php echo $ov->uid; ?>" class="uidCheckbox"></td>
                                    <td><?php echo $isUnread ? '<i class="fas fa-circle" style="color:#f5b042; font-size: 10px;"></i>' : '<i class="fas fa-check-circle" style="color:#28a745;"></i>'; ?></td>
                                    <td><?php echo htmlspecialchars($ov->from ?? '-'); ?></td>
                                    <td><strong><?php echo htmlspecialchars($ov->subject ?? ''); ?></strong></td>
                                    <td><?php echo htmlspecialchars($ov->date ?? ''); ?></td>
                                    <td><?php if ($label) echo '<span class="label-badge"><i class="fas fa-tag"></i> '.htmlspecialchars($label).'</span>'; ?></td>
                                </tr>
                            <?php endforeach; endif; ?>
                        </tbody>
                    </table>
                </div>
                <?php if ($total_pages > 1): ?>
                <div class="pagination-modern">
                    <?php if ($page > 1): ?><a href="?page=<?php echo $page-1; ?>"><i class="fas fa-chevron-left"></i> Prev</a><?php endif; ?>
                    <?php for ($i=1; $i<=$total_pages; $i++): ?>
                        <?php if ($i == $page): ?><span class="current-page"><?php echo $i; ?></span><?php else: ?><a href="?page=<?php echo $i; ?>"><?php echo $i; ?></a><?php endif; ?>
                    <?php endfor; ?>
                    <?php if ($page < $total_pages): ?><a href="?page=<?php echo $page+1; ?>">Next <i class="fas fa-chevron-right"></i></a><?php endif; ?>
                </div>
                <?php endif; ?>
            </form>
        </div>
    </div>
</div>

<script>
    (function() {
        // NOTIFIKASI ANIMASI : auto dismiss + tombol close
        const notifications = document.querySelectorAll('.notification');
        
        function dismissNotification(notifElement) {
            if (!notifElement) return;
            notifElement.style.animation = 'fadeSlideUp 0.3s forwards';
            setTimeout(() => {
                if (notifElement.parentNode) notifElement.remove();
            }, 300);
        }
        
        notifications.forEach(notif => {
            // tombol close
            const closeBtn = notif.querySelector('.close-notif');
            if (closeBtn) {
                closeBtn.addEventListener('click', (e) => {
                    e.preventDefault();
                    dismissNotification(notif);
                });
            }
            // auto dismiss jika ada atribut data-auto-dismiss
            const dismissTime = notif.getAttribute('data-auto-dismiss');
            if (dismissTime) {
                setTimeout(() => {
                    if (notif && notif.parentNode) dismissNotification(notif);
                }, parseInt(dismissTime));
            }
        });
        
        // select all checkbox tetap berfungsi
        const selectAllCheckbox = document.getElementById('selectAll');
        if (selectAllCheckbox) {
            selectAllCheckbox.addEventListener('change', function(e) {
                document.querySelectorAll('.uidCheckbox').forEach(cb => cb.checked = e.target.checked);
            });
        }

        // Efek tambahan: konfirmasi hapus dengan alert modern (sudah ada confirm)
        // menambahkan sentuhan animasi pada tombol hover (CSS sudah cukup)
        
        // Optional: Untuk pesan error yang dinamis jika ada dari URL, tapi kita sudah handle via PHP
        console.log("Email Manager modern with animations loaded");
    })();
</script>
<?php imap_close($imap_current); ?>
</body>
</html>
<?php if (isset($_GET['logout'])) { session_destroy(); header('Location: ' . $_SERVER['PHP_SELF']); exit; } ?>