<?php
/*******************************************************************************************************************
| Video Progress Tracking API
| Handles watch progress updates for resume functionality
|*******************************************************************************************************************/

define('_ISVALID', true);

// Include core configuration
include_once '../../f_core/config.core.php';

// Set JSON response headers
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

try {
    // Only allow POST requests
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        sendError('Method not allowed', 405);
    }
    
    // Get current user
    $userId = VSession::isLoggedIn() ? $_SESSION['user_id'] : null;
    
    if (!$userId) {
        sendError('User must be logged in', 401);
    }
    
    // Get JSON input
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);
    
    if (json_last_error() !== JSON_ERROR_NONE) {
        sendError('Invalid JSON input', 400);
    }
    
    // Validate required fields
    $requiredFields = ['video_key', 'current_time', 'duration'];
    foreach ($requiredFields as $field) {
        if (!isset($data[$field])) {
            sendError("Missing required field: {$field}", 400);
        }
    }
    
    // Validate CSRF token
    if (!VSecurity::validateCSRFToken('video_progress', $data['csrf_token'] ?? '')) {
        sendError('Invalid CSRF token', 403);
    }
    
    $videoKey = $data['video_key'];
    $currentTime = (float)$data['current_time'];
    $duration = (float)$data['duration'];
    
    // Validate data
    if ($currentTime < 0 || $duration <= 0 || $currentTime > $duration) {
        sendError('Invalid time values', 400);
    }
    
    // Initialize streaming system
    $streaming = new VStreaming();
    
    // Update watch progress
    $streaming->updateWatchProgress($videoKey, $userId, $currentTime, $duration);
    
    sendSuccess([
        'message' => 'Progress updated successfully',
        'video_key' => $videoKey,
        'current_time' => $currentTime,
        'duration' => $duration,
        'watch_percentage' => ($duration > 0) ? ($currentTime / $duration) * 100 : 0
    ]);
    
} catch (Exception $e) {
    VLogger::getInstance()->error('Video progress API error', [
        'error' => $e->getMessage(),
        'trace' => $e->getTraceAsString()
    ]);
    
    sendError('Internal server error', 500);
}

/**
 * Send success response
 */
function sendSuccess($data, $code = 200)
{
    http_response_code($code);
    echo json_encode([
        'success' => true,
        'data' => $data,
        'timestamp' => time()
    ]);
    exit();
}

/**
 * Send error response
 */
function sendError($message, $code = 400)
{
    http_response_code($code);
    echo json_encode([
        'success' => false,
        'error' => $message,
        'timestamp' => time()
    ]);
    exit();
}
?>