<?php
$formats = Database::fetchAll("SELECT * FROM video_formats ORDER BY is_active DESC, sort_order ASC, id ASC");
$ic = 'w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none';
?>

<div class="space-y-4">

    <form method="POST" action="/admin/settings" class="flex items-center gap-4 mb-2 bg-white rounded-lg shadow-sm border border-gray-200 px-5 py-3.5">
        <?= Router::csrfField() ?>
        <input type="hidden" name="_tab" value="transcode">
        <input type="hidden" name="_sub" value="formats">
        <label class="text-sm font-medium text-gray-700 shrink-0">Trim start</label>
        <input type="number" name="transcode_trim_start" value="<?= (int)Setting::get('transcode_trim_start', '0') ?>" min="0" max="300" class="<?= $ic ?>" style="width:80px">
        <span class="text-xs text-gray-400 shrink-0">seconds</span>
        <span class="text-xs text-gray-300 hidden sm:inline">—</span>
        <span class="text-xs text-gray-400 hidden sm:inline">Removes the first X seconds from every video. 0 = disabled.</span>
        <button type="submit" class="px-3 py-2 bg-primary-600 text-white text-sm font-medium rounded-lg hover:bg-primary-700 transition-colors shrink-0 ml-auto">Save</button>
    </form>

    <div class="flex items-center justify-between">
        <p class="text-sm text-gray-500">Output formats generated from source files. All options (trim, watermark) are applied to every format including the source resolution.</p>
        <button type="button" onclick="openFormatModal(0)" class="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-primary-600 bg-primary-50 rounded-lg hover:bg-primary-100 transition-colors shrink-0">
            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15"/></svg>
            Add Format
        </button>
    </div>

    <?php foreach ($formats as $f): ?>
    <div class="bg-white rounded-lg shadow-sm border border-gray-200">
        <div class="px-5 py-3.5 flex items-center justify-between">
            <div class="flex items-center gap-3 min-w-0">
                <div class="w-9 h-9 rounded-lg flex items-center justify-center shrink-0 <?= $f['is_active'] ? 'bg-primary-50 text-primary-600' : 'bg-gray-100 text-gray-400' ?>">
                    <i class="fa-solid fa-film"></i>
                </div>
                <div class="min-w-0">
                    <div class="flex items-center gap-2">
                        <span class="text-sm font-semibold text-gray-900"><?= htmlspecialchars($f['name']) ?></span>
                        <code class="text-[10px] bg-gray-100 px-1.5 py-0.5 rounded text-gray-500"><?= htmlspecialchars($f['postfix']) ?></code>
                        <?php if (!$f['is_active']): ?>
                        <span class="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium bg-gray-100 text-gray-500">Inactive</span>
                        <?php endif; ?>
                        <?php if ($f['is_source']): ?>
                        <span class="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium bg-blue-100 text-blue-700">Source</span>
                        <?php endif; ?>
                    </div>
                    <div class="text-xs text-gray-400 mt-0.5">
                        <?= $f['width'] ?>x<?= $f['height'] ?><?= $f['keep_aspect'] ? ' (keep aspect)' : '' ?>
                    </div>
                </div>
            </div>
            <div class="flex items-center gap-2 shrink-0">
                <button type="button" onclick="toggleFormat(<?= (int)$f['id'] ?>, <?= $f['is_active'] ? 'false' : 'true' ?>, this)" class="relative inline-flex h-5 w-9 items-center rounded-full transition-colors <?= $f['is_active'] ? 'bg-primary-600' : 'bg-gray-300' ?>" title="<?= $f['is_active'] ? 'Disable' : 'Enable' ?>">
                    <span class="inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform shadow-sm <?= $f['is_active'] ? 'translate-x-4' : 'translate-x-0.5' ?>"></span>
                </button>
                <button type="button" onclick="openFormatModal(<?= (int)$f['id'] ?>)" class="px-2.5 py-1.5 text-xs font-medium text-gray-600 bg-gray-100 rounded-md hover:bg-gray-200 transition-colors">Edit</button>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<div id="formatModal" class="hidden fixed inset-0 z-50 flex items-center justify-center p-4" onclick="if(event.target===this)document.getElementById('formatModal').classList.add('hidden')">
    <div class="fixed inset-0 bg-black/50"></div>
    <div class="relative bg-white rounded-xl shadow-2xl w-full max-w-lg max-h-[90vh] overflow-y-auto" onclick="event.stopPropagation()">
        <div class="px-5 py-4 border-b border-gray-200 flex items-center justify-between">
            <h3 id="fmTitle" class="text-sm font-semibold text-gray-900">Add Format</h3>
            <button type="button" onclick="document.getElementById('formatModal').classList.add('hidden')" class="text-gray-400 hover:text-gray-600 text-xl leading-none" style="background:none;border:none;cursor:pointer">&times;</button>
        </div>
        <div class="p-5 space-y-4">
            <input type="hidden" id="fmId" value="0">

            <div><label class="block text-sm font-medium text-gray-700 mb-1">Name</label><input type="text" id="fmName" class="<?= $ic ?>" placeholder="MP4 720p"></div>

            <div class="grid grid-cols-2 gap-3">
                <div><label class="block text-sm font-medium text-gray-700 mb-1">File postfix</label><input type="text" id="fmPostfix" class="<?= $ic ?>" placeholder="_720p.mp4"><p class="mt-1 text-xs text-gray-400">e.g. _720p.mp4, _480p.mp4</p></div>
                <div><label class="block text-sm font-medium text-gray-700 mb-1">Resolution</label>
                    <div class="flex gap-2 items-center">
                        <input type="number" id="fmWidth" class="<?= $ic ?>" placeholder="1280" style="width:80px">
                        <span class="text-gray-400">x</span>
                        <input type="number" id="fmHeight" class="<?= $ic ?>" placeholder="720" style="width:80px">
                    </div>
                </div>
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">FFmpeg options</label>
                <textarea id="fmFfmpeg" rows="3" class="<?= $ic ?> font-mono text-xs" placeholder="-vcodec libx264 -movflags +faststart -crf 23 -preset medium -acodec aac -ar 44100 -ab 128k -f mp4"></textarea>
                <p class="mt-1 text-xs text-gray-400">Custom FFmpeg encoding parameters. <a href="https://ffmpeg.org/ffmpeg.html" target="_blank" class="text-primary-600 hover:underline">FFmpeg documentation</a></p>
            </div>

            <div class="grid grid-cols-2 gap-3">
                <label class="flex items-center gap-2.5 text-sm text-gray-700 cursor-pointer">
                    <input type="checkbox" id="fmActive" checked class="rounded border-gray-300 text-primary-600 focus:ring-primary-500">
                    Active
                </label>
                <label class="flex items-center gap-2.5 text-sm text-gray-700 cursor-pointer">
                    <input type="checkbox" id="fmAspect" checked class="rounded border-gray-300 text-primary-600 focus:ring-primary-500">
                    Keep aspect ratio
                </label>
            </div>
        </div>
        <div class="px-5 py-4 border-t border-gray-200 flex items-center justify-between">
            <button type="button" id="fmDeleteBtn" onclick="deleteFormat()" class="text-xs text-red-500 hover:text-red-700 hidden">Delete format</button>
            <div class="flex gap-2 ml-auto">
                <button type="button" onclick="document.getElementById('formatModal').classList.add('hidden')" class="px-3 py-2 bg-white text-gray-700 text-sm font-medium rounded-lg border border-gray-300 hover:bg-gray-50">Cancel</button>
                <button type="button" onclick="saveFormat()" class="px-4 py-2 bg-primary-600 text-white text-sm font-medium rounded-lg hover:bg-primary-700">Save</button>
            </div>
        </div>
    </div>
</div>

<script>
var _csrf='<?= Router::csrfToken() ?>';
var _formats=<?= json_encode(array_map(fn($f)=>['id'=>(int)$f['id'],'name'=>$f['name'],'postfix'=>$f['postfix'],'width'=>(int)$f['width'],'height'=>(int)$f['height'],'keep_aspect'=>(bool)$f['keep_aspect'],'ffmpeg_options'=>$f['ffmpeg_options'],'is_active'=>(bool)$f['is_active'],'is_source'=>(bool)$f['is_source']], $formats)) ?>;

function openFormatModal(id){
    var f=_formats.find(x=>x.id===id);
    document.getElementById('fmTitle').textContent=f?'Edit Format':'New Format';
    document.getElementById('fmId').value=id;
    document.getElementById('fmName').value=f?f.name:'';
    document.getElementById('fmPostfix').value=f?f.postfix:'';
    document.getElementById('fmWidth').value=f?f.width:'';
    document.getElementById('fmHeight').value=f?f.height:'';
    document.getElementById('fmFfmpeg').value=f?f.ffmpeg_options:'-vcodec libx264 -movflags +faststart -crf 23 -preset medium -acodec aac -ar 44100 -ab 128k -f mp4';
    document.getElementById('fmActive').checked=f?f.is_active:true;
    document.getElementById('fmAspect').checked=f?f.keep_aspect:true;
    document.getElementById('fmDeleteBtn').classList.toggle('hidden',!f);
    document.getElementById('formatModal').classList.remove('hidden');
}

function toggleFormat(id, active, btn){
    fetch('/admin/settings/format/save',{method:'POST',headers:{'Content-Type':'application/json','X-CSRF-Token':_csrf},body:JSON.stringify({csrf_token:_csrf,id:id,is_active:active,_toggle:true}),credentials:'same-origin'}).then(r=>r.json()).then(d=>{if(d.success)location.reload();else alert(d.error)});
}

function saveFormat(){
    var body={id:parseInt(document.getElementById('fmId').value),name:document.getElementById('fmName').value,postfix:document.getElementById('fmPostfix').value,width:parseInt(document.getElementById('fmWidth').value)||0,height:parseInt(document.getElementById('fmHeight').value)||0,ffmpeg_options:document.getElementById('fmFfmpeg').value,is_active:document.getElementById('fmActive').checked,keep_aspect:document.getElementById('fmAspect').checked};
    fetch('/admin/settings/format/save',{method:'POST',headers:{'Content-Type':'application/json','X-CSRF-Token':_csrf},body:JSON.stringify(Object.assign({csrf_token:_csrf},body)),credentials:'same-origin'}).then(r=>r.json()).then(d=>{if(d.success)location.reload();else alert(d.error)});
}

function deleteFormat(){
    if(!confirm('Delete this format?'))return;
    fetch('/admin/settings/format/delete',{method:'POST',headers:{'Content-Type':'application/json','X-CSRF-Token':_csrf},body:JSON.stringify({csrf_token:_csrf,id:parseInt(document.getElementById('fmId').value)}),credentials:'same-origin'}).then(r=>r.json()).then(d=>{if(d.success)location.reload();else alert(d.error)});
}
</script>
