<?php
require_once __DIR__ . '/../auth_helper.php';
require_admin();
$msg=''; $err='';
try {
 if ($_SERVER['REQUEST_METHOD']==='POST') {
   $a=$_POST['admin_action'] ?? '';
   if ($a==='logout') { unset($_SESSION['admin_ok']); redirect('login.php'); }
   if ($a==='save_announcement') { set_setting('announcement',(string)($_POST['announcement'] ?? '')); $msg='Announcement saved.'; }
   if ($a==='save_rules') { set_setting('withdraw_min',(string)($_POST['withdraw_min'] ?? '500')); set_setting('withdraw_max',(string)($_POST['withdraw_max'] ?? '25000')); set_setting('withdraw_fee',(string)($_POST['withdraw_fee'] ?? '0')); $msg='Withdraw rules saved.'; }
   if ($a==='deposit_decision') {
      $id=(string)($_POST['request_id'] ?? ''); $decision=(string)($_POST['decision'] ?? ''); $note=trim((string)($_POST['admin_note'] ?? ''));
      pdo()->beginTransaction();
      $st=pdo()->prepare("SELECT * FROM deposit_requests WHERE id=? AND status='pending' FOR UPDATE"); $st->execute([$id]); $r=$st->fetch();
      if(!$r) throw new Exception('Deposit request not found or already reviewed.');
      if($decision==='approve'){
        pdo()->prepare('UPDATE users SET balance=balance+? WHERE id=?')->execute([$r['amount'],$r['user_id']]);
        pdo()->prepare("UPDATE deposit_requests SET status='approved',admin_note=?,reviewed_at=? WHERE id=?")->execute([$note,now_sql(),$id]);
        addTransaction($r['user_id'],'deposit_approved',(float)$r['amount'],'success','Deposit approved by admin. '.$note);
        $msg='Deposit approved and balance added.';
      } else {
        pdo()->prepare("UPDATE deposit_requests SET status='rejected',admin_note=?,reviewed_at=? WHERE id=?")->execute([$note,now_sql(),$id]);
        addTransaction($r['user_id'],'deposit_rejected',(float)$r['amount'],'rejected','Deposit rejected. '.$note);
        $msg='Deposit rejected.';
      }
      pdo()->commit();
   }
   if ($a==='withdraw_decision') {
      $id=(string)($_POST['request_id'] ?? ''); $decision=(string)($_POST['decision'] ?? ''); $note=trim((string)($_POST['admin_note'] ?? ''));
      pdo()->beginTransaction();
      $st=pdo()->prepare("SELECT * FROM withdraw_requests WHERE id=? AND status='pending' FOR UPDATE"); $st->execute([$id]); $r=$st->fetch();
      if(!$r) throw new Exception('Withdraw request not found or already reviewed.');
      if($decision==='approve'){
        pdo()->prepare("UPDATE withdraw_requests SET status='approved',admin_note=?,reviewed_at=? WHERE id=?")->execute([$note,now_sql(),$id]);
        addTransaction($r['user_id'],'withdraw_approved',(float)$r['amount'],'success','Withdraw paid by admin. '.$note);
        $msg='Withdraw approved. Balance was already deducted when user requested.';
      } else {
        pdo()->prepare('UPDATE users SET balance=balance+? WHERE id=?')->execute([$r['amount'],$r['user_id']]);
        pdo()->prepare("UPDATE withdraw_requests SET status='rejected',admin_note=?,reviewed_at=? WHERE id=?")->execute([$note,now_sql(),$id]);
        addTransaction($r['user_id'],'withdraw_refund',(float)$r['amount'],'success','Withdraw rejected and refunded. '.$note);
        $msg='Withdraw rejected and refunded.';
      }
      pdo()->commit();
   }
   if ($a==='add_payment') {
      $st=pdo()->prepare('INSERT INTO payment_methods(country_code,method_key,label,provider,wallet_number,instructions,active,sort_order,created_at) VALUES(?,?,?,?,?,?,?,?,?)');
      $st->execute([$_POST['country_code'],trim($_POST['method_key']),trim($_POST['label']),trim($_POST['provider']),trim($_POST['wallet_number']),trim($_POST['instructions']),(int)!empty($_POST['active']),(int)($_POST['sort_order'] ?? 0),now_sql()]);
      $msg='Payment method added.';
   }
   if ($a==='delete_payment') { pdo()->prepare('DELETE FROM payment_methods WHERE id=?')->execute([(int)$_POST['id']]); $msg='Payment method deleted.'; }
   if ($a==='add_game') {
      $st=pdo()->prepare('INSERT INTO games(title,icon,provider,category,image_url,game_url,is_hot,active,sort_order,created_at) VALUES(?,?,?,?,?,?,?,?,?,?)');
      $st->execute([trim($_POST['title']),trim($_POST['icon'] ?: '🎮'),trim($_POST['provider']),trim($_POST['category']),trim($_POST['image_url']),trim($_POST['game_url']),(int)!empty($_POST['is_hot']),(int)!empty($_POST['active']),(int)($_POST['sort_order'] ?? 100),now_sql()]);
      $msg='Game added.';
   }
   if ($a==='delete_game') { pdo()->prepare('DELETE FROM games WHERE id=?')->execute([(int)$_POST['id']]); $msg='Game deleted.'; }
 }
} catch (Throwable $e) { if(pdo()->inTransaction()) pdo()->rollBack(); $err=$e->getMessage(); }
$settings=all_settings();
$depPending=get_deposit_requests('pending'); $wPending=get_withdraw_requests('pending'); $completedDep = []; foreach (get_deposit_requests('all') as $r) { if (($r['status'] ?? '') !== 'pending') $completedDep[] = $r; } $completedW = []; foreach (get_withdraw_requests('all') as $r) { if (($r['status'] ?? '') !== 'pending') $completedW[] = $r; }
$usersCount=(int)pdo()->query('SELECT COUNT(*) FROM users')->fetchColumn(); $depCount=count($depPending); $wCount=count($wPending); $balSum=(float)pdo()->query('SELECT COALESCE(SUM(balance),0) FROM users')->fetchColumn();
$methods=pdo()->query('SELECT * FROM payment_methods ORDER BY country_code, sort_order, id')->fetchAll(); $games=pdo()->query('SELECT * FROM games ORDER BY sort_order,id')->fetchAll(); $users=latest_users(120);
function admin_request_card(array $r,string $type): void { $isD=$type==='deposit'; ?>
 <div class="admin-req pending"><div class="admin-req-top"><div><b><?= e($isD?($r['phone']??$r['user_id']):($r['phone']??$r['user_id'])) ?></b><br><small><?= e($isD?($r['phone']??''):($r['phone']??'')) ?> · <?= e($r['country_name'] ?? $r['country_code']) ?></small></div><span class="status status-pending">pending</span></div><div class="admin-req-meta"><?php if($isD): ?><b>Amount:</b> <?= e(money($r['amount'])) ?><br><b>Method:</b> <?= e($r['method_label']) ?><br><b>Wallet:</b> <?= e($r['wallet_number']) ?><br><b>TrxID:</b> <?= e($r['trxid']) ?><br><?php else: ?><b>Amount:</b> <?= e(money($r['amount'])) ?><br><b>Method:</b> <?= e($r['method_label']) ?><br><b>Name:</b> <?= e($r['full_name']) ?><br><b>Account:</b> <?= e($r['account_number']) ?><br><?php endif; ?><b>Created:</b> <?= e($r['created_at']) ?></div><form method="post" class="admin-action-form"><input type="hidden" name="admin_action" value="<?= $isD?'deposit_decision':'withdraw_decision' ?>"><input type="hidden" name="request_id" value="<?= e($r['id']) ?>"><input class="admin-fld" name="admin_note" placeholder="Admin note / reason"><div class="admin-btn-row"><button class="approve-btn" name="decision" value="approve">Approve</button><button class="reject-btn" name="decision" value="reject">Reject</button></div></form></div>
<?php }
?><!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>Admin - CK444.COM</title><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"><link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800;900&family=Barlow+Condensed:wght@700;800;900&display=swap" rel="stylesheet"><link rel="stylesheet" href="../assets/index_theme.css?v=22"></head><body>
<div class="page active admin-page"><div class="admin-wrap"><div class="admin-top"><div><div class="admin-title">CK444.COM ADMIN</div><div class="tiny">Desktop + phone optimized control panel</div></div><form method="post"><input type="hidden" name="admin_action" value="logout"><button class="mini-btn">Logout</button></form></div><?php if($msg): ?><div class="msg"><?= e($msg) ?></div><?php endif; ?><?php if($err): ?><div class="msg err"><?= e($err) ?></div><?php endif; ?>
<div class="stat-grid"><div class="stat-card"><b><?= $usersCount ?></b><span>Users</span></div><div class="stat-card"><b><?= $depCount ?></b><span>Deposit Pending</span></div><div class="stat-card"><b><?= $wCount ?></b><span>Withdraw Pending</span></div><div class="stat-card"><b><?= e(money($balSum)) ?></b><span>User Balance</span></div></div>
<div class="admin-tabs"><button class="admin-tab on" onclick="Adm.tab('pending',this)">Pending Requests</button><button class="admin-tab" onclick="Adm.tab('completed',this)">Completed / Rejected</button><button class="admin-tab" onclick="Adm.tab('users',this)">Users</button><button class="admin-tab" onclick="Adm.tab('payment',this)">Payment Methods</button><button class="admin-tab" onclick="Adm.tab('settings',this)">Games & Settings</button><a class="admin-tab" href="../index.php">Open Site</a></div>
<div id="panel-pending" class="admin-panel on"><div class="admin-grid-two"><section class="admin-card2"><h3>Deposit Requests</h3><?php if(!$depPending): ?><p class="text-muted">No pending deposit request.</p><?php endif; ?><?php foreach($depPending as $r) admin_request_card($r,'deposit'); ?></section><section class="admin-card2"><h3>Withdraw Requests</h3><?php if(!$wPending): ?><p class="text-muted">No pending withdraw request.</p><?php endif; ?><?php foreach($wPending as $r) admin_request_card($r,'withdraw'); ?></section></div></div>
<div id="panel-completed" class="admin-panel"><section class="admin-card2"><h3>Completed / Rejected Deposit + Withdraw</h3><div style="overflow:auto"><table class="admin-table"><tr><th>Type</th><th>User</th><th>Amount</th><th>Method</th><th>Status</th><th>Reviewed</th></tr><?php foreach($completedDep as $r): ?><tr><td>Deposit</td><td><?= e($r['phone'] ?? $r['user_id']) ?></td><td><?= e(money($r['amount'])) ?></td><td><?= e($r['method_label']) ?><br><small><?= e($r['trxid']) ?></small></td><td><span class="status status-<?= e($r['status']) ?>"><?= e($r['status']) ?></span></td><td><?= e($r['reviewed_at']) ?><br><small><?= e($r['admin_note']) ?></small></td></tr><?php endforeach; ?><?php foreach($completedW as $r): ?><tr><td>Withdraw</td><td><?= e($r['phone'] ?? $r['user_id']) ?></td><td><?= e(money($r['amount'])) ?></td><td><?= e($r['method_label']) ?><br><small><?= e($r['account_number']) ?></small></td><td><span class="status status-<?= e($r['status']) ?>"><?= e($r['status']) ?></span></td><td><?= e($r['reviewed_at']) ?><br><small><?= e($r['admin_note']) ?></small></td></tr><?php endforeach; ?></table></div></section></div>
<div id="panel-users" class="admin-panel"><section class="admin-card2"><h3>Users — click to see full info</h3><div class="user-cards-admin"><?php foreach($users as $u): $s=user_admin_summary($u['id']); ?><details class="user-detail"><summary><span><b><?= e($u['phone']) ?></b><small><?= e($u['country_name']) ?> · <?= e($u['status']) ?></small></span><strong><?= e(money($u['balance'])) ?></strong></summary><div class="user-detail-grid"><p><b>UID:</b> <?= e($u['phone']) ?></p><p><b>Phone:</b> <?= e($u['phone']) ?></p><p><b>Email:</b> <?= e($u['email'] ?? '') ?></p><p><b>Country:</b> <?= e($u['country_name']) ?> (<?= e($u['country_code']) ?> / <?= e($u['dial_code']) ?>)</p><p><b>Balance:</b> <?= e(money($u['balance'])) ?></p><p><b>Bonus:</b> <?= e(money($u['bonus'])) ?></p><p><b>Safe Income:</b> <?= e(money($u['safe_income'])) ?></p><p><b>Referral Code:</b> <?= e($u['referral_code']) ?></p><p><b>Invite Code:</b> <?= e($u['invite_code']) ?></p><p><b>Created:</b> <?= e($u['created_at']) ?></p><p><b>Last Login:</b> <?= e($u['last_login']) ?></p><p><b>Transactions:</b> <?= (int)$s['tx'] ?></p><p><b>Pending Deposit:</b> <?= (int)$s['deposit_pending'] ?></p><p><b>Pending Withdraw:</b> <?= (int)$s['withdraw_pending'] ?></p><p><b>Approved Deposits:</b> <?= e(money($s['deposit_total'])) ?></p><p><b>Approved Withdraw:</b> <?= e(money($s['withdraw_total'])) ?></p></div></details><?php endforeach; ?></div></section></div>
<div id="panel-payment" class="admin-panel"><div class="admin-grid-two"><section class="admin-card2"><h3>Add Payment Method</h3><form method="post"><input type="hidden" name="admin_action" value="add_payment"><div class="form-row"><label>Country</label><select name="country_code"><option value="BD">Bangladesh</option><option value="PK">Pakistan</option></select></div><div class="select-inline"><div class="form-row"><label>Method Key</label><input name="method_key" placeholder="bkash / easypaisa" required></div><div class="form-row"><label>Label</label><input name="label" placeholder="bKash Personal" required></div></div><div class="select-inline"><div class="form-row"><label>Provider</label><input name="provider" placeholder="bKash / JazzCash"></div><div class="form-row"><label>Sort</label><input name="sort_order" type="number" value="10"></div></div><div class="form-row"><label>Wallet / Account Number</label><input name="wallet_number" required></div><div class="form-row"><label>Instructions</label><textarea name="instructions"></textarea></div><label class="tiny"><input type="checkbox" name="active" checked> Active</label><button class="full-btn" style="margin-top:12px">Add Method</button></form></section><section class="admin-card2"><h3>Current Methods</h3><?php foreach($methods as $m): ?><div class="admin-req"><div class="admin-req-top"><div><b><?= e($m['label']) ?></b><br><small><?= e($m['country_code']) ?> · <?= e($m['wallet_number']) ?></small></div><form method="post"><input type="hidden" name="admin_action" value="delete_payment"><input type="hidden" name="id" value="<?= (int)$m['id'] ?>"><button class="reject-btn" onclick="return confirm('Delete method?')">Delete</button></form></div></div><?php endforeach; ?></section></div></div>
<div id="panel-settings" class="admin-panel"><div class="admin-grid-two"><section class="admin-card2"><h3>Announcement & Withdraw Rules</h3><form method="post"><input type="hidden" name="admin_action" value="save_announcement"><div class="form-row"><label>Announcement</label><textarea name="announcement"><?= e($settings['announcement']) ?></textarea></div><button class="full-btn">Save Announcement</button></form><form method="post" style="margin-top:15px"><input type="hidden" name="admin_action" value="save_rules"><div class="select-inline"><div class="form-row"><label>Min Withdraw</label><input name="withdraw_min" type="number" step="0.01" value="<?= e($settings['withdraw_min']) ?>"></div><div class="form-row"><label>Max Withdraw</label><input name="withdraw_max" type="number" step="0.01" value="<?= e($settings['withdraw_max']) ?>"></div></div><div class="form-row"><label>Fee %</label><input name="withdraw_fee" type="number" step="0.01" value="<?= e($settings['withdraw_fee']) ?>"></div><button class="full-btn gold-btn">Save Rules</button></form></section><section class="admin-card2"><h3>Add Game</h3><form method="post"><input type="hidden" name="admin_action" value="add_game"><div class="select-inline"><div class="form-row"><label>Title</label><input name="title" required></div><div class="form-row"><label>Icon</label><input name="icon" value="🎮"></div></div><div class="select-inline"><div class="form-row"><label>Provider</label><input name="provider"></div><div class="form-row"><label>Category</label><select name="category"><option>slots</option><option>casino</option><option>sports</option><option>crash</option><option>fishing</option><option>lottery</option><option>pvc</option></select></div></div><div class="form-row"><label>Image URL</label><input name="image_url" placeholder="assets/games/example.png"></div><div class="form-row"><label>Game URL</label><input name="game_url" placeholder="game.php?game=name"></div><div class="select-inline"><label class="tiny"><input type="checkbox" name="is_hot" checked> Hot</label><label class="tiny"><input type="checkbox" name="active" checked> Active</label><div class="form-row"><label>Sort</label><input name="sort_order" type="number" value="100"></div></div><button class="full-btn">Add Game</button></form></section></div><section class="admin-card2"><h3>Games</h3><div style="overflow:auto"><table class="admin-table"><tr><th>Image</th><th>Game</th><th>Category</th><th>Provider</th><th>URL</th><th>Action</th></tr><?php foreach($games as $g): ?><tr><td><?php if($g['image_url']): ?><img class="admin-game-img" src="../<?= e($g['image_url']) ?>"><?php endif; ?></td><td><?= e($g['icon']) ?> <?= e($g['title']) ?></td><td><?= e($g['category']) ?></td><td><?= e($g['provider']) ?></td><td><?= e($g['game_url']) ?></td><td><form method="post"><input type="hidden" name="admin_action" value="delete_game"><input type="hidden" name="id" value="<?= (int)$g['id'] ?>"><button class="reject-btn" onclick="return confirm('Delete game?')">Delete</button></form></td></tr><?php endforeach; ?></table></div></section></div>
</div></div><script>const Adm={tab(n,b){document.querySelectorAll('.admin-tab').forEach(x=>x.classList.remove('on'));b.classList.add('on');document.querySelectorAll('.admin-panel').forEach(x=>x.classList.remove('on'));document.getElementById('panel-'+n).classList.add('on');}};</script></body></html>
