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

$uid = $user_id;

// ── Today's summary stats ─────────────────────────────────
$today = date('Y-m-d');

// My tasks completed today
$my_tasks_today = (int)($conn->query("
    SELECT COUNT(*) as c FROM task_completions
    WHERE user_id=$uid AND DATE(completed_at)=CURDATE()
")->fetch_assoc()['c'] ?? 0);

// My task earnings today
$my_earnings_today = (float)($conn->query("
    SELECT COALESCE(SUM(earned),0) as s FROM task_completions
    WHERE user_id=$uid AND DATE(completed_at)=CURDATE()
")->fetch_assoc()['s'] ?? 0);

// Subordinate tasks completed today (downliners level 1-3)
$sub_tasks_today = (int)($conn->query("
    SELECT COUNT(*) as c FROM task_completions tc
    INNER JOIN users u ON u.id = tc.user_id
    WHERE u.referred_by = $uid AND DATE(tc.completed_at)=CURDATE()
")->fetch_assoc()['c'] ?? 0);

// Subordinate task earnings today (commission from downliners)
$sub_earn_today = (float)($conn->query("
    SELECT COALESCE(SUM(amount),0) as s FROM commission_logs
    WHERE user_id=$uid AND type='task' AND DATE(created_at)=CURDATE()
")->fetch_assoc()['s'] ?? 0);

$total_earnings_today = $my_earnings_today + $sub_earn_today;

// ── Last 30 days report ───────────────────────────────────
$rows = [];
for ($i = 0; $i < 30; $i++) {
    $d = date('Y-m-d', strtotime("-$i days"));
    $label = date('d-m', strtotime($d));

    // New referrals (additions)
    $new_add = (int)($conn->query("
        SELECT COUNT(*) as c FROM users
        WHERE referred_by=$uid AND DATE(created_at)='$d'
    ")->fetch_assoc()['c'] ?? 0);

    // Deposits — plan purchases on that day
    $deposits = (float)($conn->query("
        SELECT COALESCE(SUM(p.price),0) as s
        FROM user_plans up
        JOIN plans p ON p.id = up.plan_id
        WHERE up.user_id=$uid AND DATE(up.joined_at)='$d' AND p.is_free=0
    ")->fetch_assoc()['s'] ?? 0);

    // Withdrawals — 0 until withdrawals table exists
    $withdrawals = 0.000;

    // Rebates (task earnings)
    $rebates = (float)($conn->query("
        SELECT COALESCE(SUM(earned),0) as s FROM task_completions
        WHERE user_id=$uid AND DATE(completed_at)='$d'
    ")->fetch_assoc()['s'] ?? 0);

    // Commission (from downliners)
    $commission = (float)($conn->query("
        SELECT COALESCE(SUM(amount),0) as s FROM commission_logs
        WHERE user_id=$uid AND DATE(created_at)='$d'
    ")->fetch_assoc()['s'] ?? 0);

    // Total tasks for the user's active plan on that day
    // Use the active plan's daily_tasks as total
    $total_tasks = 0;
    $plan_row = $conn->query("
        SELECT p.daily_tasks FROM user_plans up
        JOIN plans p ON p.id = up.plan_id
        WHERE up.user_id=$uid AND up.active=1
        ORDER BY up.id DESC LIMIT 1
    ")->fetch_assoc();
    if ($plan_row) $total_tasks = (int)$plan_row['daily_tasks'];

    // Completed tasks that day
    $completed = (int)($conn->query("
        SELECT COUNT(*) as c FROM task_completions
        WHERE user_id=$uid AND DATE(completed_at)='$d'
    ")->fetch_assoc()['c'] ?? 0);

    $remaining = max(0, $total_tasks - $completed);

    // Lucky draw (placeholder - 0 if no lucky_draw table)
    $lucky = 0.000;

    // Lucky sign-in (placeholder)
    $signin = 0.000;

    $rows[] = [
        'date'       => $label,
        'new_add'    => $new_add,
        'deposits'   => $deposits,
        'withdrawals'=> $withdrawals,
        'rebates'    => $rebates,
        'commission' => $commission,
        'total_tasks'=> $total_tasks,
        'completed'  => $completed,
        'remaining'  => $remaining,
        'lucky'      => $lucky,
        'signin'     => $signin,
    ];
}
?>
<!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 - Daily Settlement Report</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}

/* ── Summary Header Strip ── */
.summary-strip{
  background:rgba(255,255,255,.35);
  padding:10px 16px;
  display:flex;
  justify-content:space-between;
  align-items:center;
  font-size:13px;
  color:#2a3a1a;
  font-weight:500
}
.summary-strip .total-earn{display:flex;align-items:center;gap:6px}
.summary-strip .total-earn svg{width:16px;height:16px;fill:#5a7a3a}

/* ── 2x2 Stats Grid ── */
.stats-2x2{
  margin:0;
  display:grid;
  grid-template-columns:1fr 1fr;
  border:1px solid #d0d8c8;
  background:#fff
}
.stat-cell{
  padding:18px 12px;
  text-align:center;
  border-right:1px solid #d0d8c8;
  border-bottom:1px solid #d0d8c8
}
.stat-cell:nth-child(2){border-right:none}
.stat-cell:nth-child(3){border-right:1px solid #d0d8c8;border-bottom:none}
.stat-cell:nth-child(4){border-right:none;border-bottom:none}
.stat-label{font-size:13px;font-weight:600;color:#222;margin-bottom:10px;line-height:1.4}
.stat-value{font-size:24px;font-weight:800;color:#3a8fc8}

/* ── Section Header ── */
.section-header{
  background:rgba(255,255,255,.35);
  padding:10px 16px;
  display:flex;
  justify-content:space-between;
  align-items:center;
  font-size:13px;
  color:#2a3a1a;
  font-weight:500
}
.section-header svg{width:15px;height:15px;fill:#5a7a3a;margin-right:5px;vertical-align:middle}

/* ── Scrollable Table Wrapper ── */
.table-wrapper{
  overflow-x:auto;
  background:#fff;
  -webkit-overflow-scrolling:touch
}
.report-table{
  border-collapse:collapse;
  width:max-content;
  min-width:100%
}
.report-table th{
  background:#f5f8f2;
  font-size:11px;
  font-weight:700;
  color:#333;
  padding:10px 8px;
  text-align:center;
  border:1px solid #e0e8d8;
  white-space:normal;
  word-break:break-word;
  min-width:72px;
  line-height:1.3
}
.report-table th:first-child{
  position:sticky;left:0;
  background:#f5f8f2;
  z-index:2;
  min-width:60px
}
.report-table td{
  font-size:12px;
  font-weight:600;
  padding:10px 8px;
  text-align:center;
  border:1px solid #eef2ea;
  white-space:nowrap
}
.report-table td:first-child{
  position:sticky;left:0;
  background:#fff;
  z-index:1;
  color:#d4870a;
  font-weight:700
}
.report-table tr:nth-child(even) td{background:#fafcf8}
.report-table tr:nth-child(even) td:first-child{background:#fafcf8}

/* Column value colors matching screenshot */
.col-additions{color:#e67e22}
.col-deposits{color:#e74c3c}
.col-withdrawals{color:#27ae60}
.col-rebates{color:#27ae60}
.col-commission{color:#e74c3c}
.col-total{color:#e67e22}
.col-completed{color:#27ae60}
.col-remaining{color:#e67e22}
.col-lucky{color:#e67e22}
.col-signin{color:#3a8fc8}

/* ── 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>Daily Settlement Report</h1>
  <div class="top-bar-right"></div>
</div>

<!-- Summary strip -->
<div class="summary-strip">
  <span class="total-earn">
    <svg viewBox="0 0 24 24"><path d="M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z"/></svg>
    Total Earnings<?= number_format($total_earnings_today, 3) ?><?= $currency ?>
  </span>
  <span><?= date('d-m-Y') ?></span>
</div>

<!-- 2×2 Stats -->
<div class="stats-2x2">
  <div class="stat-cell">
    <div class="stat-label">Tasks Completed by Me(Single)</div>
    <div class="stat-value"><?= $my_tasks_today ?></div>
  </div>
  <div class="stat-cell">
    <div class="stat-label">My Task Earnings (<?= $currency ?>)</div>
    <div class="stat-value"><?= number_format($my_earnings_today, 3) ?></div>
  </div>
  <div class="stat-cell">
    <div class="stat-label">Subordinate Tasks Completed(Single)</div>
    <div class="stat-value"><?= $sub_tasks_today ?></div>
  </div>
  <div class="stat-cell">
    <div class="stat-label">Subordinate Task Earnings(<?= $currency ?>)</div>
    <div class="stat-value"><?= number_format($sub_earn_today, 3) ?></div>
  </div>
</div>

<!-- Section label -->
<div class="section-header">
  <span>
    <svg viewBox="0 0 24 24"><path d="M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z"/></svg>
    Daily Settlement Report
  </span>
  <span>Last 30 Days</span>
</div>

<!-- Scrollable Table -->
<div class="table-wrapper">
  <table class="report-table">
    <thead>
      <tr>
        <th>Date</th>
        <th>New Additions</th>
        <th>Deposits</th>
        <th>Withdrawals</th>
        <th>Rebates</th>
        <th>Commission</th>
        <th>Total Number of Tasks</th>
        <th>Completed Tasks</th>
        <th>Remaining Task Quantity</th>
        <th>Lucky Draw</th>
        <th>Lucky Sign-in</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($rows as $r): ?>
      <tr>
        <td><?= htmlspecialchars($r['date']) ?></td>
        <td class="col-additions"><?= $r['new_add'] ?></td>
        <td class="col-deposits"><?= number_format($r['deposits'], 3) ?></td>
        <td class="col-withdrawals"><?= number_format($r['withdrawals'], 3) ?></td>
        <td class="col-rebates"><?= number_format($r['rebates'], 3) ?></td>
        <td class="col-commission"><?= number_format($r['commission'], 3) ?></td>
        <td class="col-total"><?= $r['total_tasks'] ?></td>
        <td class="col-completed"><?= $r['completed'] ?></td>
        <td class="col-remaining"><?= $r['remaining'] ?></td>
        <td class="col-lucky"><?= number_format($r['lucky'], 3) ?></td>
        <td class="col-signin"><?= number_format($r['signin'], 3) ?></td>
      </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</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'; ?>

</body>
</html>