<?php 
session_start();
require_once 'config/auth_check.php';
require_once 'config/db.php';

// Generate unique Music ID (GVMU0001 format)
$res = $conn->query("SELECT MAX(id) as last_id FROM musics");
$row = $res->fetch_assoc();
$next_num = ($row['last_id'] ?? 0) + 1;
$music_id = "GVMU" . str_pad($next_num, 4, '0', STR_PAD_LEFT);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Visual Music Clipper | Grovia Admin</title>
    <script src="https://unpkg.com/wavesurfer.js@7/dist/wavesurfer.min.js"></script>
    <script src="https://unpkg.com/wavesurfer.js@7/dist/plugins/regions.min.js"></script>
    <style>
        :root { --sidebar-bg: #3b4368; --accent: #3498db; --bg: #f4f7f6; }
        body { margin: 0; font-family: 'Segoe UI', sans-serif; background: var(--bg); display: flex; }
        .sidebar { width: 280px; background: var(--sidebar-bg); height: 100vh; position: fixed; color: #fff; }
        .main-content { margin-left: 280px; width: 100%; padding: 40px; }
        .form-card { background: #fff; padding: 35px; border-radius: 12px; box-shadow: 0 10px 30px rgba(0,0,0,0.05); max-width: 850px; margin: auto; }
        
        label { display: block; margin-bottom: 8px; font-weight: 600; color: #444; font-size: 11px; text-transform: uppercase; }
        input, select { width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; margin-bottom: 20px; }
        
        /* Wavesurfer UI */
        #waveform-container { background: #1e1e2f; padding: 25px; border-radius: 12px; margin-bottom: 20px; display: none; }
        #waveform { width: 100%; height: 128px; }
        .trim-info-bar { display: flex; justify-content: space-between; background: rgba(255,255,255,0.05); padding: 10px 15px; border-radius: 8px; margin-top: 15px; border: 1px solid rgba(255,255,255,0.1); }
        .trim-stat { color: #fff; font-size: 13px; }
        .trim-stat span { color: var(--accent); font-weight: bold; font-family: monospace; }
        .controls { display: flex; gap: 15px; margin-top: 20px; align-items: center; }
        .play-btn { background: var(--accent); color: #fff; border: none; padding: 12px 25px; border-radius: 6px; cursor: pointer; font-weight: bold; }
        
        .btn-upload { background: #2ecc71; color: #fff; border: none; padding: 15px; border-radius: 6px; cursor: pointer; font-weight: bold; width: 100%; font-size: 16px; }
        .btn-upload:disabled { background: #95a5a6; cursor: not-allowed; }

        /* Response Overlay */
        #responseOverlay { display:none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.8); z-index: 9999; align-items: center; justify-content: center; }
        .modal-content { background: white; padding: 40px; border-radius: 15px; text-align: center; max-width: 400px; width: 90%; }
    </style>
</head>
<body>

<div class="sidebar">
    <div style="padding:30px; text-align:center;max-width:150px"><img src="assets/img/logo.png" style="width:inherit-webkit-fill-available !important" alt="GROVIA LOGO"></div>
    <a href="manage-musics.php" style="display:block; padding:18px 25px; color:#fff; text-decoration:none;">← Back to Library</a>
</div>

<div class="main-content">
    <div class="form-card">
        <h2 style="margin:0 0 25px 0;">Visual Audio Trimmer</h2>
        
        <form id="addMusicForm">
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                <div>
                    <label>Music ID</label>
                    <input type="text" name="music_id" value="<?php echo $music_id; ?>" readonly style="background:#f9f9f9; color:#7f8c8d;">
                </div>
                <div>
                    <label>Music Title</label>
                    <input type="text" name="music_title" placeholder="Enter song title..." required>
                </div>
            </div>

            <label>Upload Audio Track</label>
            <input type="file" id="musicInp" accept="audio/*" required>

            <div id="waveform-container">
                <div id="waveform"></div>
                <div class="trim-info-bar">
                    <div class="trim-stat">Start: <span id="displayStart">0.00s</span></div>
                    <div class="trim-stat">End: <span id="displayEnd">15.00s</span></div>
                    <div class="trim-stat">Clipped Length: <span id="displayLength">15.00s</span></div>
                </div>
                <div class="controls">
                    <button type="button" class="play-btn" id="playBtn">Play Selection</button>
                    <span style="color:rgba(255,255,255,0.5); font-size:12px;">Drag edges to trim (15s - 30s)</span>
                </div>
            </div>

            <input type="hidden" name="start_time" id="startTime" value="0">
            <input type="hidden" name="music_length" id="musicLength" value="15.00">

            <label>Status</label>
            <select name="status">
                <option value="Active">Active</option>
                <option value="Inactive">Inactive</option>
            </select>

            <button type="submit" class="btn-upload" id="submitBtn">Trim & Upload Track</button>
        </form>
    </div>
</div>

<div id="responseOverlay">
    <div class="modal-content">
        <div id="statusIcon" style="font-size: 50px; margin-bottom: 20px;"></div>
        <h3 id="statusTitle" style="margin:0; color:#333;"></h3>
        <p id="statusDesc" style="color:#666; margin: 10px 0 20px 0;"></p>
        <div id="redirectTimer" style="font-size:12px; color:#aaa;">Redirecting in <span id="timer">3</span> seconds...</div>
    </div>
</div>



<script>
let ws, wsRegions;

// 1. Initialize Wavesurfer and Region Selection
document.getElementById('musicInp').onchange = function(e) {
    const file = e.target.files[0];
    if (!file) return;

    document.getElementById('waveform-container').style.display = 'block';
    if(ws) ws.destroy();
    
    ws = WaveSurfer.create({
        container: '#waveform',
        waveColor: '#4b4b6b',
        progressColor: '#3498db',
        cursorColor: '#ffffff',
        height: 128,
        barWidth: 2
    });

    wsRegions = ws.registerPlugin(WaveSurfer.Regions.create());
    ws.load(URL.createObjectURL(file));

    ws.on('ready', () => {
        const region = wsRegions.addRegion({
            start: 0,
            end: 15,
            color: 'rgba(52, 152, 219, 0.3)',
            drag: true,
            resize: true,
        });
        updateData(region);
    });

    wsRegions.on('region-updated', (region) => {
        let duration = region.end - region.start;
        if (duration < 15) region.setOptions({ end: region.start + 15 });
        if (duration > 30) region.setOptions({ end: region.start + 30 });
        updateData(region);
    });
};

function updateData(region) {
    const duration = (region.end - region.start).toFixed(2);
    document.getElementById('startTime').value = region.start.toFixed(2);
    document.getElementById('musicLength').value = duration;
    document.getElementById('displayStart').innerText = region.start.toFixed(2) + "s";
    document.getElementById('displayEnd').innerText = region.end.toFixed(2) + "s";
    document.getElementById('displayLength').innerText = duration + "s";
}

document.getElementById('playBtn').onclick = () => {
    const region = Object.values(wsRegions.getRegions())[0];
    if (region) region.play();
};

// 2. Client-Side Clipping & Upload
document.getElementById('addMusicForm').onsubmit = async (e) => {
    e.preventDefault();
    const btn = document.getElementById('submitBtn');
    const overlay = document.getElementById('responseOverlay');
    const timerSpan = document.getElementById('timer');
    
    btn.innerText = "Processing Clip...";
    btn.disabled = true;

    const start = parseFloat(document.getElementById('startTime').value);
    const duration = parseFloat(document.getElementById('musicLength').value);
    const fileInp = document.getElementById('musicInp');

    try {
        const audioContext = new (window.AudioContext || window.webkitAudioContext)();
        const arrayBuffer = await fileInp.files[0].arrayBuffer();
        const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);

        // Create new clipped buffer
        const sampleRate = audioBuffer.sampleRate;
        const frameCount = duration * sampleRate;
        const clippedBuffer = audioContext.createBuffer(audioBuffer.numberOfChannels, frameCount, sampleRate);

        for (let i = 0; i < audioBuffer.numberOfChannels; i++) {
            const channelData = audioBuffer.getChannelData(i);
            const clippedData = clippedBuffer.getChannelData(i);
            const startOffset = Math.floor(start * sampleRate);
            for (let j = 0; j < frameCount; j++) {
                clippedData[j] = channelData[startOffset + j] || 0;
            }
        }

        // Convert to WAV Blob
        const clippedBlob = bufferToWav(clippedBuffer);
        const clippedFile = new File([clippedBlob], "clipped.wav", { type: "audio/wav" });

        const formData = new FormData(e.target);
        formData.set('music_file', clippedFile);

        const res = await fetch('api/save-music.php', { method: 'POST', body: formData });
        const data = await res.json();

        overlay.style.display = "flex";
        if(data.success) {
            document.getElementById('statusIcon').innerHTML = "✅";
            document.getElementById('statusTitle').innerText = "Clipped & Saved";
            document.getElementById('statusDesc').innerText = data.message;
            let count = 3;
            const interval = setInterval(() => {
                count--; timerSpan.innerText = count;
                if(count === 0) { clearInterval(interval); window.location.href = 'manage-musics.php'; }
            }, 1000);
        } else {
            document.getElementById('statusIcon').innerHTML = "❌";
            document.getElementById('statusTitle').innerText = "Error";
            document.getElementById('statusDesc').innerText = data.message;
            setTimeout(() => { overlay.style.display = "none"; btn.disabled = false; btn.innerText = "Trim & Upload Track"; }, 3000);
        }
    } catch (err) {
        alert("Audio processing failed.");
        btn.disabled = false;
    }
};

// 3. Helper: AudioBuffer to WAV
function bufferToWav(buffer) {
    let numOfChan = buffer.numberOfChannels, length = buffer.length * numOfChan * 2 + 44, bufferArr = new ArrayBuffer(length), view = new DataView(bufferArr), channels = [], i, sample, offset = 0, pos = 0;
    const setUint16 = (d) => { view.setUint16(pos, d, true); pos += 2; };
    const setUint32 = (d) => { view.setUint32(pos, d, true); pos += 4; };
    setUint32(0x46464952); setUint32(length - 8); setUint32(0x45564157); setUint32(0x20746d66); setUint32(16); setUint16(1); setUint16(numOfChan); setUint32(buffer.sampleRate); setUint32(buffer.sampleRate * 2 * numOfChan); setUint16(numOfChan * 2); setUint16(16); setUint32(0x61746164); setUint32(length - pos - 4);
    for(i = 0; i < numOfChan; i++) channels.push(buffer.getChannelData(i));
    while(pos < length) {
        for(i = 0; i < numOfChan; i++) {
            sample = Math.max(-1, Math.min(1, channels[i][offset]));
            sample = (sample < 0 ? sample * 0x8000 : sample * 0x7FFF);
            view.setInt16(pos, sample, true); pos += 2;
        }
        offset++;
    }
    return new Blob([bufferArr], {type: "audio/wav"});
}
</script>
</body>
</html>