@extends('layouts.admin')

@section('title', 'Programări Backup')

@section('content')
<div class="space-y-6">
    <!-- Header -->
    <div class="flex items-center justify-between">
        <div>
            <h1 class="text-3xl font-bold text-gray-900 dark:text-white">Programări Backup Automate</h1>
            <p class="mt-2 text-sm text-gray-600 dark:text-gray-400">
                Configurează backup-uri automate care rulează periodic
            </p>
        </div>
        <button onclick="showCreateScheduleModal()" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition">
            <i class="fas fa-plus mr-2"></i>Programare Nouă
        </button>
    </div>

    <!-- Listă Programări -->
    <div class="grid grid-cols-1 gap-6">
        @forelse($schedules as $schedule)
            <div class="bg-white dark:bg-gray-800 rounded-lg shadow-md p-6">
                <div class="flex items-start justify-between">
                    <div class="flex-1">
                        <div class="flex items-center gap-3 mb-2">
                            <h3 class="text-lg font-semibold text-gray-900 dark:text-white">
                                {{ $schedule->name }}
                            </h3>
                            <span class="px-2 py-1 text-xs font-semibold rounded-full
                                @if($schedule->type === 'full') bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300
                                @elseif($schedule->type === 'zones') bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300
                                @else bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300
                                @endif">
                                {{ ucfirst($schedule->type) }}
                            </span>
                            @if($schedule->enabled)
                                <span class="px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300">
                                    <i class="fas fa-check-circle mr-1"></i>Activ
                                </span>
                            @else
                                <span class="px-2 py-1 text-xs font-semibold rounded-full bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300">
                                    <i class="fas fa-pause-circle mr-1"></i>Inactiv
                                </span>
                            @endif
                        </div>

                        <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mt-4">
                            <div>
                                <p class="text-xs text-gray-600 dark:text-gray-400">Frecvență</p>
                                <p class="text-sm font-medium text-gray-900 dark:text-white">
                                    <i class="fas fa-calendar mr-1"></i>
                                    {{ ucfirst($schedule->frequency) }}
                                    @if($schedule->frequency === 'weekly')
                                        ({{ ['Duminică', 'Luni', 'Marți', 'Miercuri', 'Joi', 'Vineri', 'Sâmbătă'][$schedule->day_of_week] }})
                                    @elseif($schedule->frequency === 'monthly')
                                        (Ziua {{ $schedule->day_of_month }})
                                    @endif
                                </p>
                            </div>

                            <div>
                                <p class="text-xs text-gray-600 dark:text-gray-400">Oră Rulare</p>
                                <p class="text-sm font-medium text-gray-900 dark:text-white">
                                    <i class="fas fa-clock mr-1"></i>{{ substr($schedule->time, 0, 5) }}
                                </p>
                            </div>

                            <div>
                                <p class="text-xs text-gray-600 dark:text-gray-400">Următoarea Rulare</p>
                                <p class="text-sm font-medium text-gray-900 dark:text-white">
                                    @if($schedule->next_run_at)
                                        <i class="fas fa-hourglass-half mr-1"></i>{{ $schedule->next_run_at->format('d M, H:i') }}
                                    @else
                                        <i class="fas fa-minus mr-1"></i>-
                                    @endif
                                </p>
                            </div>

                            <div>
                                <p class="text-xs text-gray-600 dark:text-gray-400">Retenție</p>
                                <p class="text-sm font-medium text-gray-900 dark:text-white">
                                    <i class="fas fa-history mr-1"></i>{{ $schedule->retention_days }} zile
                                </p>
                            </div>
                        </div>

                        @if($schedule->last_run_at)
                            <div class="mt-3 text-xs text-gray-600 dark:text-gray-400">
                                Ultima rulare: {{ $schedule->last_run_at->diffForHumans() }}
                            </div>
                        @endif
                    </div>

                    <div class="flex items-center gap-2 ml-4">
                        <button onclick="toggleSchedule({{ $schedule->id }}, {{ $schedule->enabled ? 'false' : 'true' }})"
                                class="px-3 py-2 {{ $schedule->enabled ? 'bg-yellow-600 hover:bg-yellow-700' : 'bg-green-600 hover:bg-green-700' }} text-white rounded-lg transition text-sm">
                            <i class="fas fa-{{ $schedule->enabled ? 'pause' : 'play' }} mr-1"></i>
                            {{ $schedule->enabled ? 'Pause' : 'Activează' }}
                        </button>
                        <button onclick="editSchedule({{ $schedule->id }})"
                                class="px-3 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition text-sm">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button onclick="deleteSchedule({{ $schedule->id }})"
                                class="px-3 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg transition text-sm">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
            </div>
        @empty
            <div class="bg-white dark:bg-gray-800 rounded-lg shadow-md p-12 text-center">
                <i class="fas fa-clock text-6xl text-gray-300 dark:text-gray-600 mb-4"></i>
                <h3 class="text-xl font-semibold text-gray-900 dark:text-white mb-2">
                    Nicio Programare Configurată
                </h3>
                <p class="text-gray-600 dark:text-gray-400 mb-6">
                    Configurează backup-uri automate pentru a proteja datele periodic
                </p>
                <button onclick="showCreateScheduleModal()"
                        class="px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition">
                    <i class="fas fa-plus mr-2"></i>Prima Programare
                </button>
            </div>
        @endforelse
    </div>
</div>

<!-- Modal: Creare/Editare Programare -->
<div id="scheduleModal" class="hidden fixed inset-0 bg-gray-900 bg-opacity-50 overflow-y-auto h-full w-full z-50">
    <div class="relative top-20 mx-auto p-8 border w-full max-w-2xl shadow-lg rounded-lg bg-white dark:bg-gray-800">
        <div class="flex items-center justify-between mb-6">
            <h3 class="text-2xl font-bold text-gray-900 dark:text-white" id="modalTitle">Programare Nouă</h3>
            <button onclick="closeScheduleModal()" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300">
                <i class="fas fa-times text-2xl"></i>
            </button>
        </div>

        <form id="scheduleForm" class="space-y-6">
            @csrf
            <input type="hidden" id="scheduleId" name="id">

            <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Nume Programare *
                </label>
                <input type="text" name="name" id="scheduleName" required
                       placeholder="ex: Backup Zilnic Automat"
                       class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Tip Backup *
                </label>
                <select name="type" id="scheduleType" required
                        class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
                    <option value="full">Backup Complet (Zone + Bază de Date)</option>
                    <option value="zones">Doar Zone DNS</option>
                    <option value="database">Doar Bază de Date</option>
                </select>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Frecvență *
                    </label>
                    <select name="frequency" id="scheduleFrequency" required onchange="updateFrequencyOptions()"
                            class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
                        <option value="daily">Zilnic</option>
                        <option value="weekly">Săptămânal</option>
                        <option value="monthly">Lunar</option>
                    </select>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Ora Rulării *
                    </label>
                    <input type="time" name="time" id="scheduleTime" value="02:00" required
                           class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
                </div>
            </div>

            <div id="weeklyOptions" class="hidden">
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Ziua Săptămânii
                </label>
                <select name="day_of_week" id="scheduleDayOfWeek"
                        class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
                    <option value="0">Duminică</option>
                    <option value="1" selected>Luni</option>
                    <option value="2">Marți</option>
                    <option value="3">Miercuri</option>
                    <option value="4">Joi</option>
                    <option value="5">Vineri</option>
                    <option value="6">Sâmbătă</option>
                </select>
            </div>

            <div id="monthlyOptions" class="hidden">
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Ziua Lunii (1-28)
                </label>
                <input type="number" name="day_of_month" id="scheduleDayOfMonth" min="1" max="28" value="1"
                       class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Retenție (Zile) *
                </label>
                <input type="number" name="retention_days" id="scheduleRetention" min="1" max="365" value="30" required
                       class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
                <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                    Backup-urile mai vechi de acest număr de zile vor fi șterse automat
                </p>
            </div>

            <div class="flex items-center">
                <input type="checkbox" name="enabled" id="scheduleEnabled" checked
                       class="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500">
                <label for="scheduleEnabled" class="ml-2 text-sm font-medium text-gray-700 dark:text-gray-300">
                    Activează programarea imediat
                </label>
            </div>

            <div class="flex gap-3">
                <button type="button" onclick="closeScheduleModal()"
                        class="flex-1 px-4 py-3 bg-gray-600 hover:bg-gray-700 text-white rounded-lg transition">
                    Anulează
                </button>
                <button type="submit"
                        class="flex-1 px-4 py-3 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition font-semibold">
                    <i class="fas fa-save mr-2"></i>Salvează
                </button>
            </div>
        </form>
    </div>
</div>

@push('scripts')
<script>
function showCreateScheduleModal() {
    document.getElementById('modalTitle').textContent = 'Programare Nouă';
    document.getElementById('scheduleForm').reset();
    document.getElementById('scheduleId').value = '';
    document.getElementById('scheduleModal').classList.remove('hidden');
    updateFrequencyOptions();
}

function closeScheduleModal() {
    document.getElementById('scheduleModal').classList.add('hidden');
}

function updateFrequencyOptions() {
    const frequency = document.getElementById('scheduleFrequency').value;
    document.getElementById('weeklyOptions').classList.toggle('hidden', frequency !== 'weekly');
    document.getElementById('monthlyOptions').classList.toggle('hidden', frequency !== 'monthly');
}

document.getElementById('scheduleForm').addEventListener('submit', async function(e) {
    e.preventDefault();

    const formData = new FormData(this);
    const data = Object.fromEntries(formData);
    data.enabled = document.getElementById('scheduleEnabled').checked;

    const scheduleId = document.getElementById('scheduleId').value;
    const url = scheduleId
        ? `/admin/backups/schedules/${scheduleId}`
        : '{{ route("admin.backups.schedules.store") }}';
    const method = scheduleId ? 'PUT' : 'POST';

    try {
        const response = await fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            body: JSON.stringify(data)
        });

        const result = await response.json();

        if (result.success) {
            alert('Programare salvată cu succes!');
            location.reload();
        } else {
            alert('Eroare: ' + result.message);
        }
    } catch (error) {
        alert('A apărut o eroare la salvare');
        console.error(error);
    }
});

async function toggleSchedule(id, enabled) {
    try {
        const response = await fetch(`/admin/backups/schedules/${id}/toggle`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            body: JSON.stringify({ enabled })
        });

        const result = await response.json();
        if (result.success) {
            location.reload();
        }
    } catch (error) {
        alert('A apărut o eroare');
    }
}

async function deleteSchedule(id) {
    if (!confirm('Sigur doriți să ștergeți această programare?')) return;

    try {
        const response = await fetch(`/admin/backups/schedules/${id}`, {
            method: 'DELETE',
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            }
        });

        const result = await response.json();
        if (result.success) {
            alert('Programare ștearsă cu succes!');
            location.reload();
        }
    } catch (error) {
        alert('A apărut o eroare');
    }
}

function editSchedule(id) {
    // Implementare în viitor
    alert('Funcția de editare va fi implementată în curând');
}
</script>
@endpush
@endsection
