<?php
$PAGE_TITLE='Report Details';
require __DIR__.'/_layout.php';

$type   = $_GET['type']   ?? '';
$filter = $_GET['filter'] ?? '';
$sort   = $_GET['sort']   ?? '';

function sort_url($newSort){
  $qs = $_GET; $qs['sort'] = $newSort; return '?'.http_build_query($qs);
}
function sort_pills($current, $options){
  $out = '<div style="display:flex;gap:6px;flex-wrap:wrap;margin:10px 0 16px">';
  foreach($options as $val=>$label){
    $active = $current===$val ? 'active' : '';
    $out .= '<a href="'.htmlspecialchars(sort_url($val),ENT_QUOTES).'" class="sort-pill '.$active.'">'.htmlspecialchars($label,ENT_QUOTES).'</a>';
  }
  $out .= '</div>';
  return $out;
}
?>
<style>
.sort-pill{padding:7px 12px;border-radius:999px;background:#fff;border:1px solid #e2e8f0;color:#334155;font-size:12px;font-weight:600;text-decoration:none}
.sort-pill:hover{border-color:#c7d2fe;color:#4338ca}
.sort-pill.active{background:linear-gradient(135deg,#6366f1,#8b5cf6);color:#fff;border-color:transparent;box-shadow:0 4px 10px rgba(99,102,241,.3)}
</style>

<p style="margin-bottom:10px"><a href="reports.php" style="color:#6366f1;font-weight:600">← রিপোর্টে ফেরত</a></p>

<?php
// =========================================================================
// USER BALANCE DETAILS
// =========================================================================
if ($type === 'user_balance') {
  $order = 'u.balance DESC';
  switch ($sort) {
    case 'oldest':      $order = 'u.id ASC'; break;
    case 'newest':      $order = 'u.id DESC'; break;
    case 'balance_asc': $order = 'u.balance ASC'; break;
    case 'balance_desc':
    default:            $order = 'u.balance DESC'; $sort='balance_desc';
  }
  $rows = $pdo->query("SELECT u.id,u.name,u.email,u.phone,u.balance,u.total_recharge,u.created_at
                       FROM users u
                       WHERE u.role='user' AND u.balance>0
                       ORDER BY $order LIMIT 500")->fetchAll();
  $sum_bal = 0; $sum_rec = 0; foreach($rows as $r){ $sum_bal += (float)$r['balance']; $sum_rec += (float)$r['total_recharge']; }
  ?>
  <h2 style="margin-bottom:6px">💵 ইউজার ব্যালেন্স বিস্তারিত</h2>
  <p style="color:#64748b;margin-bottom:6px">যাদের ব্যালেন্স আছে (<?=count($rows)?> জন) — মোট ব্যালেন্স: <b><?=money($sum_bal)?></b> | মোট রিচার্জ: <b><?=money($sum_rec)?></b></p>
  <?=sort_pills($sort, [
    'oldest'=>'⏳ পুরাতন একাউন্ট আগে',
    'newest'=>'🆕 নতুন একাউন্ট আগে',
    'balance_desc'=>'💰 বেশি ব্যালেন্স আগে',
    'balance_asc'=>'💸 কম ব্যালেন্স আগে',
  ])?>
  <table>
    <thead><tr><th>#</th><th>নাম</th><th>ইমেইল</th><th>ফোন</th><th>রিচার্জ</th><th>বর্তমান ব্যালেন্স</th><th>জয়েন</th></tr></thead>
    <tbody>
    <?php $i=1; foreach($rows as $r): ?>
      <tr>
        <td><?=$i++?></td>
        <td><b><?=e($r['name'])?></b></td>
        <td><?=e($r['email'])?></td>
        <td><?=e($r['phone'])?></td>
        <td style="color:#10b981;font-weight:600"><?=money($r['total_recharge'])?></td>
        <td style="color:#2563eb;font-weight:700"><?=money($r['balance'])?></td>
        <td><?=e($r['created_at'])?></td>
      </tr>
    <?php endforeach; if(!$rows): ?>
      <tr><td colspan="7" style="text-align:center;padding:20px;color:#64748b">কোন ইউজারের ব্যালেন্স নেই</td></tr>
    <?php endif; ?>
    </tbody>
  </table>
<?php
}

// =========================================================================
// ALL USERS
// =========================================================================
elseif ($type === 'users') {
  $order = 'u.id DESC';
  switch ($sort) {
    case 'oldest':       $order = 'u.id ASC'; break;
    case 'recharge_desc':$order = 'u.total_recharge DESC'; break;
    case 'recharge_asc': $order = 'u.total_recharge ASC'; break;
    case 'newest':
    default:             $order = 'u.id DESC'; $sort='newest';
  }
  $rows = $pdo->query("SELECT u.id,u.name,u.email,u.phone,u.balance,u.total_recharge,u.created_at
                       FROM users u WHERE u.role='user' ORDER BY $order LIMIT 500")->fetchAll();
  ?>
  <h2 style="margin-bottom:6px">👥 সকল ইউজার (<?=count($rows)?>)</h2>
  <?=sort_pills($sort,[
    'newest'=>'🆕 নতুন আগে','oldest'=>'⏳ পুরাতন আগে',
    'recharge_desc'=>'💰 বেশি রিচার্জ আগে','recharge_asc'=>'💸 কম রিচার্জ আগে',
  ])?>
  <table>
    <thead><tr><th>#</th><th>নাম</th><th>ইমেইল</th><th>ফোন</th><th>রিচার্জ</th><th>ব্যালেন্স</th><th>জয়েন</th></tr></thead>
    <tbody>
    <?php $i=1; foreach($rows as $r): ?>
      <tr>
        <td><?=$i++?></td>
        <td><b><?=e($r['name'])?></b></td>
        <td><?=e($r['email'])?></td>
        <td><?=e($r['phone'])?></td>
        <td style="color:#10b981;font-weight:600"><?=money($r['total_recharge'])?></td>
        <td style="color:#2563eb;font-weight:700"><?=money($r['balance'])?></td>
        <td><?=e($r['created_at'])?></td>
      </tr>
    <?php endforeach; ?>
    </tbody>
  </table>
<?php
}

// =========================================================================
// RECHARGES
// =========================================================================
elseif ($type === 'recharges') {
  $status = in_array($filter,['approved','pending','rejected'],true) ? $filter : 'approved';
  $order = 'r.id DESC';
  switch ($sort) {
    case 'oldest':      $order = 'r.id ASC'; break;
    case 'amount_desc': $order = 'r.amount DESC'; break;
    case 'amount_asc':  $order = 'r.amount ASC'; break;
    case 'newest':
    default:            $order = 'r.id DESC'; $sort='newest';
  }
  $st = $pdo->prepare("SELECT r.*, u.name AS uname, u.email
                       FROM recharges r LEFT JOIN users u ON u.id=r.user_id
                       WHERE r.status=? ORDER BY $order LIMIT 500");
  $st->execute([$status]); $rows=$st->fetchAll();
  $sum = 0; foreach($rows as $r){ $sum += (float)$r['amount']; }
  $labels = ['approved'=>'Approved','pending'=>'Pending','rejected'=>'Rejected'];
  ?>
  <h2 style="margin-bottom:6px">💰 <?=$labels[$status]?> রিচার্জ (<?=count($rows)?>) — মোট <?=money($sum)?></h2>
  <?=sort_pills($sort,[
    'newest'=>'🆕 নতুন আগে','oldest'=>'⏳ পুরাতন আগে',
    'amount_desc'=>'⬆️ বেশি টাকা আগে','amount_asc'=>'⬇️ কম টাকা আগে',
  ])?>
  <table>
    <thead><tr><th>#</th><th>Date</th><th>User</th><th>Email</th><th>Amount</th><th>Method</th><th>Status</th></tr></thead>
    <tbody>
    <?php foreach($rows as $r): ?>
      <tr>
        <td>#<?=$r['id']?></td>
        <td><?=e($r['created_at'])?></td>
        <td><b><?=e($r['uname'])?></b></td>
        <td><?=e($r['email'])?></td>
        <td><b><?=money($r['amount'])?></b></td>
        <td><?=e($r['method']??'—')?></td>
        <td><span class="badge <?=$status==='approved'?'ok':($status==='pending'?'pending':'fail')?>"><?=e($r['status'])?></span></td>
      </tr>
    <?php endforeach; if(!$rows): ?>
      <tr><td colspan="7" style="text-align:center;padding:20px;color:#64748b">কোন রিচার্জ নেই</td></tr>
    <?php endif; ?>
    </tbody>
  </table>
<?php
}

// =========================================================================
// ORDERS
// =========================================================================
elseif ($type === 'orders') {
  $where = '1=1';
  switch ($filter) {
    case 'successful':    $where = "o.status IN ('completed','success')"; break;
    case 'pending':       $where = "o.status='pending'"; break;
    case 'failed':        $where = "o.status IN ('failed','rejected')"; break;
    case 'cancelled':     $where = "o.status IN ('cancelled','refund')"; break;
    case 'today':         $where = "DATE(o.created_at)=CURDATE()"; break;
    case 'month':         $where = "YEAR(o.created_at)=YEAR(CURDATE()) AND MONTH(o.created_at)=MONTH(CURDATE())"; break;
    case 'today_success': $where = "o.status IN ('completed','success') AND DATE(o.created_at)=CURDATE()"; break;
    case 'month_success': $where = "o.status IN ('completed','success') AND YEAR(o.created_at)=YEAR(CURDATE()) AND MONTH(o.created_at)=MONTH(CURDATE())"; break;
    case 'all':
    default:              $where = '1=1'; $filter='all';
  }
  $order = 'o.id DESC';
  switch ($sort) {
    case 'oldest':     $order = 'o.id ASC'; break;
    case 'price_desc': $order = 'o.price DESC'; break;
    case 'price_asc':  $order = 'o.price ASC'; break;
    case 'newest':
    default:           $order = 'o.id DESC'; $sort='newest';
  }
  $rows = $pdo->query("SELECT o.*, u.name AS uname, s.name AS sname
                       FROM orders o
                       LEFT JOIN users u ON u.id=o.user_id
                       LEFT JOIN services s ON s.id=o.service_id
                       WHERE $where
                       ORDER BY $order LIMIT 500")->fetchAll();
  $sum = 0; foreach($rows as $r){ $sum += (float)$r['price']; }
  $flabels = [
    'all'=>'সব অর্ডার','successful'=>'Successful অর্ডার','pending'=>'Pending অর্ডার',
    'failed'=>'Failed / Rejected','cancelled'=>'Cancelled','today'=>'আজকের অর্ডার','month'=>'এই মাসের অর্ডার',
    'today_success'=>'আজকের Revenue','month_success'=>'এই মাসের Revenue',
  ];
  ?>
  <h2 style="margin-bottom:6px">📦 <?=$flabels[$filter]?? 'অর্ডার'?> (<?=count($rows)?>) — মোট মূল্য <?=money($sum)?></h2>
  <?=sort_pills($sort,[
    'newest'=>'🆕 নতুন আগে','oldest'=>'⏳ পুরাতন আগে',
    'price_desc'=>'⬆️ বেশি মূল্য আগে','price_asc'=>'⬇️ কম মূল্য আগে',
  ])?>
  <table>
    <thead><tr><th>#</th><th>Date</th><th>User</th><th>Service</th><th>Info</th><th>Price</th><th>Status</th><th></th></tr></thead>
    <tbody>
    <?php foreach($rows as $r):
      $ok = in_array($r['status'],['completed','success'],true);
      $bad = in_array($r['status'],['failed','cancelled','refund','rejected'],true);
      $b = $ok?'ok':($bad?'fail':'pending'); ?>
      <tr>
        <td>#<?=$r['id']?></td>
        <td><?=e($r['created_at'])?></td>
        <td><b><?=e($r['uname'])?></b></td>
        <td><?=e($r['sname'])?></td>
        <td><?=e($r['nid']?:'—')?></td>
        <td><b><?=money($r['price'])?></b></td>
        <td><span class="badge <?=$b?>"><?=e($r['status'])?></span></td>
        <td><a class="btn sm" href="orders.php?view=<?=$r['id']?>">👁️</a></td>
      </tr>
    <?php endforeach; if(!$rows): ?>
      <tr><td colspan="8" style="text-align:center;padding:20px;color:#64748b">কোন অর্ডার নেই</td></tr>
    <?php endif; ?>
    </tbody>
  </table>
<?php
}
else {
  echo '<p style="color:#64748b">অবৈধ রিপোর্ট টাইপ।</p>';
}

require __DIR__.'/_footer.php';
