<?php
/**
 * ============================================================================
 * stories/create.php - Create 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();
$content = isset($_POST['content']) ? trim($_POST['content']) : null;
$mediaType = 'text';

try {
    $database = new Database();
    $db = $database->getConnection();
    
    $storyClass = new \App\Story($db);
    
    $mediaUrl = null;
    
    // Handle media upload (single file per request)
    if (isset($_FILES['media']) && $_FILES['media']['error'] === UPLOAD_ERR_OK) {
        $uploadDir = __DIR__ . '/../assets/uploads/stories/';
        if (!file_exists($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }
        
        $fileType = $_FILES['media']['type'];
        $allowedTypes = [
            'image/jpeg', 'image/png', 'image/gif', 'image/webp',
            'video/mp4', 'video/quicktime', 'video/x-msvideo'
        ];
        
        if (!in_array($fileType, $allowedTypes)) {
            echo json_encode(['success' => false, 'error' => 'Invalid file type']);
            exit();
        }
        
        $maxSize = 50 * 1024 * 1024; // 50MB for videos, will check later
        if ($_FILES['media']['size'] > $maxSize) {
            echo json_encode(['success' => false, 'error' => 'File too large']);
            exit();
        }
        
        // Determine media type
        if (strpos($fileType, 'image') !== false) {
            $mediaType = 'image';
        } elseif (strpos($fileType, 'video') !== false) {
            $mediaType = 'video';
        }
        
        $extension = pathinfo($_FILES['media']['name'], PATHINFO_EXTENSION);
        $filename = uniqid('story_') . '_' . time() . '.' . $extension;
        $uploadPath = $uploadDir . $filename;
        
        if (move_uploaded_file($_FILES['media']['tmp_name'], $uploadPath)) {
            // Store relative path, not full URL
            $mediaUrl = 'assets/uploads/stories/' . $filename;
        } else {
            echo json_encode(['success' => false, 'error' => 'Failed to upload file']);
            exit();
        }
    }
    
    // Validate that we have either media or content
    if (!$mediaUrl && !$content) {
        echo json_encode(['success' => false, 'error' => 'Story must have media or text content']);
        exit();
    }
    
    // Create story
    $storyId = $storyClass->create($userId, $mediaType, $mediaUrl, $content);
    
    if ($storyId) {
        echo json_encode([
            'success' => true,
            'story_id' => $storyId,
            'message' => 'Story created successfully'
        ]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Failed to create story']);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
?>