<?php
header('Content-Type: application/json; charset=utf-8');

ini_set('display_errors', 0);
error_reporting(E_ALL);

require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/db.php';
require_once dirname(__DIR__) . '/includes/functions.php';

$songId = isset($_POST['song_id']) ? (int)$_POST['song_id'] : 0;
if ($songId <= 0 && isset($_POST['id'])) {
    $songId = (int)$_POST['id'];
}

if ($songId <= 0) {
    jsonResponse(['success' => false, 'message' => '유효하지 않은 곡 ID입니다.'], 400);
    exit;
}

try {
    $pdo = getDBConnection();

    $checkStmt = $pdo->prepare("SELECT id FROM songs WHERE id = :id AND is_missing = 0");
    $checkStmt->execute([':id' => $songId]);
    if (!$checkStmt->fetch()) {
        jsonResponse(['success' => false, 'message' => '존재하지 않거나 유실된 곡입니다.'], 404);
        exit;
    }

    $updateStmt = $pdo->prepare("UPDATE songs SET play_count = play_count + 1 WHERE id = :id");
    $updateStmt->execute([':id' => $songId]);

    if (settingBool('player_history_enabled', true)) {
        $historyStmt = $pdo->prepare("INSERT INTO play_history (song_id, played_at) VALUES (:song_id, CURRENT_TIMESTAMP)");
        $historyStmt->execute([':song_id' => $songId]);
    }

    jsonResponse([
        'success' => true,
        'message' => '재생 횟수와 히스토리를 기록했습니다.',
    ]);
} catch (Throwable $e) {
    if (function_exists('writeAppLog')) {
        writeAppLog('error', 'play_count_error', 'Play count update failed', ['song_id' => $songId, 'error' => $e->getMessage()]);
    }
    jsonResponse(['success' => false, 'message' => '재생 기록을 저장하지 못했습니다.'], 500);
}
