<?php
/**
 * ============================================================================
 * posts/toggle-like.php - Toggle Post Like API
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

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

if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'error' => 'Not authenticated']);
    exit();
}

$userId = getUserId();
$postId = isset($_POST['post_id']) ? (int)$_POST['post_id'] : 0;

if (!$postId) {
    echo json_encode(['success' => false, 'error' => 'Invalid post ID']);
    exit();
}

try {
    $database = new Database();
    $db = $database->getConnection();
    
    $postClass = new \App\Post($db);
    
    // Get current like status
    $post = $postClass->getPost($postId, $userId);
    
    if (!$post) {
        echo json_encode(['success' => false, 'error' => 'Post not found']);
        exit();
    }
    
    $liked = $post['user_liked'];
    
    // Toggle like
    if ($liked) {
        $result = $postClass->unlike($postId, $userId);
        $action = 'unliked';
    } else {
        $result = $postClass->like($postId, $userId);
        $action = 'liked';
    }
    
    if ($result !== false) {
        echo json_encode([
            'success' => true,
            'action' => $action,
            'liked' => !$liked
        ]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Failed to toggle like']);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
?>