<?php
require_once '../includes/init.php';

if (!isAuthenticated()) {
    jsonResponse(false, 'Not authenticated');
}

$data = json_decode(file_get_contents('php://input'), true);
$messageId = intval($data['message_id'] ?? 0);
$forAll = filter_var($data['for_all'] ?? false, FILTER_VALIDATE_BOOLEAN);

if (!$messageId) {
    jsonResponse(false, 'Invalid message');
}

$db = getDB();
$currentUserId = $_SESSION['user_id'];

// Verify message ownership
$stmt = $db->prepare("SELECT sender_id, receiver_id FROM messages WHERE id = ?");
$stmt->execute([$messageId]);
$message = $stmt->fetch();

if (!$message) {
    jsonResponse(false, 'Message not found');
}

if ($forAll && $message['sender_id'] == $currentUserId) {
    // Delete for all (only sender can do this, and only within time limit)
    $stmt = $db->prepare("
        UPDATE messages 
        SET is_deleted_for_all = 1, deleted_at = NOW()
        WHERE id = ? AND sender_id = ? 
        AND created_at > DATE_SUB(NOW(), INTERVAL 1 HOUR)
    ");
    $stmt->execute([$messageId, $currentUserId]);
} else {
    // Delete for me only
    if ($message['sender_id'] == $currentUserId) {
        $stmt = $db->prepare("UPDATE messages SET deleted_by_sender = 1 WHERE id = ?");
    } else {
        $stmt = $db->prepare("UPDATE messages SET deleted_by_receiver = 1 WHERE id = ?");
    }
    $stmt->execute([$messageId]);
}

jsonResponse(true, 'Message deleted');
?>
