<?php
/**
 * Colex AI - Pin / Unpin Conversation Endpoint
 *
 * POST /api/colex/pin-conversation
 * Body: { "conversation_id": "...", "pinned": true|false }
 */

// Ensure this file is accessed through the router
if (!isset($auth) || !isset($db)) {
    http_response_code(500);
    die(json_encode(['error' => 'Direct access not permitted.']));
}

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

// Ensure user is authenticated
if (!$auth->isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

$userId = $auth->getUserId();

$input = json_decode(file_get_contents('php://input'), true);
$conversationId = isset($input['conversation_id']) ? $input['conversation_id'] : null;
$pinned = isset($input['pinned']) ? (int)(bool)$input['pinned'] : null;

if (empty($conversationId) || $pinned === null) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing conversation_id or pinned']);
    exit;
}

try {
    // Verify ownership before updating
    $conversation = $db->raw("
        SELECT id
        FROM colex_conversations
        WHERE id = ? AND user_id = ?
    ", [$conversationId, $userId]);

    if (empty($conversation)) {
        http_response_code(404);
        echo json_encode(['error' => 'Not found']);
        exit;
    }

    $db->raw("
        UPDATE colex_conversations
        SET is_pinned = ?
        WHERE id = ? AND user_id = ?
    ", [$pinned, $conversationId, $userId]);

    echo json_encode(['success' => true, 'is_pinned' => (bool)$pinned]);

} catch (Exception $e) {
    error_log("Error updating pin status: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'Failed to update pin status']);
}
