<?php
/**
 * ============================================================================
 * stories/view.php - View Story 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();
$storyId = isset($_POST['story_id']) ? (int)$_POST['story_id'] : 0;

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

try {
    $database = new Database();
    $db = $database->getConnection();
    
    $storyClass = new \App\Story($db);
    
    // Get story
    $story = $storyClass->getStory($storyId);
    
    if (!$story) {
        echo json_encode(['success' => false, 'error' => 'Story not found or expired']);
        exit();
    }
    
    // Mark as viewed (if not own story)
    if ($story['user_id'] != $userId) {
        $storyClass->markAsViewed($storyId, $userId);
    }
    
    echo json_encode([
        'success' => true,
        'story' => $story
    ]);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
?>