<?php
$storages = Database::fetchAll("SELECT s.*, (SELECT COUNT(*) FROM videos WHERE storage_id = s.id) as video_count FROM media_storages s ORDER BY s.is_default DESC, s.sort_order, s.id");
$driverIcons = ['local' => 'fa-server', 'ftp' => 'fa-folder-open', 's3' => 'fa-cloud', 'webdav' => 'fa-network-wired'];
$driverLabels = ['local' => 'Local', 'ftp' => 'FTP', 's3' => 'S3', 'webdav' => 'WebDAV'];
$legacyCount = Database::count('videos', 'storage_id IS NULL AND video_folder IS NOT NULL');
$totalVideos = 0;
$totalDisk = 0;
$totalUsed = 0;
foreach ($storages as $s) {
    $totalVideos += (int)$s['video_count'];
    $du = MediaStorage::liveDiskUsage($s);
    $totalDisk += $du['disk_total'];
    $totalUsed += $du['disk_used'];
}
$globalPct = $totalDisk > 0 ? round($totalUsed / $totalDisk * 100) : 0;
?>

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

    
    <div class="grid grid-cols-3 gap-3">
        <div class="bg-white rounded-lg border border-gray-200 p-3">
            <div class="text-lg font-bold text-gray-900"><?= count($storages) ?></div>
            <div class="text-[11px] text-gray-500">Storage<?= count($storages) > 1 ? 's' : '' ?></div>
        </div>
        <div class="bg-white rounded-lg border border-gray-200 p-3">
            <div class="text-lg font-bold text-gray-900"><?= number_format($totalVideos) ?></div>
            <div class="text-[11px] text-gray-500">Total videos</div>
        </div>
        <div class="bg-white rounded-lg border border-gray-200 p-3">
            <?php if ($totalDisk > 0): ?>
            <div class="text-lg font-bold text-gray-900"><?= $globalPct ?>%</div>
            <div class="text-[11px] text-gray-500"><?= Format::fileSize($totalUsed) ?> / <?= Format::fileSize($totalDisk) ?></div>
            <?php else: ?>
            <div class="text-lg font-bold text-gray-400">&mdash;</div>
            <div class="text-[11px] text-gray-500">Disk usage</div>
            <?php endif; ?>
        </div>
    </div>

    <?php
    $defaultStorage = null;
    foreach ($storages as $s) { if ($s['is_default']) { $defaultStorage = $s; break; } }
    $defaultRemote = $defaultStorage && ($defaultStorage['driver'] ?? 'local') !== 'local';
    $scratchCount = count(glob(APP_ROOT . '/public/uploads/videos/*', GLOB_ONLYDIR) ?: []);
    $transcodeOn = class_exists('TranscodeManager') && TranscodeManager::isEnabled();
    ?>
    <?php if ($defaultRemote): ?>
    
    <div class="flex items-start gap-2.5 p-3 bg-green-50 rounded-lg border border-green-200">
        <i class="fa-solid fa-cloud-arrow-up text-green-500 mt-0.5 text-sm"></i>
        <div class="text-xs text-green-800 leading-relaxed min-w-0">
            <strong>External storage active.</strong> New media is uploaded to <strong><?= htmlspecialchars($defaultStorage['name']) ?></strong> and the local copy on this server is deleted automatically once it&rsquo;s on the CDN<?= $transcodeOn ? ' (after transcoding)' : '' ?> &mdash; nothing accumulates on the app server.
            <?php if ($scratchCount > 0): ?>
            <span class="text-green-600">&middot; <?= number_format($scratchCount) ?> item<?= $scratchCount !== 1 ? 's' : '' ?> currently uploading/transcoding.</span>
            <?php else: ?>
            <span class="text-green-600">&middot; local scratch is empty.</span>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>

    
    <div class="flex items-center justify-between gap-3">
        <p class="text-sm text-gray-500">New files go to the default storage. Auto-switches when disk threshold is reached.</p>
        <a href="/admin/storage/create" 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 Storage
        </a>
    </div>

    
    <?php foreach ($storages as $s):
        $id = (int)$s['id'];
        $vc = (int)$s['video_count'];
        $hs = $s['health_status'] ?? 'unknown';
        $hm = $s['health_message'] ?? '';
        $du = MediaStorage::liveDiskUsage($s);
        $diskTotal = $du['disk_total'];
        $diskUsed = $du['disk_used'];
        $diskPct = $diskTotal > 0 ? round($diskUsed / $diskTotal * 100) : 0;
        $diskColor = $diskPct >= 90 ? 'bg-red-500' : ($diskPct >= 70 ? 'bg-amber-500' : 'bg-green-500');
        $isDisabled = ($s['status'] ?? 'active') === 'disabled';
        $hasError = $hs === 'error';
        $cardBorder = $hasError ? 'border-red-300' : ($isDisabled ? 'border-gray-300' : 'border-gray-200');
        $cardBg = $hasError ? 'bg-red-50/40' : ($isDisabled ? 'bg-gray-50' : 'bg-white');
        $iconCls = $s['is_default'] ? 'bg-primary-100 text-primary-600' : ($hasError ? 'bg-red-100 text-red-500' : 'bg-gray-100 text-gray-400');
    ?>
    <div class="rounded-lg shadow-sm border <?= $cardBorder ?> <?= $cardBg ?>">
        <div class="px-4 sm:px-5 py-4 flex items-center gap-3 sm:gap-4">
            
            <div class="w-10 h-10 rounded-xl flex items-center justify-center shrink-0 <?= $iconCls ?>">
                <i class="fa-solid <?= $driverIcons[$s['driver']] ?? 'fa-server' ?>" style="font-size:14px"></i>
            </div>

            
            <div class="min-w-0 flex-1">
                <div class="flex items-center gap-2 flex-wrap">
                    <span class="text-sm font-semibold text-gray-900"><?= htmlspecialchars($s['name']) ?></span>
                    <span class="px-1.5 py-0.5 rounded text-[10px] font-medium bg-gray-100 text-gray-500"><?= $driverLabels[$s['driver']] ?? $s['driver'] ?></span>
                    <?php if ($s['is_default']): ?><span class="px-1.5 py-0.5 rounded text-[10px] font-medium bg-green-100 text-green-700">Default</span><?php endif; ?>
                    <?php if (($s['status'] ?? 'active') === 'readonly'): ?><span class="px-1.5 py-0.5 rounded text-[10px] font-medium bg-amber-100 text-amber-700">Read-only</span><?php endif; ?>
                    <?php if ($isDisabled): ?><span class="px-1.5 py-0.5 rounded text-[10px] font-medium bg-gray-200 text-gray-500">Disabled</span><?php endif; ?>
                    <?php if (!empty($s['secure_urls'])): ?><span class="px-1.5 py-0.5 rounded text-[10px] font-medium bg-blue-100 text-blue-700"><i class="fa-solid fa-shield-halved" style="font-size:7px"></i></span><?php endif; ?>
                </div>
                <div class="flex items-center gap-3 mt-1 text-xs text-gray-400 flex-wrap">
                    <span><?= number_format($vc) ?> video<?= $vc !== 1 ? 's' : '' ?></span>
                    <?php if ($diskTotal > 0): ?>
                    <span class="flex items-center gap-1.5">
                        <span class="w-16 h-1.5 bg-gray-200 rounded-full overflow-hidden"><span class="block h-full <?= $diskColor ?> rounded-full" style="width:<?= $diskPct ?>%"></span></span>
                        <?= $diskPct ?>% <span class="text-[10px] text-gray-300">(<?= Format::fileSize($diskUsed) ?> / <?= Format::fileSize($diskTotal) ?>)</span>
                    </span>
                    <?php endif; ?>
                    <?php if ($hasError): ?>
                    <span class="text-red-500 text-[10px]"><i class="fa-solid fa-circle-exclamation" style="font-size:8px"></i> <?= htmlspecialchars($hm) ?></span>
                    <?php endif; ?>
                </div>
            </div>

            
            <div class="flex items-center gap-0.5 shrink-0">
                <?php if (!$s['is_default']): ?>
                <button type="button" onclick="stSetDefault(<?= $id ?>)" title="Set as default" class="w-8 h-8 flex items-center justify-center rounded-lg text-gray-400 hover:text-amber-500 hover:bg-amber-50 transition-colors"><i class="fa-solid fa-star" style="font-size:12px"></i></button>
                <button type="button" onclick="stToggle(<?= $id ?>)" title="<?= $isDisabled ? 'Enable' : 'Disable' ?>" class="w-8 h-8 flex items-center justify-center rounded-lg <?= $isDisabled ? 'text-gray-400 hover:text-green-600 hover:bg-green-50' : 'text-green-600 hover:text-gray-500 hover:bg-gray-100' ?> transition-colors"><i class="fa-solid fa-power-off" style="font-size:12px"></i></button>
                <?php endif; ?>
                <a href="/admin/storage/<?= $id ?>/edit" title="Edit" class="w-8 h-8 flex items-center justify-center rounded-lg text-gray-400 hover:text-primary-600 hover:bg-primary-50 transition-colors no-underline"><i class="fa-solid fa-pen" style="font-size:11px"></i></a>
                <?php if (!$s['is_default'] && $vc === 0): ?>
                <button type="button" onclick="stDelete(<?= $id ?>)" title="Delete storage" class="w-8 h-8 flex items-center justify-center rounded-lg text-gray-400 hover:text-red-600 hover:bg-red-50 transition-colors"><i class="fa-solid fa-trash" style="font-size:11px"></i></button>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <?php endforeach; ?>

    <?php if ($legacyCount > 0): ?>
    <div class="flex items-start gap-2 p-3 bg-amber-50 rounded-lg border border-amber-200">
        <i class="fa-solid fa-lightbulb text-amber-400 mt-0.5 text-xs"></i>
        <p class="text-xs text-amber-700"><strong><?= number_format($legacyCount) ?></strong> video<?= $legacyCount > 1 ? 's' : '' ?> not assigned to any storage.</p>
    </div>
    <?php endif; ?>

</div>

<script>
(function () {
    var _csrf = '<?= Router::csrfToken() ?>';
    function _post(url, body) {
        return fetch(url, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': _csrf },
            body: JSON.stringify(Object.assign({ csrf_token: _csrf }, body)),
            credentials: 'same-origin'
        }).then(function (r) { return r.json(); });
    }
    window.stSetDefault = function (id) {
        _post('/admin/settings/storage/default', { id: id }).then(function (r) {
            if (r.success) location.reload(); else alert(r.error || 'Error');
        });
    };
    window.stToggle = function (id) {
        _post('/admin/settings/storage/toggle-status', { id: id }).then(function (r) {
            if (r.success) location.reload(); else alert(r.error || 'Error');
        });
    };
    window.stDelete = function (id) {
        if (!confirm('Delete this storage? This cannot be undone.')) return;
        _post('/admin/settings/storage/delete', { id: id }).then(function (r) {
            if (r.success) location.reload(); else alert(r.error || 'Error');
        });
    };
})();
</script>
