<?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['action'])) {
        throw new Exception('Missing required fields');
    }

    $mailbox = getMailboxConnection();
    $connection = $mailbox['connection'];
    
    $messageIds = (array)$data['message_ids'];
    $action = $data['action'];
    
    $successCount = 0;
    foreach ($messageIds as $uid) {
        switch ($action) {
            case 'read':
                if (imap_clearflag_full($connection, $uid, "\\Seen", FT_UID)) {
                    $successCount++;
                }
                break;
                
            case 'unread':
                if (imap_clearflag_full($connection, $uid, "\\Seen", FT_UID)) {
                    $successCount++;
                }
                break;
                
            case 'flag':
                if (imap_setflag_full($connection, $uid, "\\Flagged", FT_UID)) {
                    $successCount++;
                }
                break;
                
            case 'unflag':
                if (imap_clearflag_full($connection, $uid, "\\Flagged", FT_UID)) {
                    $successCount++;
                }
                break;
                
            default:
                throw new Exception('Invalid action specified');
        }
    }
    
    if ($successCount > 0) {
        $actionText = $action === 'read' ? 'marked as read' : 
                     ($action === 'unread' ? 'marked as unread' : 
                     ($action === 'flag' ? 'flagged' : 'unflagged'));
                     
        echo json_encode([
            'success' => true,
            'message' => $successCount . ' message(s) ' . $actionText . ' successfully',
            'affected_count' => $successCount
        ]);
    } else {
        throw new Exception('No messages were updated');
    }

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

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