@extends('layouts.app')

@section('title', 'Riwayat Analisis - FIN-ANALYSIS PRO')

@section('content')
<div class="max-w-7xl mx-auto">
    <!-- Header -->
    <div class="mb-8 flex flex-col md:flex-row md:items-center md:justify-between">
        <div>
            <h1 class="text-3xl font-bold text-gray-900 dark:text-white mb-2">
                Riwayat Analisis
            </h1>
            <p class="text-gray-600 dark:text-gray-400">
                Daftar semua analisis Altman Z-Score yang telah Anda lakukan
            </p>
        </div>
        
        <!-- Action Buttons -->
        <div class="mt-4 md:mt-0 flex space-x-3">
            <button type="button" 
                    @click="exportData"
                    class="btn-outline">
                <i class="fas fa-download mr-2"></i>
                Ekspor
            </button>
            
            <a href="{{ route('analysis.step1') }}" class="btn-primary">
                <i class="fas fa-plus-circle mr-2"></i>
                Analisis Baru
            </a>
        </div>
    </div>

    <!-- Filters -->
    <div class="mb-6 bg-white dark:bg-gray-800 rounded-lg shadow p-4">
        <form method="GET" action="{{ route('history.index') }}" class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                <!-- Search -->
                <div class="col-span-1 md:col-span-2">
                    <div class="relative">
                        <i class="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                        <input type="text" 
                               name="search" 
                               value="{{ request('search') }}"
                               placeholder="Cari perusahaan..." 
                               class="input-field pl-10">
                    </div>
                </div>
                
                <!-- Filter Bidang Usaha -->
                <div>
                    <select name="business_field" class="input-field">
                        <option value="">Semua Bidang</option>
                        @foreach($businessFields as $field)
                            <option value="{{ $field }}" {{ request('business_field') == $field ? 'selected' : '' }}>
                                {{ $field }}
                            </option>
                        @endforeach
                    </select>
                </div>
                
                <!-- Filter Kategori -->
                <div>
                    <select name="category" class="input-field">
                        <option value="">Semua Kategori</option>
                        <option value="safe" {{ request('category') == 'safe' ? 'selected' : '' }}>Aman</option>
                        <option value="warning" {{ request('category') == 'warning' ? 'selected' : '' }}>Waspada</option>
                        <option value="danger" {{ request('category') == 'danger' ? 'selected' : '' }}>Bahaya</option>
                    </select>
                </div>
            </div>
            
            <!-- Date Range -->
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                    <label class="text-sm text-gray-600 dark:text-gray-400">Dari Tanggal</label>
                    <input type="date" name="date_from" value="{{ request('date_from') }}" class="input-field">
                </div>
                <div>
                    <label class="text-sm text-gray-600 dark:text-gray-400">Sampai Tanggal</label>
                    <input type="date" name="date_to" value="{{ request('date_to') }}" class="input-field">
                </div>
                <div class="flex items-end">
                    <button type="submit" class="btn-primary w-full">
                        <i class="fas fa-filter mr-2"></i>
                        Terapkan Filter
                    </button>
                </div>
            </div>
        </form>
    </div>

    <!-- History Table -->
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
        <div class="overflow-x-auto">
            <table class="table">
                <thead>
                    <tr>
                        <th class="w-8">
                            <input type="checkbox" id="selectAll" class="rounded border-gray-300">
                        </th>
                        <th>Tanggal</th>
                        <th>Perusahaan</th>
                        <th>Bidang Usaha</th>
                        <th>Periode</th>
                        <th class="text-right">Z-Score</th>
                        <th class="text-center">Kategori</th>
                        <th class="text-center">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($analyses as $analysis)
                        <tr class="hover:bg-gray-50 dark:hover:bg-gray-700 transition">
                            <td class="px-4 py-3">
                                <input type="checkbox" value="{{ $analysis->id }}" class="rounded border-gray-300">
                            </td>
                            <td class="px-4 py-3 whitespace-nowrap">
                                <div class="text-sm">{{ $analysis->created_at->format('d/m/Y') }}</div>
                                <div class="text-xs text-gray-500">{{ $analysis->created_at->format('H:i') }}</div>
                            </td>
                            <td class="px-4 py-3">
                                <div class="font-medium">{{ $analysis->company_name }}</div>
                            </td>
                            <td class="px-4 py-3">
                                @if($analysis->business_field === 'Lainnya')
                                    {{ $analysis->other_field }}
                                @else
                                    {{ $analysis->business_field }}
                                @endif
                            </td>
                            <td class="px-4 py-3">{{ $analysis->period }}</td>
                            <td class="px-4 py-3 text-right font-mono font-medium">
                                {{ number_format($analysis->z_score, 4) }}
                            </td>
                            <td class="px-4 py-3 text-center">
                                @php
                                    $categoryClasses = [
                                        'safe' => 'badge-success',
                                        'warning' => 'badge-warning',
                                        'danger' => 'badge-danger'
                                    ];
                                @endphp
                                <span class="badge {{ $categoryClasses[$analysis->z_category] ?? 'badge-info' }}">
                                    {{ $analysis->category_label }}
                                </span>
                            </td>
                            <td class="px-4 py-3 text-center">
                                <div class="flex items-center justify-center space-x-2">
                                    <a href="{{ route('history.show', $analysis->id) }}" 
                                       class="p-1 text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300"
                                       title="Detail">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    
                                    <a href="{{ route('report.preview', $analysis->id) }}" 
                                       target="_blank"
                                       class="p-1 text-green-600 hover:text-green-800 dark:text-green-400 dark:hover:text-green-300"
                                       title="Preview Laporan">
                                        <i class="fas fa-file-pdf"></i>
                                    </a>
                                    
                                    <a href="{{ route('report.download', $analysis->id) }}" 
                                       class="p-1 text-purple-600 hover:text-purple-800 dark:text-purple-400 dark:hover:text-purple-300"
                                       title="Download PDF">
                                        <i class="fas fa-download"></i>
                                    </a>
                                    
                                    <button type="button"
                                            onclick="toggleFavorite({{ $analysis->id }})"
                                            class="p-1 {{ $analysis->is_favorite ? 'text-yellow-500' : 'text-gray-400 hover:text-yellow-500' }}"
                                            title="{{ $analysis->is_favorite ? 'Hapus dari favorit' : 'Tambah ke favorit' }}">
                                        <i class="fas fa-star"></i>
                                    </button>
                                    
                                    <button type="button"
                                            onclick="confirmDelete({{ $analysis->id }}, '{{ $analysis->company_name }}')"
                                            class="p-1 text-red-600 hover:text-red-800 dark:text-red-400 dark:hover:text-red-300"
                                            title="Hapus">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="8" class="px-4 py-8 text-center text-gray-500 dark:text-gray-400">
                                <i class="fas fa-history text-4xl mb-3 opacity-50"></i>
                                <p>Belum ada data analisis</p>
                                <a href="{{ route('analysis.step1') }}" class="btn-primary mt-3 inline-block">
                                    Mulai Analisis Pertama
                                </a>
                            </td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
        
        <!-- Pagination -->
        <div class="px-4 py-3 border-t border-gray-200 dark:border-gray-700">
            {{ $analyses->withQueryString()->links() }}
        </div>
    </div>
</div>

<!-- Delete Form (Hidden) -->
<form id="delete-form" method="POST" style="display: none;">
    @csrf
    @method('DELETE')
</form>

@endsection

@push('scripts')
<script>
function confirmDelete(id, companyName) {
    if (confirm(`Apakah Anda yakin ingin menghapus analisis untuk "${companyName}"?`)) {
        const form = document.getElementById('delete-form');
        form.action = `/history/${id}`;
        form.submit();
    }
}

function toggleFavorite(id) {
    fetch(`/api/analysis/${id}/favorite`, {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': '{{ csrf_token() }}',
            'Accept': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Gagal mengubah status favorit');
    });
}

function exportData() {
    const selectedIds = [];
    document.querySelectorAll('input[type="checkbox"]:checked').forEach(cb => {
        if (cb.value) selectedIds.push(cb.value);
    });
    
    let url = '/history/export';
    if (selectedIds.length > 0) {
        url += '?ids=' + selectedIds.join(',');
    }
    
    window.location.href = url;
}

// Select All functionality
document.getElementById('selectAll')?.addEventListener('change', function() {
    document.querySelectorAll('input[type="checkbox"]').forEach(cb => {
        if (cb.id !== 'selectAll') {
            cb.checked = this.checked;
        }
    });
});
</script>
@endpush