<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>My Plans - Nova</title>
    
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Google Fonts & Font Awesome -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&family=Poppins:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    
    <style>
        body { font-family: 'Inter', sans-serif; overflow-x: hidden; background-color: #f7f8fa; }
        .main-container { max-width: 480px; margin: 0 auto; background-color: white; min-height: 100vh; }
        .active-indicator {
            position: absolute; bottom: 0; left: 50%; transform: translateX(-50%);
            width: 60%; height: 3px; background: linear-gradient(90deg, #dc2626, #ef4444);
            border-radius: 3px 3px 0 0; box-shadow: 0 0 10px rgba(220, 38, 38, 0.5);
        }
        .nav-item.active { transform: translateY(-2px); }
        nav.bottom-nav { position: fixed !important; bottom: 0; left: 0; right: 0; z-index: 50; max-width: 480px; margin: 0 auto; }
        main { padding-bottom: 100px; }

        /* Tab content visibility logic */
        .tab-content { display: none; }
        .tab-content.active { display: grid; }
    </style>
</head>
<body class="min-h-screen">

    <?php
        use App\Models\Purchase;
        use App\Models\UserLedger;

        $purchases = Purchase::where('user_id', auth()->id())->where('status', 'active')->with('package')->get();
        $dailyPurchases = $purchases->filter(function($p) { return optional($p->package)->tab == 'vip'; });
        $welfarePurchases = $purchases->filter(function($p) { return optional($p->package)->tab == 'fixed'; });
    ?>
    
    <div class="main-container">
        <!-- Header -->
        <header class="bg-white px-4 py-4 flex items-center justify-between shadow-sm sticky top-0 z-40">
            <button onclick="history.back()" class="text-gray-600 text-xl w-8 h-8 flex items-center justify-center">
                <i class="fas fa-arrow-left"></i>
            </button>
            <h1 class="text-gray-800 font-bold text-lg">My Plans</h1>
            <div class="w-8"></div> <!-- Placeholder for centering the title -->
        </header>

        <main class="relative z-10">
            <div class="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50 pb-4">
                <div class="w-full px-2 md:px-4 py-4">
                    
                    <!-- Modern Tab Selection -->
                    <div class="mb-4 md:mb-6 flex justify-center">
                        <div class="bg-white/60 backdrop-blur-md rounded-3xl p-1.5 shadow-lg border border-white/50 inline-flex">
                            <button id="daily-tab" class="tab flex-1 px-4 md:px-8 py-2 md:py-3 bg-gradient-to-r from-red-600 to-red-700 text-white rounded-2xl font-semibold text-xs md:text-sm shadow-lg shadow-red-500/30 transition-all" data-tab="daily-plans">
                                Daily Plans
                            </button>
                            <button id="welfare-tab" class="tab flex-1 px-4 md:px-8 py-2 md:py-3 text-gray-600 rounded-2xl font-semibold text-xs md:text-sm transition-all" data-tab="welfare-plans">
                                Welfare Plans
                            </button>
                        </div>
                    </div>

                    <!-- Daily Investment Plans Grid -->
                    <div id="daily-plans" class="tab-content active grid-cols-2 gap-2 md:gap-4">
                        @forelse($dailyPurchases as $purchase)
                            @php
                                $element = $purchase->package;
                                if(!$element) continue;

                                $last_claim = UserLedger::where(['user_id' => auth()->id(), 'reason' => 'daily_claim_'.$element->id, 'purchase_id' => $purchase->id])->latest()->first();
                                $lastInteractionDate = $last_claim ? $last_claim->created_at : $purchase->created_at;
                                $diffInHours = now()->diffInHours($lastInteractionDate);
                                $canClaim = $diffInHours >= 24;
                                $claimedToday = UserLedger::where(['user_id' => auth()->id(), 'reason' => 'daily_claim_'.$element->id, 'purchase_id' => $purchase->id])->whereDate('created_at', today())->exists();
                            @endphp
                            <div class="group bg-white rounded-2xl md:rounded-3xl shadow-lg transition-all duration-500 overflow-hidden border border-gray-100">
                                <div class="relative p-3 md:p-4">
                                    <div class="flex items-center justify-between mb-2">
                                        <span class="px-2 md:px-4 py-0.5 md:py-1 bg-gradient-to-r from-blue-500 to-blue-600 text-white text-xs font-bold rounded-full shadow-lg">{{ $element->name }}</span>
                                        <span class="px-2 md:px-4 py-0.5 md:py-1 bg-gradient-to-r from-yellow-500 to-amber-500 text-white text-xs font-bold rounded-full shadow-lg">{{ $element->validity }} Days</span>
                                    </div>
                                    <div class="relative mb-2 flex justify-center">
                                        <div class="w-14 h-14 md:w-20 md:h-20 rounded-xl md:rounded-2xl overflow-hidden shadow-xl ring-2 md:ring-3 ring-blue-100">
                                            <img src="{{ asset($element->photo) }}" alt="{{ $element->name }}" class="w-full h-full object-cover">
                                        </div>
                                    </div>
                                    <div class="bg-gradient-to-br from-gray-50 to-blue-50 rounded-xl p-2 mb-3 text-center">
                                        <p class="text-sm md:text-2xl font-black text-red-600">৳{{ number_format($element->daily_limit, 2) }}</p>
                                        <p class="text-xs text-gray-600 font-semibold mt-0.5">Daily Income</p>
                                    </div>
                                    
                                    @if($claimedToday)
                                        <button disabled class="w-full bg-gradient-to-r from-green-500 to-emerald-500 text-white py-2 rounded-xl font-bold text-xs md:text-sm shadow-lg">Claimed</button>
                                    @elseif($canClaim)
                                        <a href="/my/vip?vip_id={{$element->id}}" class="block text-center w-full bg-gradient-to-r from-red-500 to-orange-500 hover:from-red-600 hover:to-orange-600 text-white py-2 rounded-xl font-bold text-xs md:text-sm shadow-lg hover:shadow-xl transition-all">Claim Now</a>
                                    @else
                                        <button disabled class="w-full bg-gradient-to-r from-gray-400 to-gray-500 text-white py-2 rounded-xl font-bold text-xs md:text-sm shadow-lg opacity-80" id="countdown-{{ $purchase->id }}">00h 00m 00s</button>
                                    @endif
                                </div>
                            </div>

                            @if(!$canClaim && !$claimedToday)
                            <script>
                                (function() {
                                    const countdownElement = document.getElementById("countdown-{{ $purchase->id }}");
                                    if (!countdownElement) return;

                                    const interactionDate = new Date("{{ $lastInteractionDate->toIso8601String() }}");
                                    const endTime = new Date(interactionDate.getTime() + 24 * 60 * 60 * 1000);

                                    const interval = setInterval(() => {
                                        const now = new Date().getTime();
                                        const distance = endTime - now;

                                        if (distance < 0) {
                                            clearInterval(interval);
                                            const link = document.createElement('a');
                                            link.href = "/my/vip?vip_id={{$element->id}}";
                                            link.className = "block text-center w-full bg-gradient-to-r from-red-500 to-orange-500 hover:from-red-600 hover:to-orange-600 text-white py-2 rounded-xl font-bold text-xs md:text-sm shadow-lg hover:shadow-xl transition-all";
                                            link.textContent = 'Claim Now';
                                            countdownElement.parentNode.replaceChild(link, countdownElement);
                                            return;
                                        }

                                        const hours = Math.floor(distance / (1000 * 60 * 60)).toString().padStart(2, '0');
                                        const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)).toString().padStart(2, '0');
                                        const seconds = Math.floor((distance % (1000 * 60)) / 1000).toString().padStart(2, '0');

                                        countdownElement.textContent = `${hours}h ${minutes}m ${seconds}s`;
                                    }, 1000);
                                })();
                            </script>
                            @endif

                        @empty
                            <p class="col-span-2 text-center text-gray-500 py-10">You have no active daily plans.</p>
                        @endforelse
                    </div>

                    <!-- Welfare Plans Grid -->
                    <div id="welfare-plans" class="tab-content grid-cols-2 gap-2 md:gap-4">
                        @forelse($welfarePurchases as $purchase)
                            @php
                                $element = $purchase->package;
                                if(!$element) continue;
                                $isExpired = $purchase->created_at->addDays($element->validity) <= now();
                            @endphp
                             <div class="group bg-white rounded-2xl md:rounded-3xl shadow-lg transition-all duration-500 overflow-hidden border border-gray-100">
                                <div class="relative p-3 md:p-4">
                                    <div class="flex items-center justify-between mb-2">
                                        <span class="px-2 md:px-4 py-0.5 md:py-1 bg-gradient-to-r from-indigo-500 to-purple-600 text-white text-xs font-bold rounded-full shadow-lg">{{ $element->name }}</span>
                                        <span class="px-2 md:px-4 py-0.5 md:py-1 bg-gradient-to-r from-teal-500 to-cyan-500 text-white text-xs font-bold rounded-full shadow-lg">{{ $element->validity }} Days</span>
                                    </div>
                                    <div class="relative mb-2 flex justify-center">
                                        <div class="w-14 h-14 md:w-20 md:h-20 rounded-xl md:rounded-2xl overflow-hidden shadow-xl ring-2 md:ring-3 ring-indigo-100">
                                            <img src="{{ asset($element->photo) }}" alt="{{ $element->name }}" class="w-full h-full object-cover">
                                        </div>
                                    </div>
                                    <div class="bg-gradient-to-br from-gray-50 to-indigo-50 rounded-xl p-2 mb-3 text-center">
                                        <p class="text-sm md:text-2xl font-black text-indigo-600">৳{{ number_format($element->daily_limit * $element->validity, 2) }}</p>
                                        <p class="text-xs text-gray-600 font-semibold mt-0.5">Total Income</p>
                                    </div>
                                    
                                    @if($isExpired)
                                        <a href="/my/vip?vip_id={{$element->id}}" class="block text-center w-full bg-gradient-to-r from-blue-500 to-indigo-500 hover:from-blue-600 hover:to-indigo-600 text-white py-2 rounded-xl font-bold text-xs md:text-sm shadow-lg hover:shadow-xl transition-all">Claim Total</a>
                                    @else
                                        <button disabled class="w-full bg-gradient-to-r from-gray-400 to-gray-500 text-white py-2 rounded-xl font-bold text-xs md:text-sm shadow-lg opacity-80">Running</button>
                                    @endif
                                </div>
                            </div>
                        @empty
                            <p class="col-span-2 text-center text-gray-500 py-10">You have no active welfare plans.</p>
                        @endforelse
                    </div>
                </div>
            </div>
        </main>
    </div>

    <!-- Bottom Navigation -->
    <nav class="bottom-nav bg-gradient-to-t from-white via-white to-white/95 backdrop-blur-lg shadow-[0_-8px_32px_rgba(0,0,0,0.12)] border-t border-red-100 h-20">
        <div class="flex justify-around items-center w-full h-full">
            @php
                $nav_items = [
                    ['path' => 'dashboard', 'icon' => 'fas fa-home', 'label' => 'Home'],
                    ['path' => 'vip', 'icon' => 'fas fa-briefcase', 'label' => 'Plans'],
                    ['path' => 'my-team', 'icon' => 'fas fa-users', 'label' => 'Team'],
                    ['path' => 'my-profile', 'icon' => 'fas fa-user', 'label' => 'Profile'],
                ];
            @endphp
            @foreach($nav_items as $item)
            <a href="{{ url($item['path']) }}" class="nav-item flex-1 flex flex-col items-center justify-center relative rounded-2xl text-gray-500 hover:text-red-500 transition-all duration-300 h-full {{ request()->is('my-vip') || request()->is('vip') ? ( $item['label'] == 'Plans' ? 'text-red-600 bg-red-50 active' : '' ) : (request()->is($item['path']) ? 'text-red-600 bg-red-50 active' : '') }}">
                <div class="relative">
                    <i class="{{ $item['icon'] }} text-xl mb-1"></i>
                    @if(request()->is('my-vip') || request()->is('vip') ? $item['label'] == 'Plans' : request()->is($item['path']))
                        <div class="active-indicator"></div>
                    @endif
                </div>
                <span class="font-poppins text-[10px] font-semibold tracking-wide">{{ $item['label'] }}</span>
            </a>
            @endforeach
        </div>
    </nav>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Tab switching logic
            const tabs = document.querySelectorAll('.tab');
            const tabContents = document.querySelectorAll('.tab-content');
            const dailyTab = document.getElementById('daily-tab');
            const welfareTab = document.getElementById('welfare-tab');

            tabs.forEach(tab => {
                tab.addEventListener('click', function () {
                    const targetId = this.getAttribute('data-tab');
                    
                    tabContents.forEach(c => c.classList.remove('active'));
                    document.getElementById(targetId).classList.add('active');

                    // Update tab styles
                    if (targetId === 'daily-plans') {
                        dailyTab.className = 'tab flex-1 px-4 md:px-8 py-2 md:py-3 bg-gradient-to-r from-red-600 to-red-700 text-white rounded-2xl font-semibold text-xs md:text-sm shadow-lg shadow-red-500/30 transition-all';
                        welfareTab.className = 'tab flex-1 px-4 md:px-8 py-2 md:py-3 text-gray-600 rounded-2xl font-semibold text-xs md:text-sm transition-all';
                    } else {
                        dailyTab.className = 'tab flex-1 px-4 md:px-8 py-2 md:py-3 text-gray-600 rounded-2xl font-semibold text-xs md:text-sm transition-all';
                        welfareTab.className = 'tab flex-1 px-4 md:px-8 py-2 md:py-3 bg-gradient-to-r from-blue-600 to-blue-700 text-white rounded-2xl font-semibold text-xs md:text-sm shadow-lg shadow-blue-500/30 transition-all';
                    }
                });
            });
        });
    </script>
</body>
</html>