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

require_once 'config.php';
require_once 'email_config.php';
date_default_timezone_set('Asia/Jakarta');

// ============================================================
// INCLUDE PHPMailer SEKALI SAJA DI ATAS
// ============================================================
require_once $_SERVER['DOCUMENT_ROOT'] . '/phpmailer/src/Exception.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/phpmailer/src/PHPMailer.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/phpmailer/src/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Cek login
if (!isset($_SESSION['username'])) {
    header("Location: login.php");
    exit();
}

// Koneksi ke database
try {
    $db = new PDO('mysql:host=localhost;dbname=erniinrk_solo', 'erniinrk_solo', 'Kelentit123@');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

// ============================================================
// FUNGSI UNTUK MENGAMBIL PLAIN TEXT DARI EMAIL
// ============================================================
function getPlainTextBody($inbox, $email_num, $structure) {
    $plain_text = '';
    
    // Jika tidak ada bagian (parts), ambil body langsung
    if (!isset($structure->parts) || empty($structure->parts)) {
        $body = imap_body($inbox, $email_num);
        if ($structure->encoding == 3) {
            $body = base64_decode($body);
        } elseif ($structure->encoding == 4) {
            $body = quoted_printable_decode($body);
        }
        return trim($body);
    }
    
    // Loop melalui semua bagian
    foreach ($structure->parts as $part_index => $part) {
        if ($part->subtype == 'PLAIN' && $part->type == 0) {
            $body = imap_fetchbody($inbox, $email_num, $part_index + 1);
            if ($part->encoding == 3) {
                $body = base64_decode($body);
            } elseif ($part->encoding == 4) {
                $body = quoted_printable_decode($body);
            }
            $plain_text = trim($body);
            break;
        }
        
        if (isset($part->parts)) {
            foreach ($part->parts as $sub_part_index => $sub_part) {
                if ($sub_part->subtype == 'PLAIN' && $sub_part->type == 0) {
                    $body = imap_fetchbody($inbox, $email_num, $part_index + 1 . '.' . ($sub_part_index + 1));
                    if ($sub_part->encoding == 3) {
                        $body = base64_decode($body);
                    } elseif ($sub_part->encoding == 4) {
                        $body = quoted_printable_decode($body);
                    }
                    $plain_text = trim($body);
                    break 2;
                }
            }
        }
    }
    
    if (empty($plain_text)) {
        foreach ($structure->parts as $part_index => $part) {
            if ($part->subtype == 'HTML' && $part->type == 0) {
                $body = imap_fetchbody($inbox, $email_num, $part_index + 1);
                if ($part->encoding == 3) {
                    $body = base64_decode($body);
                } elseif ($part->encoding == 4) {
                    $body = quoted_printable_decode($body);
                }
                $plain_text = strip_tags($body);
                $plain_text = trim($plain_text);
                break;
            }
        }
    }
    
    return $plain_text;
}

// ============================================================
// FUNGSI FETCH EMAIL DARI SERVER
// ============================================================
function fetchEmailsFromServer($inbox) {
    $emails = imap_search($inbox, 'UNSEEN');
    $fetched = 0;
    
    if ($emails) {
        rsort($emails);
        $limit = 50;
        
        foreach ($emails as $email_num) {
            if ($fetched >= $limit) break;
            
            $header = imap_headerinfo($inbox, $email_num);
            $structure = imap_fetchstructure($inbox, $email_num);
            $plain_body = getPlainTextBody($inbox, $email_num, $structure);
            
            $message_id = $header->message_id;
            $checkStmt = $GLOBALS['db']->prepare("SELECT id FROM email_messages WHERE message_id = ?");
            $checkStmt->execute([$message_id]);
            
            if ($checkStmt->rowCount() == 0) {
                $sender = $header->fromaddress;
                $subject = $header->subject;
                $date = date('Y-m-d H:i:s', strtotime($header->date));
                
                $stmt = $GLOBALS['db']->prepare("
                    INSERT INTO email_messages (message_id, subject, sender, recipient, message, status, created_at)
                    VALUES (?, ?, ?, ?, ?, 'unread', ?)
                ");
                $stmt->execute([
                    $message_id,
                    $subject,
                    $sender,
                    IMAP_USERNAME,
                    $plain_body,
                    $date
                ]);
                $fetched++;
            }
        }
    }
    
    return $fetched;
}

// ============================================================
// FUNGSI FETCH EMAIL (DIPANGGIL VIA AJAX)
// ============================================================
function fetchEmails() {
    $inbox = imap_open(IMAP_HOST, IMAP_USERNAME, IMAP_PASSWORD);
    if (!$inbox) {
        return ['error' => 'Gagal terhubung ke email server: ' . imap_last_error()];
    }
    
    $fetched = fetchEmailsFromServer($inbox);
    imap_close($inbox);
    
    return ['success' => $fetched . ' email baru diterima'];
}

// ============================================================
// AUTO-FETCH EMAIL SAAT HALAMAN DIMUAT
// ============================================================
$autoFetchMessage = null;

// Cek kapan terakhir fetch (dari tabel)
$lastFetchCheck = $db->prepare("SELECT MAX(created_at) as last_fetch FROM email_messages");
$lastFetchCheck->execute();
$lastFetch = $lastFetchCheck->fetch(PDO::FETCH_ASSOC);

$doAutoFetch = true;
if ($lastFetch && $lastFetch['last_fetch']) {
    $lastFetchTime = strtotime($lastFetch['last_fetch']);
    $now = time();
    // Jika terakhir fetch kurang dari 5 menit, skip auto-fetch
    if (($now - $lastFetchTime) < 300) {
        $doAutoFetch = false;
    }
}

// Jika perlu fetch, lakukan
if ($doAutoFetch) {
    $inbox = imap_open(IMAP_HOST, IMAP_USERNAME, IMAP_PASSWORD);
    if ($inbox) {
        $fetched = fetchEmailsFromServer($inbox);
        imap_close($inbox);
        if ($fetched > 0) {
            $autoFetchMessage = $fetched . ' email baru diterima otomatis';
        }
    }
}

// ============================================================
// PROSES DELETE EMAIL (AJAX)
// ============================================================
if (isset($_POST['action']) && $_POST['action'] == 'delete') {
    $id = $_POST['id'] ?? 0;
    
    try {
        $stmt = $db->prepare("DELETE FROM email_messages WHERE id = ?");
        $stmt->execute([$id]);
        
        if ($stmt->rowCount() > 0) {
            echo json_encode(['success' => true, 'message' => 'Email berhasil dihapus']);
        } else {
            echo json_encode(['success' => false, 'error' => 'Email tidak ditemukan']);
        }
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit();
}

// ============================================================
// FUNGSI SEND REPLY
// ============================================================
function sendReply($to, $subject, $message, $reply_to_id = null) {
    $mail = new PHPMailer(true);
    
    try {
        $mail->isSMTP();
        $mail->Host       = SMTP_HOST;
        $mail->SMTPAuth   = true;
        $mail->Username   = SMTP_USERNAME;
        $mail->Password   = SMTP_PASSWORD;
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port       = SMTP_PORT;
        $mail->AuthType   = 'LOGIN';
        
        $mail->setFrom(SMTP_FROM_EMAIL, SMTP_FROM_NAME);
        $mail->addAddress($to);
        $mail->Subject = $subject;
        $mail->Body    = $message;
        $mail->isHTML(false);
        
        $mail->send();
        
        if ($reply_to_id) {
            $stmt = $GLOBALS['db']->prepare("UPDATE email_messages SET status = 'replied' WHERE id = ?");
            $stmt->execute([$reply_to_id]);
        }
        
        return ['success' => true, 'message' => 'Email berhasil dikirim'];
    } catch (Exception $e) {
        return ['error' => 'Gagal mengirim email: ' . $mail->ErrorInfo];
    }
}

// ============================================================
// PROSES AJAX
// ============================================================
if (isset($_GET['action']) && $_GET['action'] == 'fetch') {
    $result = fetchEmails();
    echo json_encode($result);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'reply') {
    $to = $_POST['to'];
    $subject = $_POST['subject'];
    $message = $_POST['message'];
    $reply_id = $_POST['reply_id'] ?? null;
    
    $result = sendReply($to, $subject, $message, $reply_id);
    echo json_encode($result);
    exit();
}

// ============================================================
// AMBIL EMAIL DARI DATABASE
// ============================================================
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$limit = 20;
$offset = ($page - 1) * $limit;

$status_filter = isset($_GET['status']) ? $_GET['status'] : 'all';
$search = isset($_GET['search']) ? $_GET['search'] : '';

$where_conditions = ["is_incoming = 1"];
$params = [];

if ($status_filter != 'all') {
    $where_conditions[] = "status = ?";
    $params[] = $status_filter;
}

if ($search) {
    $where_conditions[] = "(subject LIKE ? OR sender LIKE ? OR message LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

$where_clause = "WHERE " . implode(" AND ", $where_conditions);

$countStmt = $db->prepare("SELECT COUNT(*) as total FROM email_messages $where_clause");
$countStmt->execute($params);
$totalEmails = $countStmt->fetch(PDO::FETCH_ASSOC)['total'];
$totalPages = ceil($totalEmails / $limit);

$query = "SELECT * FROM email_messages $where_clause ORDER BY created_at DESC LIMIT $offset, $limit";
$stmt = $db->prepare($query);
$stmt->execute($params);
$emails = $stmt->fetchAll(PDO::FETCH_ASSOC);

$unreadStmt = $db->prepare("SELECT COUNT(*) as unread FROM email_messages WHERE status = 'unread' AND is_incoming = 1");
$unreadStmt->execute();
$unreadCount = $unreadStmt->fetch(PDO::FETCH_ASSOC)['unread'];

$selected_email = null;
if (isset($_GET['id'])) {
    $detailStmt = $db->prepare("SELECT * FROM email_messages WHERE id = ?");
    $detailStmt->execute([$_GET['id']]);
    $selected_email = $detailStmt->fetch(PDO::FETCH_ASSOC);
    
    if ($selected_email && $selected_email['status'] == 'unread') {
        $updateStmt = $db->prepare("UPDATE email_messages SET status = 'read' WHERE id = ?");
        $updateStmt->execute([$_GET['id']]);
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Jago Hongkong - Email Management</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.1/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        #sidebar {
            width: 250px;
            background: linear-gradient(to bottom, #343a40, #2c3136);
            color: white;
            min-height: 100vh;
            padding-top: 1rem;
            transition: all 0.3s;
            box-shadow: 2px 0 10px rgba(0,0,0,0.1);
            position: fixed;
            left: 0;
            top: 0;
            height: 100%;
        }

        #sidebar a {
            color: rgba(255,255,255,0.8);
            display: block;
            padding: 12px 20px;
            text-decoration: none;
            transition: all 0.3s;
            border-left: 3px solid transparent;
        }

        #sidebar a:hover, #sidebar a.active {
            background: rgba(255,255,255,0.1);
            color: white;
            border-left: 3px solid #007bff;
        }

        #sidebar a i {
            width: 20px;
            margin-right: 10px;
            display: inline-block;
        }

        .badge-unread {
            background-color: #dc3545;
            color: white;
            float: right;
        }

        .email-list {
            max-height: 70vh;
            overflow-y: auto;
        }

        .email-item {
            padding: 12px 15px;
            border-bottom: 1px solid #e9ecef;
            cursor: pointer;
            transition: all 0.2s;
        }

        .email-item:hover {
            background-color: #f8f9fa;
        }

        .email-item.unread {
            background-color: #fff3cd;
            font-weight: 600;
        }

        .email-item .sender {
            font-weight: 600;
            color: #333;
        }

        .email-item .subject {
            color: #555;
        }

        .email-item .date {
            font-size: 0.8rem;
            color: #6c757d;
        }

        .email-detail {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            min-height: 500px;
        }

        .reply-box {
            margin-top: 20px;
            border-top: 1px solid #e9ecef;
            padding-top: 20px;
        }

        .btn-fetch {
            animation: pulse 2s infinite;
        }

        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.6; }
            100% { opacity: 1; }
        }

        .status-badge {
            font-size: 0.7rem;
            padding: 3px 8px;
        }
        
        .auto-fetch-notice {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 9999;
            animation: slideDown 0.5s ease;
        }
        
        @keyframes slideDown {
            from { transform: translateY(-100px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }
    </style>
</head>
<body>
    <!-- Sidebar -->
    <?php include 'navbar.php'; ?>

    <!-- Auto Fetch Notification -->
    <?php if ($autoFetchMessage): ?>
    <div class="auto-fetch-notice">
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle mr-2"></i>
            <?= $autoFetchMessage ?>
            <button type="button" class="close" data-dismiss="alert">&times;</button>
        </div>
    </div>
    <?php endif; ?>

    <!-- Main Content -->
    <div style="margin-left: 250px; padding: 20px;">
        <div class="dashboard-header mb-4">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h2><i class="fas fa-envelope mr-2"></i>Email Management</h2>
                    <p class="mb-0">Kelola email customer support</p>
                </div>
                <div>
                    <button class="btn btn-success btn-fetch" onclick="fetchEmails()">
                        <i class="fas fa-download mr-2"></i>Fetch New Emails
                    </button>
                    <button class="btn btn-primary ml-2" onclick="composeEmail()">
                        <i class="fas fa-plus mr-2"></i>Compose
                    </button>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Email List -->
            <div class="col-lg-5">
                <div class="card">
                    <div class="card-header bg-dark text-white d-flex justify-content-between align-items-center">
                        <span><i class="fas fa-inbox mr-2"></i>Inbox</span>
                        <span class="badge badge-light"><?= $totalEmails ?> emails</span>
                    </div>
                    <div class="card-body p-0">
                        <!-- Filter -->
                        <div class="p-3 border-bottom">
                            <form method="GET" class="form-inline">
                                <div class="form-group mr-2">
                                    <select name="status" class="form-control form-control-sm" onchange="this.form.submit()">
                                        <option value="all" <?= $status_filter == 'all' ? 'selected' : '' ?>>All</option>
                                        <option value="unread" <?= $status_filter == 'unread' ? 'selected' : '' ?>>Unread</option>
                                        <option value="read" <?= $status_filter == 'read' ? 'selected' : '' ?>>Read</option>
                                        <option value="replied" <?= $status_filter == 'replied' ? 'selected' : '' ?>>Replied</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <input type="text" name="search" class="form-control form-control-sm" placeholder="Search..." value="<?= htmlspecialchars($search) ?>">
                                </div>
                                <button type="submit" class="btn btn-sm btn-primary ml-2"><i class="fas fa-search"></i></button>
                            </form>
                        </div>
                        
                        <div class="email-list">
                            <?php if (count($emails) > 0): ?>
                                <?php foreach ($emails as $email): ?>
                                    <div class="email-item <?= $email['status'] == 'unread' ? 'unread' : '' ?>" 
                                         onclick="viewEmail(<?= $email['id'] ?>)">
                                        <div class="d-flex justify-content-between">
                                            <span class="sender"><?= htmlspecialchars($email['sender']) ?></span>
                                            <span class="date"><?= date('d M H:i', strtotime($email['created_at'])) ?></span>
                                        </div>
                                        <div class="subject"><?= htmlspecialchars($email['subject']) ?></div>
                                        <div class="d-flex justify-content-between mt-1">
                                            <span class="badge badge-secondary status-badge">
                                                <?= $email['status'] == 'unread' ? '🔴 Unread' : ($email['status'] == 'replied' ? '✅ Replied' : '📖 Read') ?>
                                            </span>
                                            <small class="text-muted"><?= strlen($email['message']) > 100 ? substr($email['message'], 0, 100) . '...' : $email['message'] ?></small>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <div class="text-center py-5 text-muted">
                                    <i class="fas fa-inbox fa-3x mb-3"></i>
                                    <p>Tidak ada email</p>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <!-- Pagination -->
                        <?php if ($totalPages > 1): ?>
                        <div class="p-3 border-top">
                            <nav>
                                <ul class="pagination pagination-sm mb-0 justify-content-center">
                                    <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                                        <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                                            <a class="page-link" href="?page=<?= $i ?>&status=<?= $status_filter ?>&search=<?= urlencode($search) ?>">
                                                <?= $i ?>
                                            </a>
                                        </li>
                                    <?php endfor; ?>
                                </ul>
                            </nav>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Email Detail -->
            <div class="col-lg-7">
                <div class="email-detail">
                    <?php if ($selected_email): ?>
                        <div class="d-flex justify-content-between align-items-start mb-3">
                            <div>
                                <h4><?= htmlspecialchars($selected_email['subject']) ?></h4>
                                <div class="text-muted">
                                    <strong>From:</strong> <?= htmlspecialchars($selected_email['sender']) ?>
                                </div>
                                <div class="text-muted">
                                    <strong>Received:</strong> <?= date('d F Y H:i', strtotime($selected_email['created_at'])) ?>
                                </div>
                            </div>
                            <span class="badge badge-<?= $selected_email['status'] == 'unread' ? 'danger' : ($selected_email['status'] == 'replied' ? 'success' : 'secondary') ?> p-2">
                                <?= strtoupper($selected_email['status']) ?>
                            </span>
                        </div>
                        <hr>
                        
                        <div class="email-body" style="white-space: pre-wrap; min-height: 200px; background: #f8f9fa; padding: 15px; border-radius: 8px;">
                            <?php 
                            $clean_message = $selected_email['message'];
                            $clean_message = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', $clean_message);
                            $clean_message = str_replace("\xEF\xBB\xBF", '', $clean_message);
                            
                            if (empty(trim($clean_message))) {
                                echo '<em class="text-muted">Tidak ada isi pesan</em>';
                            } else {
                                echo nl2br(htmlspecialchars($clean_message));
                            }
                            ?>
                        </div>
                        
                        <div class="reply-box">
                            <h6><i class="fas fa-reply mr-2"></i>Balas Email</h6>
                            <form id="replyForm" onsubmit="return sendReply(event)">
                                <input type="hidden" name="reply_id" value="<?= $selected_email['id'] ?>">
                                <input type="hidden" name="to" value="<?= htmlspecialchars($selected_email['sender']) ?>">
                                <div class="form-group">
                                    <label>Subject</label>
                                    <input type="text" class="form-control" name="subject" value="Re: <?= htmlspecialchars($selected_email['subject']) ?>" required>
                                </div>
                                <div class="form-group">
                                    <label>Message</label>
                                    <textarea class="form-control" name="message" rows="5" required></textarea>
                                </div>
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-paper-plane mr-2"></i>Send Reply
                                </button>
                                <button type="button" class="btn btn-danger ml-2" onclick="deleteEmail(<?= $selected_email['id'] ?>)">
                                    <i class="fas fa-trash mr-2"></i>Delete
                                </button>
                            </form>
                        </div>
                    <?php else: ?>
                        <div class="text-center text-muted py-5">
                            <i class="fas fa-envelope-open-text fa-3x mb-3"></i>
                            <p>Pilih email untuk melihat detail</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.4/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <script>
        function viewEmail(id) {
            window.location.href = 'email.php?id=' + id;
        }
        
        function fetchEmails() {
            Swal.fire({
                title: 'Fetching emails...',
                text: 'Menghubungi server email',
                allowOutsideClick: false,
                showConfirmButton: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            $.ajax({
                url: 'email.php?action=fetch',
                method: 'GET',
                success: function(response) {
                    Swal.close();
                    const data = JSON.parse(response);
                    if (data.success) {
                        Swal.fire('Success', data.success, 'success');
                        setTimeout(() => location.reload(), 1500);
                    } else if (data.error) {
                        Swal.fire('Error', data.error, 'error');
                    }
                },
                error: function() {
                    Swal.fire('Error', 'Gagal terhubung ke server', 'error');
                }
            });
        }
        
        function sendReply(e) {
            e.preventDefault();
            const form = document.getElementById('replyForm');
            const formData = new FormData(form);
            formData.append('action', 'reply');
            
            Swal.fire({
                title: 'Mengirim email...',
                text: 'Mohon tunggu',
                allowOutsideClick: false,
                showConfirmButton: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            $.ajax({
                url: 'email.php',
                method: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    Swal.close();
                    const data = JSON.parse(response);
                    if (data.success) {
                        Swal.fire('Success', data.success, 'success');
                        setTimeout(() => location.reload(), 1500);
                    } else if (data.error) {
                        Swal.fire('Error', data.error, 'error');
                    }
                },
                error: function() {
                    Swal.fire('Error', 'Gagal mengirim email', 'error');
                }
            });
        }
        
        function deleteEmail(id) {
            Swal.fire({
                title: 'Hapus Email?',
                text: "Email ini akan dihapus secara permanen!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'Ya, Hapus!',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: 'email.php',
                        method: 'POST',
                        data: { 
                            action: 'delete',
                            id: id 
                        },
                        success: function(response) {
                            const data = JSON.parse(response);
                            if (data.success) {
                                Swal.fire('Terhapus!', data.message, 'success');
                                setTimeout(() => location.reload(), 1000);
                            } else {
                                Swal.fire('Error', data.error, 'error');
                            }
                        },
                        error: function() {
                            Swal.fire('Error', 'Gagal menghapus email', 'error');
                        }
                    });
                }
            });
        }
        
        function composeEmail() {
            window.location.href = 'email_compose.php';
        }
        
        // ============================================================
        // AUTO REFRESH - CEK EMAIL BARU SETIAP 30 DETIK
        // ============================================================
        setInterval(function() {
            $.ajax({
                url: 'email.php?action=fetch',
                method: 'GET',
                success: function(response) {
                    const data = JSON.parse(response);
                    if (data.success && data.success.includes('email baru')) {
                        // Refresh halaman jika ada email baru
                        location.reload();
                    }
                }
            });
        }, 30000); // 30 detik
    </script>
</body>
</html>