<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
<title>{{ env('APP_NAME') }} | My Orders</title>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/layui/2.5.7/css/layui.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<style>
body {margin:0;font-family:Inter,sans-serif;background:#f5f6fa;color:#333;}
.app-header {display:flex;align-items:center;justify-content:space-between;padding:12px 16px;background:#fff;box-shadow:0 2px 6px rgba(0,0,0,0.05);position:sticky;top:0;z-index:100;}
.app-header .page-title {font-weight:600;font-size:16px;}
.myorder {padding:12px;}
.myorder-top {display:flex;justify-content:space-around;background:#fff;padding:16px;border-radius:12px;margin-bottom:12px;box-shadow:0 2px 6px rgba(0,0,0,0.05);}
.myorder-top div p:first-child {font-size:18px;font-weight:600;color:#1E3A8A;margin:0;}
.myorder-top div p:last-child {font-size:12px;color:#666;margin:0;margin-top:4px;}
.record-tab {display:flex;gap:12px;margin-bottom:12px;overflow-x:auto;padding-bottom:6px;}
.record-tab a {flex:1;text-align:center;padding:8px 0;border-radius:8px;background:#e0e7ff;color:#1e3a8a;font-weight:500;text-decoration:none;white-space:nowrap;}
.record-tab a.active {background:#1e3a8a;color:#fff;}
.myorder-list .home-product-infos {display:flex;gap:12px;background:#fff;padding:12px;border-radius:12px;margin-bottom:12px;align-items:center;box-shadow:0 2px 6px rgba(0,0,0,0.05);}
.home-product-img img {width:64px;height:64px;border-radius:8px;object-fit:cover;}
.product-details h3 {margin:0;font-size:14px;font-weight:600;color:#111;}
.product-texts p {margin:4px 0;font-size:12px;color:#555;display:flex;justify-content:space-between;}
.claim-btn {padding:6px 12px;font-size:12px;border:none;border-radius:6px;background:#1E3A8A;color:#fff;cursor:pointer;}
.claim-btn:disabled {background:#94a3b8;cursor:not-allowed;}
.dropload-down {text-align:center;color:#888;padding:12px;font-size:12px;}
.toast {position:fixed;top:20px;left:50%;transform:translateX(-50%) translateY(-50px);background:#333;color:#fff;padding:10px 14px;border-radius:8px;opacity:0;transition:0.3s;z-index:1000;display:flex;align-items:center;gap:6px;}
.toast.show {opacity:1;transform:translateX(-50%) translateY(0);}
.toast.success {background:#1E3A8A;}
.toast.warning {background:#F59E0B;}
.toast.error {background:#DC2626;}
.fake-claims {margin-top:16px;background:#fff;padding:12px;border-radius:12px;box-shadow:0 2px 6px rgba(0,0,0,0.05);}
.fake-claims h4 {margin:0 0 8px 0;font-size:14px;color:#1E3A8A;}
.fake-claims ul {padding-left:20px;margin:0;}
.fake-claims ul li {font-size:12px;color:#555;margin-bottom:4px;}
</style>
</head>
<body>

<header class="app-header">
  <a href="{{ route('dashboard') }}"><i class="fa fa-chevron-left"></i></a>
  <h1 class="page-title">My Orders</h1>
  <div><i class="fa fa-bell"></i></div>
</header>

@php
$user = auth()->user();
$totalAssets = \App\Models\Purchase::where('user_id', $user->id)->where('status', 'active')->sum('amount'); 
$totalIncome = \App\Models\UserLedger::where('user_id', $user->id)->where('reason', 'daily_income')->sum('amount');
$activePurchases = \App\Models\Purchase::where('user_id', $user->id)->where('status', 'active')->get();
$expiredPurchases = \App\Models\Purchase::where('user_id', $user->id)->where('status', 'expired')->get();
@endphp

<div class="myorder">
  <!-- Summary -->
  <div class="myorder-top">
    <div>
      <p>{{ price($totalAssets) }}</p>
      <p>Total Assets</p>
    </div>
    <div>
      <p>{{ price($totalIncome) }}</p>
      <p>Total Income</p>
    </div>
  </div>

  <!-- Tabs -->
  <div class="record-tab">
    <a href="#" class="active" data-tab="valid"><i class="fa fa-check-circle"></i> Active Plans</a>
    <a href="#" data-tab="expired"><i class="fa fa-clock-rotate-left"></i> Expired Plans</a>
  </div>

  <!-- Active Orders -->
  <div class="myorder-list tab-content" id="valid" style="display:block;">
    @foreach($activePurchases as $purchase)
    @php $package = $purchase->package; @endphp
    <div class="home-product-infos">
      <div class="home-product-img">
        <img src="{{ asset($package->photo) }}" alt="Product">
      </div>
      <div class="product-details">
        <h3>{{ $package->name ?? 'Product Name' }}</h3>
        <div class="product-texts">
          <p><span>Cycle</span><span>{{ $package->validity ?? 'N/A' }} Day</span></p>
          <p><span>Total</span><span>{{ price($package->commission_with_avg_amount ?? 0) }}</span></p>
          <p><span>Purchase</span><span>{{ $purchase->created_at->format('Y-m-d H:i') }}</span></p>
          <button class="claim-btn" data-id="{{ $purchase->id }}"><i class="fa fa-hand-holding-dollar"></i> Claim Income</button>
        </div>
      </div>
    </div>
    @endforeach
  </div>

  <!-- Expired Orders -->
  <div class="myorder-list tab-content" id="expired" style="display:none;">
    @foreach($expiredPurchases as $purchase)
    @php $package = $purchase->package; @endphp
    <div class="home-product-infos">
      <div class="home-product-img">
        <img src="{{ asset($package->photo) }}" alt="Product">
      </div>
      <div class="product-details">
        <h3>{{ $package->name ?? 'Expired Product' }}</h3>
        <div class="product-texts">
          <p><span>Cycle</span><span>{{ $package->validity ?? 'N/A' }} Days</span></p>
          <p><span>Total</span><span>{{ price($package->commission_with_avg_amount ?? 0) }}</span></p>
          <p><span>Daily Income</span><span>{{ price($package->daily_income ?? 0) }}</span></p>
          <p><span>Purchased</span><span>{{ $purchase->created_at->format('Y-m-d H:i') }}</span></p>
        </div>
      </div>
    </div>
    @endforeach
  </div>

  <!-- Fake Claim Users -->
  <div class="fake-claims">
    <h4>Recent Claims</h4>
    <ul id="fakeUsers">
      <li>John D. claimed R500</li>
      <li>Mary P. claimed R200</li>
      <li>Alex K. claimed R300</li>
    </ul>
  </div>

  <div class="dropload-down">
    <div class="dropload-nodata"><i class="fa fa-leaf"></i> That’s all for now 🌿</div>
  </div>
</div>

<script>
function showToast(message,type="success"){
  const toast=$('<div class="toast '+type+'"><i class="fa '+
  (type==="success"?'fa-circle-check':type==="warning"?'fa-triangle-exclamation':'fa-circle-xmark')+'"></i> '+message+'</div>');
  $('body').append(toast);
  setTimeout(()=>toast.addClass('show'),100);
  setTimeout(()=>toast.removeClass('show'),3000);
}

// Tab switch
document.querySelectorAll('.record-tab a').forEach(tab=>{
  tab.addEventListener('click',function(e){
    e.preventDefault();
    document.querySelectorAll('.record-tab a').forEach(t=>t.classList.remove('active'));
    this.classList.add('active');
    document.querySelectorAll('.tab-content').forEach(c=>c.style.display='none');
    document.getElementById(this.getAttribute('data-tab')).style.display='block';
  });
});

// Claim Income AJAX
$(document).ready(function(){
  $('.claim-btn').click(function(){
    var btn = $(this);
    var id = btn.data('id');

    btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Claiming...');

    $.ajax({
      url: "{{ route('user.mining.received_amount') }}",
      method: "POST",
      headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
      data: { purchase_id: id },
      success: function(res) {
        btn.prop('disabled', false).html('<i class="fa fa-hand-holding-dollar"></i> Claim Income');
        if (res.status) {
          showToast(res.success || "✅ Income claimed successfully!", "success");
          setTimeout(()=>location.reload(),1500);
        } else if (res.error && res.error.toLowerCase().includes("not add")) {
          showToast("⚠️ Income not added yet! Please wait 24h.", "warning");
        } else {
          showToast(res.error || "⚠️ You cannot claim yet!", "warning");
        }
      },
      error: function() {
        btn.prop('disabled', false).html('<i class="fa fa-hand-holding-dollar"></i> Claim Income');
        showToast("❌ Error: Server not responding. Try again later.", "error");
      }
    });
  });
});
</script>

</body>
</html>
