<?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) ?: [];
$fileId = (int)($data['file_id'] ?? 0);
$userId = (int)$_SESSION['user_id'];

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

$stmt = $pdo->prepare("SELECT id, type FROM files WHERE id = :id AND is_active = 1 LIMIT 1");
$stmt->execute([':id' => $fileId]);
$file = $stmt->fetch();
if (!$file) { echo json_encode(['ok'=>false,'error'=>'File not found']); exit; }

$pdo->prepare("
  INSERT INTO file_sessions (user_id, file_id, opened_at)
  VALUES (:user_id, :file_id, NOW())
")->execute([':user_id'=>$userId, ':file_id'=>$fileId]);

$sessionId = (int)$pdo->lastInsertId();

$pdo->prepare("
  INSERT INTO file_stats (user_id, file_id, open_count, play_count, last_opened_at)
  VALUES (:user_id, :file_id, 1, 0, NOW())
  ON DUPLICATE KEY UPDATE
    open_count = open_count + 1,
    last_opened_at = NOW()
")->execute([':user_id'=>$userId, ':file_id'=>$fileId]);

echo json_encode(['ok'=>true,'session_id'=>$sessionId]);
