<?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 fs.file_id, f.type, fs.closed_at
  FROM file_sessions fs
  JOIN files f ON f.id = fs.file_id
  WHERE fs.id = :id AND fs.user_id = :user_id
  LIMIT 1
");
$stmt->execute([':id'=>$sessionId, ':user_id'=>$userId]);
$row = $stmt->fetch();
if (!$row) { echo json_encode(['ok'=>false,'error'=>'Forbidden']); exit; }

$pdo->prepare("
  UPDATE file_sessions
  SET closed_at = COALESCE(closed_at, NOW()),
      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
]);

// For MP4: count 1 play per session (if you want 'play' button counts, add api/log_play.php)
if ($row['type'] === 'mp4') {
  $pdo->prepare("
    INSERT INTO file_stats (user_id, file_id, open_count, play_count, last_opened_at)
    VALUES (:user_id, :file_id, 0, 1, NOW())
    ON DUPLICATE KEY UPDATE play_count = play_count + 1
  ")->execute([':user_id'=>$userId, ':file_id'=>(int)$row['file_id']]);
}

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