<?php
// AJAX actions: toggle star, delete, mark read/unread
require_once __DIR__ . '/auth.php';
requireLogin();

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

$action = $_POST['action'] ?? '';
$id = (int)($_POST['id'] ?? 0);

try {
    $db = getDB();

    switch ($action) {
        case 'toggle_star':
            $stmt = $db->prepare("UPDATE messages SET is_starred = NOT is_starred WHERE id = ?");
            $stmt->execute([$id]);
            $stmt = $db->prepare("SELECT is_starred FROM messages WHERE id = ?");
            $stmt->execute([$id]);
            $starred = $stmt->fetchColumn();
            echo json_encode(['success' => true, 'starred' => (bool)$starred]);
            break;

        case 'mark_read':
            $db->prepare("UPDATE messages SET is_read = 1 WHERE id = ?")->execute([$id]);
            echo json_encode(['success' => true]);
            break;

        case 'mark_unread':
            $db->prepare("UPDATE messages SET is_read = 0 WHERE id = ?")->execute([$id]);
            echo json_encode(['success' => true]);
            break;

        case 'delete':
            $db->prepare("DELETE FROM messages WHERE id = ?")->execute([$id]);
            echo json_encode(['success' => true]);
            break;

        default:
            echo json_encode(['success' => false, 'error' => 'Unknown action']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
