<?php
declare(strict_types=1);

require __DIR__ . '/../auth.php';
require __DIR__ . '/../db.php';

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

$data = json_decode(file_get_contents('php://input'), true) ?: [];
$sessionId = (int)($data['session_id'] ?? 0);
$pagesRead = max(0, (int)($data['pages_read'] ?? 0));
$watchedSeconds = max(0, (int)($data['watched_seconds'] ?? 0));
$userId = (int)$_SESSION['user_id'];

if ($sessionId <= 0) { echo json_encode(['ok'=>false,'error'=>'Invalid session_id']); exit; }

$stmt = $pdo->prepare("SELECT id FROM file_sessions WHERE id = :id AND user_id = :user_id LIMIT 1");
$stmt->execute([':id'=>$sessionId, ':user_id'=>$userId]);
if (!$stmt->fetch()) { echo json_encode(['ok'=>false,'error'=>'Forbidden']); exit; }

$pdo->prepare("
  UPDATE file_sessions
  SET pages_read = GREATEST(pages_read, :pages_read),
      watched_seconds = GREATEST(watched_seconds, :watched_seconds)
  WHERE id = :id
")->execute([
  ':pages_read'=>$pagesRead,
  ':watched_seconds'=>$watchedSeconds,
  ':id'=>$sessionId
]);

echo json_encode(['ok'=>true]);
