<?php
require_once 'connect.php';
header('Content-Type: application/json');

try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (!isset($_FILES['attachment'])) {
            throw new Exception('No file uploaded');
        }

        $file = $_FILES['attachment'];
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf', 
                        'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                        'text/plain', 'application/zip'];
        
        if (!in_array($file['type'], $allowedTypes)) {
            throw new Exception('File type not allowed');
        }

        if ($file['size'] > 10485760) { // 10MB
            throw new Exception('File size too large');
        }

        $uploadDir = '../uploads/attachments/';
        if (!file_exists($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        $filename = uniqid() . '_' . basename($file['name']);
        $uploadPath = $uploadDir . $filename;

        if (move_uploaded_file($file['tmp_name'], $uploadPath)) {
            echo json_encode([
                'success' => true,
                'file' => [
                    'name' => $file['name'],
                    'type' => $file['type'],
                    'size' => $file['size'],
                    'path' => $filename
                ]
            ]);
        } else {
            throw new Exception('Failed to save file');
        }
    } else if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        if (!isset($_GET['uid']) || !isset($_GET['part'])) {
            throw new Exception('Missing parameters');
        }

        $mailbox = getMailboxConnection();
        $connection = $mailbox['connection'];

        $uid = $_GET['uid'];
        $part = $_GET['part'];

        $structure = imap_fetchstructure($connection, $uid, FT_UID);
        if (!isset($structure->parts[$part - 1])) {
            throw new Exception('Attachment not found');
        }

        $attachment = imap_fetchbody($connection, $uid, $part, FT_UID);
        if ($structure->parts[$part - 1]->encoding == 3) {
            $attachment = base64_decode($attachment);
        } else if ($structure->parts[$part - 1]->encoding == 4) {
            $attachment = quoted_printable_decode($attachment);
        }

        $filename = '';
        if (isset($structure->parts[$part - 1]->parameters)) {
            foreach ($structure->parts[$part - 1]->parameters as $param) {
                if (strtolower($param->attribute) == 'name') {
                    $filename = $param->value;
                }
            }
        }

        if (empty($filename) && isset($structure->parts[$part - 1]->dparameters)) {
            foreach ($structure->parts[$part - 1]->dparameters as $param) {
                if (strtolower($param->attribute) == 'filename') {
                    $filename = $param->value;
                }
            }
        }

        if (empty($filename)) {
            $filename = 'attachment_' . $uid . '_' . $part;
        }

        header('Content-Type: ' . $structure->parts[$part - 1]->subtype);
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Content-Length: ' . strlen($attachment));
        header('Cache-Control: no-cache, must-revalidate');
        header('Pragma: no-cache');
        
        echo $attachment;
        exit;
    } else {
        throw new Exception('Invalid request method');
    }

} catch (Exception $e) {
    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        header('Content-Type: application/json');
    }
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

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