<?php
/**
 * ============================================================================
 * posts/toggle-pin.php - Toggle Post Pin Status 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);
    
    // Verify post ownership
    $post = $postClass->getPost($postId, $userId);
    
    if (!$post) {
        echo json_encode(['success' => false, 'error' => 'Post not found']);
        exit();
    }
    
    if ($post['user_id'] != $userId) {
        echo json_encode(['success' => false, 'error' => 'Unauthorized']);
        exit();
    }
    
    // Toggle pin
    $result = $postClass->togglePin($postId, $userId);
    
    if ($result) {
        echo json_encode([
            'success' => true,
            'pinned' => !$post['is_pinned'],
            'message' => $post['is_pinned'] ? 'Post unpinned' : 'Post pinned'
        ]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Failed to toggle pin']);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
?>