<?php
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/auth.php';
requireAdmin();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: index.php');
    exit;
}
requireCsrfToken();

$pdo = getDBConnection();
$songId = isset($_POST['id']) ? intval($_POST['id']) : 0;
$title = trim((string)($_POST['title'] ?? ''));
$artist = trim((string)($_POST['artist'] ?? ''));
$album = trim((string)($_POST['album'] ?? ''));
$albumArtist = trim((string)($_POST['album_artist'] ?? ''));
$genre = trim((string)($_POST['genre'] ?? ''));
$year = trim((string)($_POST['year'] ?? ''));
$trackNoRaw = trim((string)($_POST['track_no'] ?? ''));
$trackNo = $trackNoRaw === '' ? null : max(0, intval($trackNoRaw));
$discNoRaw = trim((string)($_POST['disc_no'] ?? ''));
$discNo = $discNoRaw === '' ? null : max(0, intval($discNoRaw));
$composer = trim((string)($_POST['composer'] ?? ''));
$comment = trim((string)($_POST['comment'] ?? ''));

if ($songId <= 0 || $title === '') {
    header('Location: song.php?id=' . max(0, $songId));
    exit;
}

$stmt = $pdo->prepare("
    UPDATE songs
    SET title = :title,
        artist = :artist,
        album = :album,
        album_artist = :album_artist,
        genre = :genre,
        year = :year,
        track_no = :track_no,
        disc_no = :disc_no,
        composer = :composer,
        comment = :comment,
        is_manual_edited = 1,
        metadata_source = 'manual',
        metadata_updated_at = NOW(),
        updated_at = NOW()
    WHERE id = :id
");
$stmt->execute([
    ':title' => $title,
    ':artist' => $artist === '' ? null : $artist,
    ':album' => $album === '' ? null : $album,
    ':album_artist' => $albumArtist === '' ? null : $albumArtist,
    ':genre' => $genre === '' ? null : $genre,
    ':year' => $year === '' ? null : $year,
    ':track_no' => $trackNo,
    ':disc_no' => $discNo,
    ':composer' => $composer === '' ? null : $composer,
    ':comment' => $comment === '' ? null : $comment,
    ':id' => $songId,
]);

if (function_exists('writeAppLog')) {
    writeAppLog('info', 'metadata_manual_update', 'Metadata manually updated', [
        'song_id' => $songId,
        'fields' => ['title', 'artist', 'album', 'album_artist', 'genre', 'year', 'track_no', 'disc_no', 'composer', 'comment'],
    ]);
}

header('Location: song.php?id=' . $songId);
exit;
