@extends('layouts.app')

@section('content')
<style>
    .analytics-card {
        background: #16181d;
        border-radius: 2.5rem;
        border: 1px solid rgba(255, 255, 255, 0.05);
        padding: 2rem;
        transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .analytics-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 20px 40px rgba(0, 0, 0, 0.4);
        border-color: rgba(212, 175, 55, 0.2);
    }
    .status-badge {
        background: rgba(34, 197, 94, 0.1);
        color: #22c55e;
        border: 1px solid rgba(34, 197, 94, 0.2);
        padding: 0.5rem 1.5rem;
        border-radius: 9999px;
        font-size: 0.75rem;
        font-weight: 800;
        box-shadow: 0 0 15px rgba(34, 197, 94, 0.1);
    }
    .roi-panel {
        background: linear-gradient(145deg, rgba(255, 255, 255, 0.08), rgba(255, 255, 255, 0.03));
        backdrop-filter: blur(10px);
        border-radius: 2rem;
        padding: 1.5rem;
        border: 1px solid rgba(255, 255, 255, 0.05);
        margin: 1.5rem 0;
    }
    .progress-container {
        height: 4px;
        background: rgba(0, 0, 0, 0.3);
        border-radius: 999px;
        width: 100%;
        margin-top: 1.5rem;
        overflow: hidden;
    }
    .progress-bar {
        height: 100%;
        background: #22c55e;
        box-shadow: 0 0 10px #22c55e;
        transition: width 1s ease-in-out;
    }
    .icon-circle {
        width: 2.5rem;
        height: 2.5rem;
        background: #23262d;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #94a3b8;
        border: 1px solid rgba(255, 255, 255, 0.03);
    }
    .text-gold { color: #d4af37; }
    .text-gray-muted { color: #64748b; }
</style>

<div class="min-h-screen pb-20 px-4" x-data="lifecycleWatcher()" style="background-color: #0a0a0a;">
    <!-- Header -->
    <div class="flex flex-row-reverse items-start justify-between mb-12 pt-8">
        <div class="text-right">
            <p class="text-gold text-[10px] font-black tracking-[0.4em] mb-2">ANALYTICS ENGINE</p>
            <h1 class="text-4xl font-bold text-white mb-2">تحليل دورة حياة <span class="text-gold">المركبات</span></h1>
            <p class="text-gray-muted text-sm font-medium">نظام ذكي لتقييم الأداء المالي واتخاذ قرارات البيع أو الاحتفاظ.</p>
        </div>

        <form method="GET" action="{{ route('admin.analytics.vehicles') }}">
            <div class="relative">
                <select name="branch_id" onchange="this.form.submit()" 
                        class="appearance-none bg-black/40 border border-[#d4af37]/40 text-white text-sm rounded-xl px-10 py-2.5 pr-4 focus:border-[#d4af37] outline-none cursor-pointer shadow-[0_0_15px_rgba(212,175,55,0.1)]">
                    <option value="">تصفية حسب الفرع</option>
                    @foreach($branches as $branch)
                        <option value="{{ $branch->id }}" {{ $branchId == $branch->id ? 'selected' : '' }}>{{ $branch->name }}</option>
                    @endforeach
                </select>
                <div class="absolute inset-y-0 right-3 flex items-center pointer-events-none text-gold">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path></svg>
                </div>
            </div>
        </form>
    </div>

    <!-- Cards Grid -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
        @foreach($analytics as $car)
            <div class="analytics-card" @click="openModal({{ json_encode($car) }})">
                <!-- Top: Badge & Title -->
                <div class="flex flex-row-reverse justify-between items-start">
                    <div class="text-right">
                        <h3 class="text-white font-bold text-xl">{{ $car['title'] }}</h3>
                        <div class="flex flex-row-reverse items-center gap-2 mt-1">
                            <span class="text-gold text-[10px] font-bold">{{ $car['year'] }}</span>
                            <span class="text-gray-muted text-[10px] font-bold tracking-widest">{{ $car['plate_number'] }}</span>
                        </div>
                    </div>
                    <div class="status-badge" 
                         style="background: {{ $car['decision']['color'] == 'red' ? 'rgba(239, 68, 68, 0.1)' : ($car['decision']['color'] == 'yellow' ? 'rgba(245, 158, 11, 0.1)' : 'rgba(34, 197, 94, 0.1)') }}; 
                                color: {{ $car['decision']['color'] == 'red' ? '#ef4444' : ($car['decision']['color'] == 'yellow' ? '#f59e0b' : '#22c55e') }};
                                border-color: {{ $car['decision']['color'] == 'red' ? 'rgba(239, 68, 68, 0.2)' : ($car['decision']['color'] == 'yellow' ? 'rgba(245, 158, 11, 0.2)' : 'rgba(34, 197, 94, 0.2)') }};">
                        {{ $car['decision']['label'] }}
                    </div>
                </div>

                <!-- ROI Panel -->
                <div class="roi-panel">
                    <div class="flex flex-row-reverse justify-between items-start">
                        <div class="text-right">
                            <p class="text-[10px] text-gray-400 font-bold mb-1">ROI (محاسبي)</p>
                            <p class="text-3xl font-black text-white">{{ $car['roi'] }}%</p>
                        </div>
                        <div class="text-right flex flex-col items-end gap-2">
                            <p class="text-[10px] text-gray-400 font-bold">ROI (نقدي)</p>
                            <p class="text-sm font-bold text-[#22c55e]">{{ $car['cash_roi'] }}%</p>
                        </div>
                    </div>
                    <div class="progress-container">
                        <div class="progress-bar" style="width: {{ min($car['roi'], 100) }}%"></div>
                    </div>
                </div>

                <!-- Bottom: Figures -->
                <div class="grid grid-cols-2 gap-4 px-1">
                    <div class="flex items-center gap-2 justify-end">
                        <div class="text-right">
                            <p class="text-[9px] text-gray-500 font-bold">الربح المحاسبي</p>
                            <p class="text-sm font-black {{ $car['net_profit'] >= 0 ? 'text-white' : 'text-red-500' }}">
                                {{ number_format($car['net_profit'], 0) }} <span class="text-[8px] text-gray-600">ر.س</span>
                            </p>
                        </div>
                        <div class="icon-circle w-8 h-8">
                            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                        </div>
                    </div>

                    <div class="flex items-center gap-2 justify-end">
                        <div class="text-right">
                            <p class="text-[9px] text-gold font-bold">القيمة الدفترية</p>
                            <p class="text-sm font-black text-white">
                                {{ number_format($car['book_value'], 0) }} <span class="text-[8px] text-gray-600">ر.س</span>
                            </p>
                        </div>
                        <div class="icon-circle w-8 h-8 border-[#d4af37]/30">
                            <svg class="w-3.5 h-3.5 text-gold" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                        </div>
                    </div>

                    <div class="flex items-center gap-2 justify-end">
                        <div class="text-right">
                            <p class="text-[9px] text-red-400 font-bold">إهلاك متراكم</p>
                            <p class="text-sm font-black text-white">
                                {{ number_format($car['accumulated_depreciation'], 0) }} <span class="text-[8px] text-gray-600">ر.س</span>
                            </p>
                        </div>
                        <div class="icon-circle w-8 h-8 border-red-500/20">
                            <svg class="w-3.5 h-3.5 text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 17h8m0 0V9m0 8l-8-8-4 4-6-6"></path></svg>
                        </div>
                    </div>

                    <div class="flex items-center gap-2 justify-end">
                        <div class="text-right">
                            <p class="text-[9px] text-blue-400 font-bold">إجمالي الإيرادات</p>
                            <p class="text-sm font-black text-white">
                                {{ number_format($car['total_revenue'], 0) }} <span class="text-[8px] text-gray-600">ر.س</span>
                            </p>
                        </div>
                        <div class="icon-circle w-8 h-8 border-blue-500/20">
                            <svg class="w-3.5 h-3.5 text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg>
                        </div>
                    </div>
                </div>
            </div>
        @endforeach
    </div>

    <!-- Modal -->
    <template x-if="showModal">
        <div class="fixed inset-0 z-[100] flex items-center justify-center p-6 bg-black/90 backdrop-blur-sm" @click.self="showModal = false">
            <div class="bg-gradient-to-br from-[#161d27] to-[#0d1117] w-full max-w-2xl rounded-2xl border border-white/10 shadow-2xl overflow-hidden flex flex-col">
                <!-- Header -->
                <div class="p-4 border-b border-white/5 flex flex-row-reverse items-center justify-between">
                    <h2 class="text-lg font-bold text-white text-center flex-1" x-text="selectedCar?.title"></h2>
                    <button @click="showModal = false" class="text-gray-400 hover:text-white transition-colors">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
                    </button>
                    <div class="w-6"></div>
                </div>
                
                <!-- Content -->
                <div class="p-6">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <!-- Left: Info Boxes -->
                        <div class="flex flex-col gap-4 text-right order-2 md:order-1">
                            <div class="grid grid-cols-2 gap-4">
                                <div>
                                    <label class="text-[10px] text-gray-400 font-bold mb-1.5 block">تكلفة الشراء</label>
                                    <div class="bg-black/40 border border-white/10 rounded-lg p-3 text-white font-medium h-10 flex items-center justify-end shadow-inner text-sm" x-text="formatCurrency(selectedCar?.purchase_cost)"></div>
                                </div>
                                <div>
                                    <label class="text-[10px] text-gold font-bold mb-1.5 block">القيمة الدفترية</label>
                                    <div class="bg-black/40 border border-gold/20 rounded-lg p-3 text-gold font-black h-10 flex items-center justify-end shadow-inner text-sm" x-text="formatCurrency(selectedCar?.book_value)"></div>
                                </div>
                            </div>
                            <div class="grid grid-cols-2 gap-4">
                                <div>
                                    <label class="text-[10px] text-red-400 font-bold mb-1.5 block">الإهلاك المتراكم</label>
                                    <div class="bg-black/40 border border-red-500/10 rounded-lg p-3 text-red-400 font-medium h-10 flex items-center justify-end shadow-inner text-sm" x-text="formatCurrency(selectedCar?.accumulated_depreciation)"></div>
                                </div>
                                <div>
                                    <label class="text-[10px] text-green-400 font-bold mb-1.5 block">صافي الربح (نقدي)</label>
                                    <div class="bg-black/40 border border-green-500/10 rounded-lg p-3 text-green-400 font-medium h-10 flex items-center justify-end shadow-inner text-sm" x-text="formatCurrency(selectedCar?.cash_profit)"></div>
                                </div>
                            </div>
                            <div>
                                <label class="text-[10px] text-gray-400 font-bold mb-1.5 block">توصية النظام الذكي</label>
                                <div class="bg-black/40 border border-white/10 rounded-lg p-3 text-white font-medium min-h-[40px] flex items-center justify-end shadow-inner text-xs text-right" x-text="selectedCar?.decision.reason"></div>
                            </div>
                        </div>

                        <!-- Right: Chart Box -->
                        <div class="bg-black/20 border border-white/5 rounded-2xl p-6 flex flex-col items-center justify-center order-1 md:order-2">
                            <h3 class="text-[11px] font-bold text-white mb-4">التدفق المالي للمركبة</h3>
                            <div class="relative w-full aspect-square max-w-[160px]">
                                <canvas id="lifecycleChart"></canvas>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </template>
</div>

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    let chartInstance = null;
    document.addEventListener('alpine:init', () => {
        Alpine.data('lifecycleWatcher', () => ({
            selectedCar: null,
            showModal: false,
            openModal(car) {
                this.selectedCar = car;
                this.showModal = true;
                this.$nextTick(() => this.initChart(car));
            },
            formatCurrency(value) {
                return new Number(value || 0).toLocaleString('ar-SA') + ' ر.س';
            },
            initChart(car) {
                const ctx = document.getElementById('lifecycleChart').getContext('2d');
                if (chartInstance) chartInstance.destroy();
                chartInstance = new Chart(ctx, {
                    type: 'doughnut',
                    data: {
                        labels: ['إيرادات', 'قيمة دفترية', 'إهلاك', 'مصروفات'],
                        datasets: [{
                            data: [car.total_revenue, car.book_value, car.accumulated_depreciation, car.total_costs],
                            backgroundColor: ['#22c55e', '#d4af37', '#ef4444', '#3b82f6'],
                            borderWidth: 0,
                            borderRadius: 5,
                            spacing: 5
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        cutout: '80%',
                        plugins: {
                            legend: {
                                position: 'bottom',
                                labels: { color: '#888', font: { family: 'Tajawal', size: 10, weight: 'bold' }, padding: 20, usePointStyle: true }
                            }
                        }
                    }
                });
            }
        }));
    });
</script>
@endpush
@endsection
