<?php
require_once 'db/config.php';

$message = '';
$messageType = '';

// Handle File Upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['audio_file'])) {
    $file = $_FILES['audio_file'];
    $filename = 'sahur.mp3'; // Force the name as requested, or we could use $file['name']
    $targetDir = 'assets/audio/';
    
    if (!is_dir($targetDir)) {
        mkdir($targetDir, 0775, true);
    }

    $targetFile = $targetDir . $filename;
    $fileType = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

    // Basic validation
    if ($fileType != "mp3") {
        $message = "Maaf, hanya file MP3 yang diizinkan.";
        $messageType = "error";
    } elseif ($file['size'] > 5000000) { // 5MB limit
        $message = "File terlalu besar. Maksimal 5MB.";
        $messageType = "error";
    } else {
        if (move_uploaded_file($file['tmp_name'], $targetFile)) {
            // Update database record
            try {
                $stmt = db()->prepare("INSERT INTO audio_assets (filename, display_name) VALUES (?, ?) ON DUPLICATE KEY UPDATE updated_at = CURRENT_TIMESTAMP");
                $stmt->execute([$filename, 'Sahur Notification']);
                $message = "File $filename berhasil diunggah/diperbarui!";
                $messageType = "success";
            } catch (Exception $e) {
                $message = "Gagal menyimpan ke database: " . $e->getMessage();
                $messageType = "error";
            }
        } else {
            $message = "Terjadi kesalahan saat mengunggah file.";
            $messageType = "error";
        }
    }
}

// Fetch current assets
$assets = db()->query("SELECT * FROM audio_assets")->fetchAll();
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Audio Assets Manager - CMS</title>
    <style>
        :root {
            --primary: #007bff;
            --success: #28a745;
            --error: #dc3545;
            --bg: #f8f9fa;
            --card: #ffffff;
            --text: #333;
        }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: var(--bg);
            color: var(--text);
            margin: 0;
            padding: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
        }
        .container {
            background: var(--card);
            padding: 2rem;
            border-radius: 12px;
            box-shadow: 0 10px 25px rgba(0,0,0,0.05);
            max-width: 500px;
            width: 100%;
        }
        h1 { font-size: 1.5rem; margin-bottom: 1.5rem; text-align: center; }
        .alert {
            padding: 10px;
            border-radius: 6px;
            margin-bottom: 1rem;
            font-size: 0.9rem;
        }
        .alert-success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .alert-error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        
        .upload-zone {
            border: 2px dashed #ddd;
            padding: 2rem;
            text-align: center;
            border-radius: 8px;
            transition: border-color 0.3s;
            cursor: pointer;
        }
        .upload-zone:hover { border-color: var(--primary); }
        .file-input { display: none; }
        
        .btn {
            background: var(--primary);
            color: white;
            border: none;
            padding: 12px 20px;
            border-radius: 6px;
            width: 100%;
            font-weight: 600;
            cursor: pointer;
            margin-top: 1rem;
            transition: opacity 0.3s;
        }
        .btn:hover { opacity: 0.9; }
        
        .asset-list { margin-top: 2rem; }
        .asset-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px;
            background: #f1f3f5;
            border-radius: 6px;
            margin-bottom: 0.5rem;
        }
        .asset-info small { color: #666; display: block; }
        audio { width: 100%; margin-top: 10px; height: 35px; }
        .back-link { display: block; text-align: center; margin-top: 1rem; color: #666; text-decoration: none; font-size: 0.9rem; }
    </style>
</head>
<body>

<div class="container">
    <h1>Panel Audio Assets</h1>

    <?php if ($message): ?>
        <div class="alert alert-<?php echo $messageType; ?>">
            <?php echo $message; ?>
        </div>
    <?php endif; ?>

    <form action="" method="POST" enctype="multipart/form-data">
        <div class="upload-zone" onclick="document.getElementById('audio_file').click()">
            <p>Klik di sini untuk pilih file MP3 (sahur.mp3)</p>
            <input type="file" name="audio_file" id="audio_file" class="file-input" accept="audio/mpeg" required>
            <div id="file-name" style="margin-top: 10px; font-weight: bold; color: var(--primary);"></div>
        </div>
        <button type="submit" class="btn">Unggah & Perbarui</button>
    </form>

    <div class="asset-list">
        <h3>File Terdaftar:</h3>
        <?php foreach ($assets as $asset): ?>
            <div class="asset-item">
                <div class="asset-info">
                    <strong><?php echo htmlspecialchars($asset['display_name']); ?></strong>
                    <small>Nama file: <?php echo htmlspecialchars($asset['filename']); ?></small>
                    <small>Terakhir diupdate: <?php echo $asset['updated_at']; ?></small>
                </div>
            </div>
            <audio controls src="assets/audio/<?php echo $asset['filename']; ?>?v=<?php echo time(); ?>"></audio>
        <?php endforeach; ?>
    </div>

    <a href="index.php" class="back-link">&larr; Kembali ke Dashboard</a>
</div>

<script>
    document.getElementById('audio_file').onchange = function() {
        document.getElementById('file-name').textContent = this.files[0].name;
    };
</script>

</body>
</html>
