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

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('Invalid request method');
    }

    $data = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($data['message_ids']) || !isset($data['destination'])) {
        throw new Exception('Missing required fields');
    }

    $mailbox = getMailboxConnection();
    $connection = $mailbox['connection'];
    
    $messageIds = (array)$data['message_ids'];
    $destination = $data['destination'];
    
    $baseFolder = '{' . $mailbox['config']['imap_host'] . ':' . $mailbox['config']['imap_port'] . '/imap/ssl}';
    
    switch ($destination) {
        case 'trash':
            $targetFolder = $baseFolder . 'Trash';
            break;
        case 'inbox':
            $targetFolder = $baseFolder . 'INBOX';
            break;
        case 'spam':
            $targetFolder = $baseFolder . 'Junk';
            break;
        default:
            throw new Exception('Invalid destination folder');
    }
    
    $movedCount = 0;
    foreach ($messageIds as $uid) {
        $headers = imap_fetchheader($connection, $uid, FT_UID);
        $body = imap_body($connection, $uid, FT_UID);
        
        if (imap_mail_move($connection, $uid, $targetFolder, FT_UID)) {
            $movedCount++;
        }
    }
    
    imap_expunge($connection);
    
    if ($movedCount > 0) {
        echo json_encode([
            'success' => true,
            'message' => $movedCount . ' message(s) moved successfully',
            'moved_count' => $movedCount
        ]);
    } else {
        throw new Exception('No messages were moved');
    }

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

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