@extends('layouts.app')
@section('title', 'System Backups')

@section('content')
@php
    $formatBytes = function (int $bytes): string {
        if ($bytes <= 0) return '0 B';
        $units = ['B', 'KB', 'MB', 'GB', 'TB'];
        $power = min((int) floor(log($bytes, 1024)), count($units) - 1);
        return number_format($bytes / (1024 ** $power), $power === 0 ? 0 : 2).' '.$units[$power];
    };
@endphp

<x-ui.page-toolbar
    title="System Backups"
    description="Create protected database and file backups, download recovery copies and remove old archives."
    :breadcrumbs="[['label'=>'Dashboard','url'=>route('dashboard')],['label'=>'Administration'],['label'=>'System Backups']]"
/>

<div class="space-y-5">
    <div class="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
        <div class="mf-card mf-card-body">
            <div class="text-xs text-muted-foreground">Stored backups</div>
            <div class="mt-1 text-xl font-semibold">{{ number_format($summary['count']) }}</div>
        </div>
        <div class="mf-card mf-card-body">
            <div class="text-xs text-muted-foreground">Backup storage used</div>
            <div class="mt-1 text-xl font-semibold">{{ $formatBytes($summary['total_size']) }}</div>
        </div>
        <div class="mf-card mf-card-body">
            <div class="text-xs text-muted-foreground">Latest backup</div>
            <div class="mt-1 text-sm font-semibold">
                {{ $summary['latest'] ? \Carbon\CarbonImmutable::createFromTimestamp($summary['latest']['created_at'])->format('d M Y H:i') : 'No backups yet' }}
            </div>
        </div>
        <div class="mf-card mf-card-body">
            <div class="text-xs text-muted-foreground">Disk space available</div>
            <div class="mt-1 text-xl font-semibold">{{ $formatBytes($summary['free_space']) }}</div>
        </div>
    </div>

    @if(!$summary['directory_writable'])
        <div class="mf-alert mf-alert-danger">The protected backup directory is not writable. Backup creation will fail until server permissions are corrected.</div>
    @endif

    <div class="grid gap-5 xl:grid-cols-[minmax(0,1fr)_360px]">
        <section class="mf-card">
            <div class="mf-card-body border-b border-border">
                <h2 class="text-sm font-semibold">Create system backup</h2>
                <p class="mt-1 text-xs text-muted-foreground">Backups are stored outside the public web directory. Environment secrets are intentionally not included.</p>
            </div>

            <form method="POST" action="{{ route('admin.system-backups.store') }}" class="mf-card-body space-y-4">
                @csrf

                <div class="grid gap-3 md:grid-cols-2">
                    <label class="mf-option w-full items-start">
                        <input type="radio" name="type" value="database" checked>
                        <span>
                            <span class="block font-medium">Database backup</span>
                            <span class="mt-0.5 block text-xs text-muted-foreground">Creates a compressed SQL recovery copy of the current database. Best for frequent backups.</span>
                        </span>
                    </label>

                    <label class="mf-option w-full items-start {{ $summary['archive_supported'] ? '' : 'opacity-60' }}">
                        <input type="radio" name="type" value="full" @disabled(!$summary['archive_supported'])>
                        <span>
                            <span class="block font-medium">Full system data backup</span>
                            <span class="mt-0.5 block text-xs text-muted-foreground">Includes the database plus private and public files stored under storage/app.</span>
                        </span>
                    </label>
                </div>

                @if(!$summary['archive_supported'])
                    <p class="mf-field-help">Full backups require the PHP Phar and zlib extensions. Database-only backups are still available.</p>
                @endif

                <div class="rounded-md border border-border bg-muted/20 p-3 text-xs text-muted-foreground">
                    <div class="font-medium text-foreground">Backup scope</div>
                    <div class="mt-1">Database backups contain schema and data. Full backups additionally include uploaded documents and files from protected/public application storage. Source code is managed through GitHub and is not duplicated inside system backups.</div>
                </div>

                <div class="flex justify-end">
                    <button class="mf-btn mf-btn-primary" type="submit" @disabled(!$summary['directory_writable'])>Create backup</button>
                </div>
            </form>
        </section>

        <section class="mf-card">
            <div class="mf-card-body border-b border-border">
                <h2 class="text-sm font-semibold">Retention cleanup</h2>
                <p class="mt-1 text-xs text-muted-foreground">Remove old local backup archives while keeping recent recovery copies.</p>
            </div>
            <form method="POST" action="{{ route('admin.system-backups.prune') }}" class="mf-card-body space-y-3" onsubmit="return confirm('Delete all system backups older than the selected number of days?');">
                @csrf
                <div>
                    <label class="mf-field-label" for="backup-retention-days">Delete backups older than</label>
                    <div class="flex items-center gap-2">
                        <input id="backup-retention-days" class="mf-input" type="number" min="1" max="3650" name="days" value="{{ old('days', 30) }}" required>
                        <span class="shrink-0 text-xs text-muted-foreground">days</span>
                    </div>
                </div>
                <button class="mf-btn w-full" type="submit">Clean old backups</button>
            </form>
        </section>
    </div>

    <section class="mf-card">
        <div class="mf-card-body border-b border-border">
            <h2 class="text-sm font-semibold">Backup archive</h2>
            <p class="mt-1 text-xs text-muted-foreground">Download important backups to a separate secure location. Local backups protect against application errors, but an off-server copy is recommended for disaster recovery.</p>
        </div>

        <div class="mf-table-frame border-0">
            <table class="mf-table" data-standard-table>
                <thead>
                    <tr>
                        <th>Backup</th>
                        <th>Type</th>
                        <th>Created</th>
                        <th>Size</th>
                        <th class="text-right">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($backups as $backup)
                        <tr>
                            <td>
                                <div class="font-medium">{{ $backup['filename'] }}</div>
                                <div class="mt-0.5 text-xs text-muted-foreground">Protected local storage</div>
                            </td>
                            <td>
                                <span class="mf-badge {{ $backup['type'] === 'full' ? 'mf-badge-info' : 'mf-badge-muted' }}">
                                    {{ $backup['type'] === 'full' ? 'Full data' : 'Database' }}
                                </span>
                            </td>
                            <td>{{ \Carbon\CarbonImmutable::createFromTimestamp($backup['created_at'])->format('d M Y H:i') }}</td>
                            <td>{{ $formatBytes($backup['size']) }}</td>
                            <td class="text-right">
                                <div class="inline-flex flex-wrap justify-end gap-2">
                                    <a class="mf-btn mf-btn-sm" href="{{ route('admin.system-backups.download', $backup['filename']) }}">Download</a>
                                    <form method="POST" action="{{ route('admin.system-backups.destroy', $backup['filename']) }}" onsubmit="return confirm('Delete this backup permanently?');">
                                        @csrf
                                        @method('DELETE')
                                        <button class="mf-btn mf-btn-sm" type="submit">Delete</button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="5" class="text-center text-muted-foreground">No system backups have been created yet.</td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </section>
</div>
@endsection
