<?php
require_once __DIR__.'/../config/config.php';
require_user();
$U = current_user();

if (isset($_GET['del'])) {
    $pdo->prepare("DELETE FROM orders WHERE id=? AND user_id=?")->execute([(int)$_GET['del'], $U['id']]);
    redirect('history.php');
}

$PAGE_TITLE='History'; require __DIR__.'/_layout.php';
$rows = $pdo->prepare("SELECT o.*, s.name AS sname, s.kind AS skind
                       FROM orders o
                       LEFT JOIN services s ON s.id=o.service_id
                       WHERE o.user_id=?
                       ORDER BY o.id DESC");
$rows->execute([$U['id']]);
$rows = $rows->fetchAll();
?>
<h2 style="margin-bottom:14px">📜 হিস্টোরি</h2>
<table><thead><tr><th>#</th><th>তারিখ</th><th>সার্ভিস</th><th>ইনফো</th><th>মূল্য</th><th>স্ট্যাটাস</th><th>এ্যাকশন</th></tr></thead><tbody>
<?php foreach($rows as $r):
  $st = $r['status'];
  $ok = in_array($st,['completed','success'],true);
  $bad = in_array($st,['failed','cancelled','refund'],true);
?>
<tr>
  <td>#<?=$r['id']?></td>
  <td><?=e($r['created_at'])?></td>
  <td><?=e($r['sname'])?></td>
  <td><?=e($r['nid']?:'—')?></td>
  <td><?=$r['cached']?'<span class=badge>Free</span>':money($r['price'])?></td>
  <td><span class="badge <?=$ok?'ok':($bad?'fail':'')?>"><?=e($st)?></span></td>
  <td>
    <?php if(($r['skind']??'')==='api' && $st==='success'): ?>
      <a class="btn sm" href="download.php?id=<?=$r['id']?>">📥</a>
    <?php else: ?>
      <a class="btn sm" href="order_view.php?id=<?=$r['id']?>">👁️</a>
    <?php endif; ?>
    <a class="btn sm danger" href="?del=<?=$r['id']?>" onclick="return confirm('Delete?')">🗑️</a>
  </td>
</tr>
<?php endforeach;?>
<?php if(!$rows):?><tr><td colspan="7" style="text-align:center;color:#64748b">কোনো ডাটা নেই</td></tr><?php endif;?>
</tbody></table>
<?php require __DIR__.'/_footer.php';
