@extends('layouts.app')

@section('title', 'Detail Analisis - ' . $analysis->company_name . ' - FIN-ANALYSIS PRO')

@php
if (!function_exists('formatCurrency')) {
    function formatCurrency($value, $currency = 'Rp') {
        if ($value === null || $value === '') return $currency . ' 0';
        return $currency . ' ' . number_format((float)$value, 0, ',', '.');
    }
}
@endphp

@section('content')
<div class="max-w-7xl mx-auto">
    <!-- Header -->
    <div class="mb-6 flex flex-col md:flex-row md:items-center md:justify-between">
        <div>
            <div class="flex items-center space-x-2 mb-2">
                <a href="{{ route('history.index') }}" class="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300">
                    <i class="fas fa-arrow-left"></i>
                </a>
                <h1 class="text-2xl font-bold text-gray-900 dark:text-white">
                    Detail Analisis
                </h1>
            </div>
            <p class="text-gray-600 dark:text-gray-400">
                Hasil analisis Altman Z-Score untuk {{ $analysis->company_name }}
            </p>
        </div>
        
        <!-- Action Buttons -->
        <div class="mt-4 md:mt-0 flex flex-wrap gap-2">
            <button type="button" 
                    onclick="toggleFavorite({{ $analysis->id }})"
                    class="btn-outline">
                <i class="fas fa-star mr-2 {{ $analysis->is_favorite ? 'text-yellow-500' : '' }}"></i>
                {{ $analysis->is_favorite ? 'Hapus dari Favorit' : 'Tambah ke Favorit' }}
            </button>
            
            <a href="{{ route('report.preview', $analysis->id) }}" 
               target="_blank"
               class="btn-outline">
                <i class="fas fa-eye mr-2"></i>
                Preview PDF
            </a>
            
            <a href="{{ route('report.download', $analysis->id) }}" 
               class="btn-primary">
                <i class="fas fa-download mr-2"></i>
                Download PDF
            </a>
        </div>
    </div>

    <!-- Company Info Cards -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
        <div class="card">
            <div class="flex items-center">
                <div class="p-3 bg-primary-100 dark:bg-primary-900/30 rounded-lg">
                    <i class="fas fa-building text-primary-600 dark:text-primary-400 text-xl"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm text-gray-500 dark:text-gray-400">Perusahaan</p>
                    <p class="font-semibold">{{ $analysis->company_name }}</p>
                </div>
            </div>
        </div>
        
        <div class="card">
            <div class="flex items-center">
                <div class="p-3 bg-info-100 dark:bg-info-900/30 rounded-lg">
                    <i class="fas fa-tag text-info-600 dark:text-info-400 text-xl"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm text-gray-500 dark:text-gray-400">Bidang Usaha</p>
                    <p class="font-semibold">
                        @if($analysis->business_field === 'Lainnya')
                            {{ $analysis->other_field }}
                        @else
                            {{ $analysis->business_field }}
                        @endif
                    </p>
                </div>
            </div>
        </div>
        
        <div class="card">
            <div class="flex items-center">
                <div class="p-3 bg-warning-100 dark:bg-warning-900/30 rounded-lg">
                    <i class="fas fa-calendar text-warning-600 dark:text-warning-400 text-xl"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm text-gray-500 dark:text-gray-400">Periode</p>
                    <p class="font-semibold">{{ $analysis->period }}</p>
                </div>
            </div>
        </div>
        
        <div class="card">
            <div class="flex items-center">
                <div class="p-3 bg-success-100 dark:bg-success-900/30 rounded-lg">
                    <i class="fas fa-chart-line text-success-600 dark:text-success-400 text-xl"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm text-gray-500 dark:text-gray-400">Tanggal Analisis</p>
                    <p class="font-semibold">{{ $analysis->created_at->format('d/m/Y H:i') }}</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Main Content Grid -->
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- Left Column - Z-Score Gauge & Summary -->
        <div class="lg:col-span-1">
            <div class="card mb-6">
                <h3 class="card-header">Ringkasan Z-Score</h3>
                
                <!-- Gauge -->
                <div class="mb-4">
                    <x-zscore-gauge :score="$analysis->z_score" size="lg" />
                </div>
                
                <!-- Score Details -->
                <div class="space-y-3">
                    <div class="flex justify-between items-center p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                        <span class="text-gray-600 dark:text-gray-400">Z-Score</span>
                        <span class="font-mono font-bold text-xl 
                            @if($analysis->z_category === 'safe') text-success-600
                            @elseif($analysis->z_category === 'warning') text-warning-600
                            @else text-danger-600
                            @endif">
                            {{ number_format($analysis->z_score, 4) }}
                        </span>
                    </div>
                    
                    <div class="flex justify-between items-center p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                        <span class="text-gray-600 dark:text-gray-400">Kategori</span>
                        <span class="badge 
                            @if($analysis->z_category === 'safe') badge-success
                            @elseif($analysis->z_category === 'warning') badge-warning
                            @else badge-danger
                            @endif">
                            {{ $analysis->category_label }}
                        </span>
                    </div>
                    
                    <div class="flex justify-between items-center p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                        <span class="text-gray-600 dark:text-gray-400">Mata Uang</span>
                        <span class="font-semibold">{{ $analysis->currency }}</span>
                    </div>
                </div>
            </div>
            
            <!-- Quick Actions -->
            <div class="card">
                <h3 class="card-header">Aksi Cepat</h3>
                <div class="space-y-2">
                    <button onclick="shareAnalysis({{ $analysis->id }})" class="w-full btn-outline text-left">
                        <i class="fas fa-share-alt mr-2"></i>
                        Bagikan Analisis
                    </button>
                    
                    <button onclick="printAnalysis()" class="w-full btn-outline text-left">
                        <i class="fas fa-print mr-2"></i>
                        Cetak Halaman
                    </button>
                    
                    
                    
                    <button onclick="confirmDelete({{ $analysis->id }}, '{{ $analysis->company_name }}')" 
                            class="w-full btn-outline text-left text-danger-600 hover:bg-danger-50 dark:hover:bg-danger-900/20">
                        <i class="fas fa-trash mr-2"></i>
                        Hapus Analisis
                    </button>
                </div>
            </div>
        </div>
        
        <!-- Right Column - Financial Data & Z-Score Components -->
        <div class="lg:col-span-2">
            <!-- Z-Score Components Card -->
            <div class="card mb-6">
                <h3 class="card-header">Komponen Z-Score</h3>
                
                <div class="grid grid-cols-1 md:grid-cols-5 gap-4 mb-6">
                    <div class="text-center p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                        <div class="text-xs text-gray-500">X1</div>
                        <div class="font-mono font-bold">{{ number_format($analysis->x1, 4) }}</div>
                    </div>
                    <div class="text-center p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                        <div class="text-xs text-gray-500">X2</div>
                        <div class="font-mono font-bold">{{ number_format($analysis->x2, 4) }}</div>
                    </div>
                    <div class="text-center p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                        <div class="text-xs text-gray-500">X3</div>
                        <div class="font-mono font-bold">{{ number_format($analysis->x3, 4) }}</div>
                    </div>
                    <div class="text-center p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                        <div class="text-xs text-gray-500">X4</div>
                        <div class="font-mono font-bold">{{ number_format($analysis->x4, 4) }}</div>
                    </div>
                    <div class="text-center p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                        <div class="text-xs text-gray-500">X5</div>
                        <div class="font-mono font-bold">{{ number_format($analysis->x5, 4) }}</div>
                    </div>
                </div>
                
                <!-- Interpretation -->
                @php
                    $interpretation = $analysis->interpretation;
                @endphp
                
                <div class="p-4 rounded-lg {{ 
                    $analysis->z_category === 'safe' ? 'bg-success-50 dark:bg-success-900/20' : 
                    ($analysis->z_category === 'warning' ? 'bg-warning-50 dark:bg-warning-900/20' : 
                    'bg-danger-50 dark:bg-danger-900/20') 
                }}">
                    <h4 class="font-semibold mb-2">Interpretasi</h4>
                    <p class="text-sm mb-3">{{ $interpretation['description'] }}</p>
                    
                    <h5 class="font-medium text-sm mb-2">Rekomendasi:</h5>
                    <ul class="list-disc list-inside text-sm space-y-1">
                        @foreach($interpretation['recommendations'] as $rec)
                            <li>{{ $rec }}</li>
                        @endforeach
                    </ul>
                </div>
            </div>
            
            <!-- Financial Data Card -->
            <div class="card">
                <h3 class="card-header">Data Keuangan</h3>
                
                <div class="overflow-x-auto">
                    <table class="min-w-full">
                        <tbody class="divide-y divide-gray-200 dark:divide-gray-700">
                            <tr class="bg-gray-50 dark:bg-gray-900">
                                <td colspan="2" class="px-4 py-2 font-semibold">ASET</td>
                            </tr>
                            <tr>
                                <td class="px-4 py-2">Aset Lancar</td>
                                <td class="px-4 py-2 text-right font-mono">
                                    {{ formatCurrency($financialData['aset_lancar'] ?? 0, $analysis->currency) }}
                                </td>
                            </tr>
                            <tr>
                                <td class="px-4 py-2">Aset Tetap</td>
                                <td class="px-4 py-2 text-right font-mono">
                                    {{ formatCurrency($financialData['aset_tetap'] ?? 0, $analysis->currency) }}
                                </td>
                            </tr>
                            <tr class="font-semibold">
                                <td class="px-4 py-2">Total Aset</td>
                                <td class="px-4 py-2 text-right font-mono text-primary-600">
                                    {{ formatCurrency(($financialData['aset_lancar'] ?? 0) + ($financialData['aset_tetap'] ?? 0), $analysis->currency) }}
                                </td>
                            </tr>
                            
                            <tr class="bg-gray-50 dark:bg-gray-900">
                                <td colspan="2" class="px-4 py-2 font-semibold">LIABILITAS</td>
                            </tr>
                            <tr>
                                <td class="px-4 py-2">Utang Lancar</td>
                                <td class="px-4 py-2 text-right font-mono">
                                    {{ formatCurrency($financialData['utang_lancar'] ?? 0, $analysis->currency) }}
                                </td>
                            </tr>
                            <tr>
                                <td class="px-4 py-2">Utang Jangka Panjang</td>
                                <td class="px-4 py-2 text-right font-mono">
                                    {{ formatCurrency($financialData['utang_jangka_panjang'] ?? 0, $analysis->currency) }}
                                </td>
                            </tr>
                            <tr class="font-semibold">
                                <td class="px-4 py-2">Total Utang</td>
                                <td class="px-4 py-2 text-right font-mono text-warning-600">
                                    {{ formatCurrency(($financialData['utang_lancar'] ?? 0) + ($financialData['utang_jangka_panjang'] ?? 0), $analysis->currency) }}
                                </td>
                            </tr>
                            
                            <tr class="bg-gray-50 dark:bg-gray-900">
                                <td colspan="2" class="px-4 py-2 font-semibold">EKUITAS</td>
                            </tr>
                            <tr class="font-semibold">
                                <td class="px-4 py-2">Nilai Buku Ekuitas</td>
                                <td class="px-4 py-2 text-right font-mono text-success-600">
                                    @php
                                        $totalAset = ($financialData['aset_lancar'] ?? 0) + ($financialData['aset_tetap'] ?? 0);
                                        $totalUtang = ($financialData['utang_lancar'] ?? 0) + ($financialData['utang_jangka_panjang'] ?? 0);
                                    @endphp
                                    {{ formatCurrency($totalAset - $totalUtang, $analysis->currency) }}
                                </td>
                            </tr>
                            
                            <tr class="bg-gray-50 dark:bg-gray-900">
                                <td colspan="2" class="px-4 py-2 font-semibold">LABA RUGI</td>
                            </tr>
                            <tr>
                                <td class="px-4 py-2">Pendapatan</td>
                                <td class="px-4 py-2 text-right font-mono">
                                    {{ formatCurrency($financialData['pendapatan'] ?? 0, $analysis->currency) }}
                                </td>
                            </tr>
                            <tr>
                                <td class="px-4 py-2">Biaya Operasional</td>
                                <td class="px-4 py-2 text-right font-mono">
                                    {{ formatCurrency($financialData['biaya_operasional'] ?? 0, $analysis->currency) }}
                                </td>
                            </tr>
                            <tr>
                                <td class="px-4 py-2">Laba Sebelum Pajak</td>
                                <td class="px-4 py-2 text-right font-mono">
                                    {{ formatCurrency(($financialData['pendapatan'] ?? 0) - ($financialData['biaya_operasional'] ?? 0), $analysis->currency) }}
                                </td>
                            </tr>
                            <tr>
                                <td class="px-4 py-2">Prive</td>
                                <td class="px-4 py-2 text-right font-mono">
                                    {{ formatCurrency($financialData['prive'] ?? 0, $analysis->currency) }}
                                </td>
                            </tr>
                            <tr class="font-semibold">
                                <td class="px-4 py-2">Laba Ditahan</td>
                                <td class="px-4 py-2 text-right font-mono text-info-600">
                                    @php
                                        $laba = ($financialData['pendapatan'] ?? 0) - ($financialData['biaya_operasional'] ?? 0);
                                    @endphp
                                    {{ formatCurrency($laba - ($financialData['prive'] ?? 0), $analysis->currency) }}
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Delete Form -->
<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 shareAnalysis(id) {
    // Generate shareable link
    fetch(`/api/analysis/${id}/share`, {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': '{{ csrf_token() }}',
            'Accept': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.shareable_link) {
            // Copy to clipboard
            navigator.clipboard.writeText(data.shareable_link).then(() => {
                alert('Link berhasil disalin ke clipboard!');
            });
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Gagal membuat link sharing');
    });
}

function printAnalysis() {
    window.print();
}
</script>
@endpush