<?php
require_once '../db.php';
require_once 'connect.php';
session_start();

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

try {
    if (!isset($_GET['uid'])) {
        throw new Exception('Message UID is required');
    }

    $mailbox = getMailboxConnection();
    $connection = $mailbox['connection'];
    
    $uid = $_GET['uid'];
    
    // Récupérer les entêtes du message
    $headers = imap_fetchheader($connection, $uid, FT_UID);
    $overview = imap_fetch_overview($connection, $uid, FT_UID)[0];
    $structure = imap_fetchstructure($connection, $uid, FT_UID);
    
    // Fonction pour décoder les entêtes
    function decode_header($header) {
        $elements = imap_mime_header_decode($header);
        $text = '';
        foreach ($elements as $element) {
            $text .= $element->text;
        }
        return $text;
    }
    
    // Fonction pour obtenir le corps du message
    function get_message_body($connection, $uid, $structure) {
        $body = '';
        
        if ($structure->type == 0) {
            // Message texte simple
            $body = imap_fetchbody($connection, $uid, '1', FT_UID);
            
            // Décodage selon l'encodage
            if ($structure->encoding == 3) {
                $body = base64_decode($body);
            } elseif ($structure->encoding == 4) {
                $body = quoted_printable_decode($body);
            }
            
            // Conversion en UTF-8 si nécessaire
            if (isset($structure->parameters)) {
                foreach ($structure->parameters as $param) {
                    if (strtolower($param->attribute) == 'charset' && strtolower($param->value) != 'utf-8') {
                        $body = mb_convert_encoding($body, 'UTF-8', $param->value);
                    }
                }
            }
        } elseif ($structure->type == 1) {
            // Message multipart
            foreach ($structure->parts as $part_number => $part) {
                if ($part->type == 0) {
                    $body = imap_fetchbody($connection, $uid, ($part_number + 1), FT_UID);
                    
                    if ($part->encoding == 3) {
                        $body = base64_decode($body);
                    } elseif ($part->encoding == 4) {
                        $body = quoted_printable_decode($body);
                    }
                    
                    if ($part->subtype == 'HTML') {
                        break;
                    }
                }
            }
        }
        
        return $body;
    }
    
    // Récupérer les pièces jointes
    $attachments = [];
    if (isset($structure->parts)) {
        foreach ($structure->parts as $part_number => $part) {
            if ($part->ifdisposition && strtolower($part->disposition) == 'attachment') {
                $filename = '';
                if (isset($part->dparameters[0])) {
                    $filename = $part->dparameters[0]->value;
                } elseif (isset($part->parameters[0])) {
                    $filename = $part->parameters[0]->value;
                }
                
                $attachments[] = [
                    'name' => decode_header($filename),
                    'part' => $part_number + 1,
                    'size' => $part->bytes
                ];
            }
        }
    }
    
    $message = [
        'uid' => $uid,
        'subject' => decode_header($overview->subject),
        'from' => decode_header($overview->from),
        'to' => decode_header($overview->to),
        'date' => $overview->date,
        'body' => get_message_body($connection, $uid, $structure),
        'attachments' => $attachments,
        'seen' => $overview->seen,
        'flagged' => $overview->flagged
    ];
    
    if (isset($overview->cc)) {
        $message['cc'] = decode_header($overview->cc);
    }
    
    // Marquer comme lu
    imap_setflag_full($connection, $uid, "\\Seen", FT_UID);
    
    echo json_encode([
        'success' => true,
        'message' => $message
    ]);

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

if (isset($connection)) {
    imap_close($connection);
}