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

$response = ["success" => false, "message" => "Critical error: Process failed."];

if (isset($_GET['id'])) {
    $id = intval($_GET['id']);

    // 1. Fetch the file path BEFORE deleting the record
    $query = "SELECT file_location, music_id, music_title FROM musics WHERE id = $id";
    $res = $conn->query($query);

    if ($res && $res->num_rows > 0) {
        $data = $res->fetch_assoc();
        $music_label = $data['music_id'];
        $title = $data['music_title'];
        $file_to_delete = "../" . $data['file_location'];

        // 2. Delete the physical audio file 
        if (!empty($data['file_location']) && file_exists($file_to_delete)) {
            @unlink($file_to_delete);
        }

        // 3. Delete the database record
        $delete = $conn->query("DELETE FROM musics WHERE id = $id");

        if ($delete) {
            $response = [
                "success" => true, 
                "message" => "Track '$title' ($music_label) and its file have been permanently removed."
            ];
        } else {
            $response = ["success" => false, "message" => "Database Error: " . $conn->error];
        }
    } else {
        $response = ["success" => false, "message" => "Error: Music track not found."];
    }
} else {
    $response = ["success" => false, "message" => "Invalid request: No ID provided."];
}

echo json_encode($response);
exit();