<?php
require_once 'db.php';
require_once 'auth_check.php';
require_once 'currency.php';

$uid = $user_id;

// ── Fetch Income records ──────────────────────────────────
// Income = task earnings + commissions received
$income_rows = $conn->query("
    SELECT 
        'task' as source,
        tc.earned as amount,
        tc.completed_at as created_at,
        CONCAT('Task Completed - ', p.name) as description
    FROM task_completions tc
    LEFT JOIN plans p ON p.id = tc.plan_id
    WHERE tc.user_id = $uid

    UNION ALL

    SELECT
        cl.type as source,
        cl.amount,
        cl.created_at,
        COALESCE(cl.description, IF(cl.type='referral','Referral Commission','Task Commission')) as description
    FROM commission_logs cl
    WHERE cl.user_id = $uid

    ORDER BY created_at DESC
    LIMIT 100
");
$income_list = [];
while ($r = $income_rows->fetch_assoc()) $income_list[] = $r;

// ── Fetch Expense records ─────────────────────────────────
// Expense = plan purchases
$expense_rows = $conn->query("
    SELECT
        'plan' as source,
        p.price as amount,
        up.joined_at as created_at,
        CONCAT('Plan Purchase - ', p.name) as description
    FROM user_plans up
    JOIN plans p ON p.id = up.plan_id
    WHERE up.user_id = $uid AND p.is_free = 0
    ORDER BY up.joined_at DESC
    LIMIT 100
");
$expense_list = [];
while ($r = $expense_rows->fetch_assoc()) $expense_list[] = $r;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<title>WFM - Income Record</title>
<style>
*{margin:0;padding:0;box-sizing:border-box}
body{
  font-family:'Segoe UI',sans-serif;
  background:linear-gradient(160deg,#b8cba8 0%,#a8bc96 40%,#8faa7a 100%);
  min-height:100vh;
  padding-bottom:80px
}

/* ── Top Bar ── */
.top-bar{
  background:rgba(255,255,255,.45);
  backdrop-filter:blur(8px);
  padding:14px 16px;
  display:flex;align-items:center;justify-content:space-between;
  border-bottom:1px solid rgba(255,255,255,.3)
}
.back-btn{
  width:36px;height:36px;
  background:rgba(255,255,255,.6);
  border-radius:50%;
  display:flex;align-items:center;justify-content:center;
  text-decoration:none
}
.back-btn svg{width:20px;height:20px;fill:#1a2a0a}
.top-bar h1{font-size:17px;font-weight:700;color:#1a2a0a;flex:1;text-align:center}
.top-bar-right{width:36px}

/* ── Tab Bar ── */
.tab-bar{
  background:#0d1b2a;
  display:flex;
  position:sticky;top:0;
  z-index:100
}
.tab-btn{
  flex:1;
  padding:16px 0;
  font-size:15px;
  font-weight:600;
  color:#7a8fa8;
  text-align:center;
  border:none;
  background:none;
  cursor:pointer;
  font-family:inherit;
  position:relative;
  transition:color .2s
}
.tab-btn.active{color:#4da8da}
.tab-btn.active::after{
  content:'';
  position:absolute;
  bottom:0;left:50%;
  transform:translateX(-50%);
  width:40px;height:3px;
  background:#4da8da;
  border-radius:2px 2px 0 0
}

/* ── Tab Content ── */
.tab-content{display:none}
.tab-content.active{display:block}

/* ── Empty State ── */
.empty-state{
  display:flex;
  flex-direction:column;
  align-items:center;
  justify-content:center;
  padding:80px 20px;
  gap:16px
}
.empty-icon{
  width:72px;height:72px;
  background:rgba(255,255,255,.3);
  border-radius:50%;
  display:flex;align-items:center;justify-content:center
}
.empty-icon svg{width:38px;height:38px;fill:rgba(255,255,255,.6)}
.empty-text{font-size:14px;color:rgba(255,255,255,.7);font-weight:500}

/* ── Record List ── */
.record-list{padding:10px 12px;display:flex;flex-direction:column;gap:8px}

.record-card{
  background:#fff;
  border-radius:14px;
  padding:14px 16px;
  display:flex;
  align-items:center;
  gap:12px
}
.record-icon{
  width:42px;height:42px;
  border-radius:12px;
  display:flex;align-items:center;justify-content:center;
  flex-shrink:0;font-size:18px
}
.record-icon.task{background:#e8f5e9}
.record-icon.referral{background:#e3f2fd}
.record-icon.commission{background:#fff8e1}
.record-icon.plan{background:#fce4ec}

.record-info{flex:1;min-width:0}
.record-desc{
  font-size:13px;font-weight:600;color:#1a2a0a;
  white-space:nowrap;overflow:hidden;text-overflow:ellipsis;
  margin-bottom:4px
}
.record-date{font-size:11px;color:#999;font-weight:400}

.record-amount{
  font-size:16px;font-weight:800;
  white-space:nowrap
}
.record-amount.income{color:#27ae60}
.record-amount.expense{color:#e74c3c}

/* ── Bottom Nav ── */
.bottom-nav{
  position:fixed;bottom:0;left:0;right:0;height:64px;
  background:#fff;border-top:1px solid #e0e0e0;
  display:flex;align-items:center;justify-content:space-around;z-index:1000
}
.bn-item{
  display:flex;flex-direction:column;align-items:center;
  gap:3px;text-decoration:none;flex:1;padding:6px 0
}
.bn-item .bn-icon{
  width:26px;height:26px;
  background-size:contain;background-repeat:no-repeat;background-position:center
}
.bn-item span{font-size:10px;font-weight:600}
.bn-item.active span{color:#3eaabb}
.bn-item:not(.active) span{color:#aaa}

/* Float Service */
.float-service{
  position:fixed;bottom:80px;right:10px;
  display:flex;flex-direction:column;align-items:center;
  z-index:999;text-decoration:none
}
.float-service img{width:55px;height:55px;border-radius:50%;object-fit:cover}
.float-service span{font-size:10px;color:#3a5a2a;font-weight:600;text-align:center;margin-top:2px}
</style>
</head>
<body>

<!-- Top Bar -->
<div class="top-bar">
  <a href="account.php" class="back-btn">
    <svg viewBox="0 0 24 24"><path d="M15.41 16.59L10.83 12l4.58-4.59L14 6l-6 6 6 6z"/></svg>
  </a>
  <h1>Income Record</h1>
  <div class="top-bar-right"></div>
</div>

<!-- Tab Bar -->
<div class="tab-bar">
  <button class="tab-btn active" onclick="switchTab('income')">Income</button>
  <button class="tab-btn" onclick="switchTab('expense')">Expense</button>
</div>

<!-- Income Tab -->
<div class="tab-content active" id="tab-income">
  <?php if (empty($income_list)): ?>
    <div class="empty-state">
      <div class="empty-icon">
        <svg viewBox="0 0 24 24"><path d="M11.8 10.9c-2.27-.59-3-1.2-3-2.15 0-1.09 1.01-1.85 2.7-1.85 1.78 0 2.44.85 2.5 2.1h2.21c-.07-1.72-1.12-3.3-3.21-3.81V3h-3v2.16c-1.94.42-3.5 1.68-3.5 3.61 0 2.31 1.91 3.46 4.7 4.13 2.5.6 3 1.48 3 2.41 0 .69-.49 1.79-2.7 1.79-2.06 0-2.87-.92-2.98-2.1h-2.2c.12 2.19 1.76 3.42 3.68 3.83V21h3v-2.15c1.95-.37 3.5-1.5 3.5-3.55 0-2.84-2.43-3.81-4.7-4.4z"/></svg>
      </div>
      <span class="empty-text">No income records yet</span>
    </div>
  <?php else: ?>
    <div class="record-list">
      <?php foreach ($income_list as $r):
        $icon = $r['source'] === 'task' ? '✅' : ($r['source'] === 'referral' ? '👥' : '💰');
        $iconClass = $r['source'] === 'task' ? 'task' : ($r['source'] === 'referral' ? 'referral' : 'commission');
        $dt = date('d M Y, H:i', strtotime($r['created_at']));
      ?>
      <div class="record-card">
        <div class="record-icon <?= $iconClass ?>"><?= $icon ?></div>
        <div class="record-info">
          <div class="record-desc"><?= htmlspecialchars($r['description']) ?></div>
          <div class="record-date"><?= $dt ?></div>
        </div>
        <div class="record-amount income">+<?= number_format((float)$r['amount'], 3) ?> <?= $currency ?></div>
      </div>
      <?php endforeach; ?>
    </div>
  <?php endif; ?>
</div>

<!-- Expense Tab -->
<div class="tab-content" id="tab-expense">
  <?php if (empty($expense_list)): ?>
    <div class="empty-state">
      <div class="empty-icon">
        <svg viewBox="0 0 24 24"><path d="M20 4H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V6c0-1.11-.89-2-2-2zm0 14H4v-6h16v6zm0-10H4V6h16v2z"/></svg>
      </div>
      <span class="empty-text">No expense records yet</span>
    </div>
  <?php else: ?>
    <div class="record-list">
      <?php foreach ($expense_list as $r):
        $dt = date('d M Y, H:i', strtotime($r['created_at']));
      ?>
      <div class="record-card">
        <div class="record-icon plan">📦</div>
        <div class="record-info">
          <div class="record-desc"><?= htmlspecialchars($r['description']) ?></div>
          <div class="record-date"><?= $dt ?></div>
        </div>
        <div class="record-amount expense">-<?= number_format((float)$r['amount'], 3) ?> <?= $currency ?></div>
      </div>
      <?php endforeach; ?>
    </div>
  <?php endif; ?>
</div>

<!-- Float Service -->
<a href="#" target="_blank" class="float-service">
  <img src="https://api.wfmtr.me/static/api/images/icon/service.png" alt="" onerror="this.src='care.png'">
  <span>Online Service</span>
</a>

<!-- Bottom Nav -->
<?php include 'navigation_bottom.php'; ?>
<script>
function switchTab(tab) {
  document.querySelectorAll('.tab-btn').forEach((b,i) => {
    b.classList.toggle('active', (i===0 && tab==='income') || (i===1 && tab==='expense'));
  });
  document.getElementById('tab-income').classList.toggle('active', tab==='income');
  document.getElementById('tab-expense').classList.toggle('active', tab==='expense');
}
</script>
</body>
</html>