<?php
header('Content-Type: application/json');

// Matikan error HTML agar response JSON tidak rusak
error_reporting(0);

$response = [
    'success' => false,
    'message' => 'Tidak ada file yang diunggah.',
    'audio' => null,
    'image' => null
];

// Direktori tujuan
$audioDir = __DIR__ . '/assets/music/';
$imageDir = __DIR__ . '/assets/images/';

// Buat direktori jika belum ada
if (!file_exists($audioDir)) { mkdir($audioDir, 0755, true); }
if (!file_exists($imageDir)) { mkdir($imageDir, 0755, true); }

$hasUpload = false;

// Cek apakah post_max_size terlampaui (jika konten POST lebih besar dari limit, $_POST dan $_FILES akan kosong)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && empty($_POST) && empty($_FILES) && isset($_SERVER['CONTENT_LENGTH']) && (int)$_SERVER['CONTENT_LENGTH'] > 0) {
    $response['success'] = false;
    $response['message'] = 'Ukuran file terlalu besar! Melebihi batas maksimal server (post_max_size).';
    echo json_encode($response);
    exit;
}

// Helper function to get upload error message
function getUploadErrorMessage($code) {
    switch ($code) {
        case UPLOAD_ERR_INI_SIZE: return 'Ukuran file melebihi batas upload_max_filesize di php.ini.';
        case UPLOAD_ERR_FORM_SIZE: return 'Ukuran file melebihi batas MAX_FILE_SIZE form.';
        case UPLOAD_ERR_PARTIAL: return 'File hanya terupload sebagian.';
        case UPLOAD_ERR_NO_FILE: return 'Tidak ada file yang diunggah.';
        case UPLOAD_ERR_NO_TMP_DIR: return 'Folder temporary tidak ditemukan di server.';
        case UPLOAD_ERR_CANT_WRITE: return 'Gagal menulis file ke disk server.';
        case UPLOAD_ERR_EXTENSION: return 'Upload dihentikan oleh ekstensi PHP.';
        default: return 'Terjadi error yang tidak diketahui.';
    }
}

// Proses Upload Audio
if (isset($_FILES['audio'])) {
    if ($_FILES['audio']['error'] === UPLOAD_ERR_OK) {
        $audioFile = $_FILES['audio'];
        $ext = strtolower(pathinfo($audioFile['name'], PATHINFO_EXTENSION));
        
        $allowedAudio = ['mp3', 'wav', 'ogg', 'm4a'];
        if (in_array($ext, $allowedAudio)) {
            // Bersihkan nama file (hapus spasi menjadi underscore atau biarkan, lebih baik url encode/biarkan karena lokal)
            $filename = basename($audioFile['name']);
            $target = $audioDir . $filename;
            
            if (move_uploaded_file($audioFile['tmp_name'], $target)) {
                $response['audio'] = 'assets/music/' . $filename;
                $hasUpload = true;
            } else {
                $response['message'] = 'Gagal menyimpan file audio ke folder server.';
                echo json_encode($response);
                exit;
            }
        } else {
            $response['message'] = 'Format file audio tidak diizinkan. Hanya MP3/WAV/OGG.';
            echo json_encode($response);
            exit;
        }
    } else if ($_FILES['audio']['error'] !== UPLOAD_ERR_NO_FILE) {
        $response['message'] = 'Error Audio: ' . getUploadErrorMessage($_FILES['audio']['error']);
        echo json_encode($response);
        exit;
    }
}

// Proses Upload Gambar (Opsional)
if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
    $imgFile = $_FILES['image'];
    $ext = strtolower(pathinfo($imgFile['name'], PATHINFO_EXTENSION));
    
    $allowedImage = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
    if (in_array($ext, $allowedImage)) {
        $filename = basename($imgFile['name']);
        $target = $imageDir . $filename;
        
        if (move_uploaded_file($imgFile['tmp_name'], $target)) {
            $response['image'] = 'assets/images/' . $filename;
            $hasUpload = true;
        } else {
            $response['message'] = 'Gagal menyimpan file gambar ke server.';
            echo json_encode($response);
            exit;
        }
    } else {
        $response['message'] = 'Format file gambar tidak diizinkan. Hanya JPG/PNG/WEBP.';
        echo json_encode($response);
        exit;
    }
}

if ($hasUpload || (isset($_POST['is_edit']) && $_POST['is_edit'] === 'true')) {
    // Berhasil (jika ada file diupload ATAU hanya mode edit teks)
    $response['success'] = true;
    $response['message'] = 'Data berhasil disimpan.';
} else if (empty($_FILES)) {
     // Jika tidak ada file fisik tapi form dikirim (bisa terjadi jika file sudah ada sebelumnya)
     $response['success'] = true;
     $response['message'] = 'Tidak ada file baru yang diunggah.';
}

echo json_encode($response);
?>
