<?php
header("Content-Type: application/json");
require_once '../config/db.php';

$music_id = $_POST['music_id'];
$music_title = $_POST['music_title'];
$length = $_POST['music_length'];
$status = $_POST['status'];

$file_path = "";
if (isset($_FILES['music_file']) && $_FILES['music_file']['error'] == 0) {
    $upload_dir = "../uploads/musics/";
    if (!is_dir($upload_dir)) { mkdir($upload_dir, 0777, true); }

    $filename = "music_" . time() . ".mp3";
    if (move_uploaded_file($_FILES['music_file']['tmp_name'], $upload_dir . $filename)) {
        $file_path = "uploads/musics/" . $filename;
    }
}

if ($file_path != "") {
    $sql = "INSERT INTO musics (music_id, music_title, file_location, music_length, status) VALUES (?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("sssss", $music_id, $music_title, $file_path, $length, $status);

    if ($stmt->execute()) {
        // Return Success JSON
        echo json_encode(["success" => true, "message" => "Track $music_title has been clipped and saved."]);
    } else {
        echo json_encode(["success" => false, "message" => "Database Error: " . $conn->error]);
    }
} else {
    echo json_encode(["success" => false, "message" => "File could not be saved to server."]);
}