<?php
require_once 'auth_check.php';
require_once 'db.php';
session_start();

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

try {
    $db = getDB1Connection();
    $stmt = $db->prepare("SELECT config FROM email_configs WHERE user_id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$result) {
        throw new Exception('Email not configured');
    }

    $config = json_decode($result['config'], true);
    $password = decrypt($config['password']);

    $mailbox = setupMailbox($config, $password);
    $emails = fetchEmails($mailbox);

    echo json_encode(['success' => true, 'emails' => $emails]);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

function decrypt($data) {
    $key = getenv('ENCRYPTION_KEY');
    $data = base64_decode($data);
    $iv = substr($data, 0, 16);
    $encrypted = substr($data, 16);
    return openssl_decrypt($encrypted, 'AES-256-CBC', $key, 0, $iv);
}

function setupMailbox($config, $password) {
    switch($config['service']) {
        case 'gmail':
            $host = '{imap.gmail.com:993/imap/ssl}INBOX';
            break;
        case 'outlook':
            $host = '{outlook.office365.com:993/imap/ssl}INBOX';
            break;
        case 'yahoo':
            $host = '{imap.mail.yahoo.com:993/imap/ssl}INBOX';
            break;
        case 'custom':
            $host = sprintf('{%s:%d/imap/ssl}INBOX', $config['imap_server'], $config['imap_port']);
            break;
        default:
            throw new Exception('Invalid email service');
    }

    $mailbox = imap_open($host, $config['email'], $password);
    if (!$mailbox) {
        throw new Exception('Failed to connect to mailbox: ' . imap_last_error());
    }

    return $mailbox;
}

function fetchEmails($mailbox) {
    $emails = [];
    $messages = imap_search($mailbox, 'ALL');

    if ($messages) {
        rsort($messages);
        $messages = array_slice($messages, 0, 50);

        foreach ($messages as $msgNum) {
            $header = imap_headerinfo($mailbox, $msgNum);
            $structure = imap_fetchstructure($mailbox, $msgNum);
            $body = getEmailBody($mailbox, $msgNum, $structure);

            $emails[] = [
                'id' => $msgNum,
                'subject' => isset($header->subject) ? mb_decode_mimeheader($header->subject) : 'No Subject',
                'from' => isset($header->from[0]->mailbox, $header->from[0]->host) ? 
                         $header->from[0]->mailbox . '@' . $header->from[0]->host : 'Unknown',
                'date' => date('Y-m-d H:i:s', strtotime($header->date)),
                'preview' => mb_substr(strip_tags($body), 0, 200) . '...',
                'body' => $body
            ];
        }
    }

    imap_close($mailbox);
    return $emails;
}

function getEmailBody($mailbox, $msgNum, $structure) {
    if (!isset($structure->parts)) {
        $body = imap_body($mailbox, $msgNum);
        $encoding = $structure->encoding;
    } else {
        $body = getEmailPart($mailbox, $msgNum, $structure, 0);
    }

    switch ($encoding) {
        case 3:
            return base64_decode($body);
        case 4:
            return quoted_printable_decode($body);
        default:
            return $body;
    }
}

function getEmailPart($mailbox, $msgNum, $structure, $partNum) {
    $data = '';

    if ($structure->type == 1) {
        foreach ($structure->parts as $index => $subStruct) {
            $prefix = $partNum ? $partNum . '.' : '';
            $data .= getEmailPart($mailbox, $msgNum, $subStruct, $prefix . ($index + 1));
        }
    } elseif ($structure->type == 0 || $structure->type == 5) {
        $data = imap_fetchbody($mailbox, $msgNum, $partNum ?: 1);
    }

    return $data;
}