<?php
require_once 'connect.php';

try {
    $folder = isset($_GET['folder']) ? $_GET['folder'] : 'INBOX';
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $perPage = 50;
    
    $mailbox = getMailboxConnection();
    $connection = $mailbox['connection'];
    
    switch($folder) {
        case 'sent':
            $mailboxName = '{' . $mailbox['config']['imap_host'] . ':' . $mailbox['config']['imap_port'] . '/imap/ssl}Sent';
            break;
        case 'drafts':
            $mailboxName = '{' . $mailbox['config']['imap_host'] . ':' . $mailbox['config']['imap_port'] . '/imap/ssl}Drafts';
            break;
        case 'trash':
            $mailboxName = '{' . $mailbox['config']['imap_host'] . ':' . $mailbox['config']['imap_port'] . '/imap/ssl}Trash';
            break;
        default:
            $mailboxName = '{' . $mailbox['config']['imap_host'] . ':' . $mailbox['config']['imap_port'] . '/imap/ssl}INBOX';
    }
    
    imap_reopen($connection, $mailboxName);
    
    $total = imap_num_msg($connection);
    $start = max(1, min($total, ($page - 1) * $perPage + 1));
    $end = min($total, $start + $perPage - 1);
    
    $messages = [];
    for ($i = $end; $i >= $start; $i--) {
        $header = imap_headerinfo($connection, $i);
        $structure = imap_fetchstructure($connection, $i);
        
        $hasAttachments = false;
        if (isset($structure->parts)) {
            foreach ($structure->parts as $part) {
                if ($part->ifdisposition && strtolower($part->disposition) == 'attachment') {
                    $hasAttachments = true;
                    break;
                }
            }
        }
        
        $from = isset($header->from[0]) ? ($header->from[0]->personal ?? $header->from[0]->mailbox . '@' . $header->from[0]->host) : 'Unknown';
        
        $messages[] = [
            'id' => $i,
            'uid' => imap_uid($connection, $i),
            'subject' => isset($header->subject) ? imap_utf8($header->subject) : 'No Subject',
            'from' => $from,
            'date' => date('Y-m-d H:i:s', strtotime($header->date)),
            'seen' => trim($header->Unseen) != 'U',
            'hasAttachments' => $hasAttachments,
            'size' => $structure->bytes
        ];
    }
    
    $response = [
        'success' => true,
        'messages' => $messages,
        'pagination' => [
            'total' => $total,
            'page' => $page,
            'perPage' => $perPage,
            'totalPages' => ceil($total / $perPage)
        ]
    ];
    
} catch (Exception $e) {
    $response = [
        'success' => false,
        'error' => $e->getMessage()
    ];
}

header('Content-Type: application/json');
echo json_encode($response);
imap_close($connection);