<?php
require_once '../includes/config.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';
requireAdminLogin();

$error = ''; $success = '';

// Handle bulk/status actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && verify_csrf()) {
    $action = $_POST['action'] ?? '';
    $uid2   = (int)($_POST['user_id'] ?? 0);

    if ($action === 'credit' && $uid2) {
        $amount = (float)$_POST['amount'];
        $desc   = trim($_POST['description'] ?? 'Admin Credit');
        if ($amount > 0) {
            creditAccount($pdo, $uid2, $amount, $desc);
            logActivity($pdo, $uid2, (int)$_SESSION['admin_id'], 'admin_credit', "Admin credited \${$amount} to user $uid2");
            addNotification($pdo, $uid2, 'Account Credited', "Your account has been credited with ".money($amount)." by the bank.", 'success');
            flash('success', money($amount) . ' credited to account successfully.');
        }
    }
    if ($action === 'debit' && $uid2) {
        $amount = (float)$_POST['amount'];
        $desc   = trim($_POST['description'] ?? 'Admin Debit');
        if ($amount > 0) {
            debitAccount($pdo, $uid2, $amount, $desc);
            logActivity($pdo, $uid2, (int)$_SESSION['admin_id'], 'admin_debit', "Admin debited \${$amount} from user $uid2");
            flash('success', money($amount) . ' debited from account.');
        }
    }
    if (in_array($action, ['suspend','activate','close']) && $uid2) {
        $status = ['suspend'=>'suspended','activate'=>'active','close'=>'closed'][$action];
        $pdo->prepare("UPDATE users SET account_status=? WHERE id=?")->execute([$status, $uid2]);
        addNotification($pdo, $uid2, 'Account Status Updated', "Your account status has been updated to: $status.", 'info');
        logActivity($pdo, $uid2, (int)$_SESSION['admin_id'], "account_$action", "Admin set user $uid2 status to $status");
        flash('success', "Account $status successfully.");
    }
    if ($action === 'set_popup' && $uid2) {
        $msg = trim($_POST['popup_message'] ?? '');
        $pdo->prepare("UPDATE users SET show_popup=1,popup_message=? WHERE id=?")->execute([$msg, $uid2]);
        flash('success', 'Popup message set.');
    }
    if ($action === 'clear_popup' && $uid2) {
        $pdo->prepare("UPDATE users SET show_popup=0,popup_message=NULL WHERE id=?")->execute([$uid2]);
        flash('success', 'Popup cleared.');
    }
    header('Location: /admin/users.php'); exit;
}

// Filters
$search  = trim($_GET['search'] ?? '');
$status  = $_GET['status'] ?? '';
$kyc     = $_GET['kyc'] ?? '';
$page    = max(1,(int)($_GET['page']??1)); $perPage = 25;

$where = "WHERE u.id > 1"; $params = [];
if ($search) { $where .= " AND (u.first_name LIKE ? OR u.last_name LIKE ? OR u.email LIKE ? OR u.account_number LIKE ?)"; $s="%$search%"; $params=[$s,$s,$s,$s]; }
if ($status) { $where .= " AND u.account_status=?"; $params[] = $status; }
if ($kyc)    { $where .= " AND u.kyc_status=?"; $params[] = $kyc; }

$total = (int)$pdo->prepare("SELECT COUNT(*) FROM users u $where")->execute($params) ? (int)$pdo->query("SELECT COUNT(*) FROM users u ".$where." ".implode(' ',array_fill(0,count($params),'?')))->fetchColumn() : 0;

// Recount with params
$countStmt = $pdo->prepare("SELECT COUNT(*) FROM users u $where");
$countStmt->execute($params); $total = (int)$countStmt->fetchColumn();
$pages = (int)ceil($total/$perPage); $offset = ($page-1)*$perPage;

$userStmt = $pdo->prepare("SELECT * FROM users u $where ORDER BY u.created_at DESC LIMIT $perPage OFFSET $offset");
$userStmt->execute($params); $users = $userStmt->fetchAll();

$pageTitle = 'Users';
?>
<?php include '../includes/header.php'; ?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div class="page-title mb-0"><i class="fa fa-users me-2 text-danger"></i>User Management <span class="text-muted small fw-normal">(<?= $total ?> total)</span></div>
  <div class="d-flex gap-2">
    <a href="/admin/users.php?export=csv&<?= http_build_query(array_filter(compact('search','status','kyc'))) ?>" class="btn btn-sm btn-outline-success"><i class="fa fa-download me-1"></i>CSV</a>
  </div>
</div>

<!-- Filters -->
<div class="card mb-4">
  <div class="card-body">
    <form method="GET" class="row g-2 align-items-end">
      <div class="col-md-4"><label class="form-label small">Search</label>
        <input type="text" name="search" class="form-control form-control-sm" placeholder="Name, email, account..." value="<?= sanitize($search) ?>">
      </div>
      <div class="col-md-2"><label class="form-label small">Status</label>
        <select name="status" class="form-select form-select-sm">
          <option value="">All</option>
          <option value="active" <?= $status==='active'?'selected':'' ?>>Active</option>
          <option value="pending" <?= $status==='pending'?'selected':'' ?>>Pending</option>
          <option value="suspended" <?= $status==='suspended'?'selected':'' ?>>Suspended</option>
          <option value="closed" <?= $status==='closed'?'selected':'' ?>>Closed</option>
        </select>
      </div>
      <div class="col-md-2"><label class="form-label small">KYC</label>
        <select name="kyc" class="form-select form-select-sm">
          <option value="">All KYC</option>
          <option value="pending" <?= $kyc==='pending'?'selected':'' ?>>Pending</option>
          <option value="verified" <?= $kyc==='verified'?'selected':'' ?>>Verified</option>
          <option value="rejected" <?= $kyc==='rejected'?'selected':'' ?>>Rejected</option>
        </select>
      </div>
      <div class="col-md-2">
        <button class="btn btn-primary btn-sm w-100"><i class="fa fa-search me-1"></i>Filter</button>
      </div>
      <div class="col-md-2">
        <a href="/admin/users.php" class="btn btn-outline-secondary btn-sm w-100">Clear</a>
      </div>
    </form>
  </div>
</div>

<div class="card">
  <div class="table-responsive">
    <table class="table table-hover mb-0 searchable-table">
      <thead>
        <tr><th>#</th><th>Name</th><th>Account</th><th>Balance</th><th>KYC</th><th>Status</th><th>Country</th><th>Joined</th><th>Actions</th></tr>
      </thead>
      <tbody>
      <?php if (empty($users)): ?>
      <tr><td colspan="9" class="text-center py-4 text-muted">No users found.</td></tr>
      <?php else: foreach ($users as $u): ?>
      <tr>
        <td class="small text-muted"><?= $u['id'] ?></td>
        <td>
          <div class="fw-bold small"><?= sanitize($u['first_name'].' '.$u['last_name']) ?></div>
          <div class="text-muted" style="font-size:.75rem"><?= sanitize($u['email']) ?></div>
        </td>
        <td><code class="small"><?= sanitize($u['account_number']) ?></code></td>
        <td class="fw-bold small"><?= money((float)$u['account_balance'],$u['currency']) ?></td>
        <td><?= statusBadge($u['kyc_status']) ?></td>
        <td><?= statusBadge($u['account_status']) ?></td>
        <td class="small"><?= sanitize($u['country']??'—') ?></td>
        <td class="small text-muted"><?= formatDate($u['created_at'],'M j, Y') ?></td>
        <td>
          <div class="d-flex gap-1">
            <a href="/admin/user-edit.php?id=<?= $u['id'] ?>" class="btn btn-xs btn-outline-primary" title="Edit"><i class="fa fa-edit"></i></a>
            <button class="btn btn-xs btn-outline-success" title="Credit" data-bs-toggle="modal" data-bs-target="#creditModal" data-uid="<?= $u['id'] ?>" data-name="<?= sanitize($u['first_name'].' '.$u['last_name']) ?>"><i class="fa fa-plus"></i></button>
            <button class="btn btn-xs btn-outline-danger" title="Debit" data-bs-toggle="modal" data-bs-target="#debitModal" data-uid="<?= $u['id'] ?>" data-name="<?= sanitize($u['first_name'].' '.$u['last_name']) ?>"><i class="fa fa-minus"></i></button>
            <?php if ($u['account_status']==='active'): ?>
            <form method="POST" style="display:inline"><?= csrf_field() ?><input type="hidden" name="action" value="suspend"><input type="hidden" name="user_id" value="<?= $u['id'] ?>"><button class="btn btn-xs btn-outline-warning" title="Suspend" data-confirm="Suspend this user?"><i class="fa fa-pause"></i></button></form>
            <?php else: ?>
            <form method="POST" style="display:inline"><?= csrf_field() ?><input type="hidden" name="action" value="activate"><input type="hidden" name="user_id" value="<?= $u['id'] ?>"><button class="btn btn-xs btn-outline-success" title="Activate"><i class="fa fa-play"></i></button></form>
            <?php endif; ?>
          </div>
        </td>
      </tr>
      <?php endforeach; endif; ?>
      </tbody>
    </table>
  </div>
  <?php if ($pages > 1): ?>
  <div class="card-footer d-flex justify-content-between align-items-center">
    <small class="text-muted">Page <?= $page ?>/<?= $pages ?></small>
    <nav><ul class="pagination pagination-sm mb-0">
      <?php for ($i=max(1,$page-2);$i<=min($pages,$page+2);$i++): ?>
      <li class="page-item <?= $i==$page?'active':'' ?>"><a class="page-link" href="?page=<?= $i ?>&<?= http_build_query(array_filter(compact('search','status','kyc'))) ?>"><?= $i ?></a></li>
      <?php endfor; ?>
    </ul></nav>
  </div>
  <?php endif; ?>
</div>

<?php include '../includes/footer.php'; ?>

<!-- Credit Modal -->
<div class="modal fade" id="creditModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
  <div class="modal-header bg-success text-white"><h5 class="modal-title"><i class="fa fa-plus-circle me-2"></i>Credit Account</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
  <form method="POST"><div class="modal-body">
    <?= csrf_field() ?><input type="hidden" name="action" value="credit"><input type="hidden" name="user_id" id="creditUid">
    <p>Crediting: <strong id="creditName"></strong></p>
    <div class="mb-3"><label class="form-label">Amount (USD)</label><div class="input-group"><span class="input-group-text">$</span><input type="number" name="amount" class="form-control" step="0.01" min="0.01" required></div></div>
    <div class="mb-3"><label class="form-label">Description</label><input type="text" name="description" class="form-control" value="Admin Credit" required></div>
  </div>
  <div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button><button class="btn btn-success fw-bold">Credit Account</button></div>
  </form>
</div></div></div>

<!-- Debit Modal -->
<div class="modal fade" id="debitModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
  <div class="modal-header bg-danger text-white"><h5 class="modal-title"><i class="fa fa-minus-circle me-2"></i>Debit Account</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
  <form method="POST"><div class="modal-body">
    <?= csrf_field() ?><input type="hidden" name="action" value="debit"><input type="hidden" name="user_id" id="debitUid">
    <p>Debiting: <strong id="debitName"></strong></p>
    <div class="mb-3"><label class="form-label">Amount (USD)</label><div class="input-group"><span class="input-group-text">$</span><input type="number" name="amount" class="form-control" step="0.01" min="0.01" required></div></div>
    <div class="mb-3"><label class="form-label">Description</label><input type="text" name="description" class="form-control" value="Admin Debit" required></div>
  </div>
  <div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button><button class="btn btn-danger fw-bold">Debit Account</button></div>
  </form>
</div></div></div>

<script>
document.querySelectorAll('[data-bs-target="#creditModal"]').forEach(btn => {
  btn.addEventListener('click', () => {
    document.getElementById('creditUid').value = btn.dataset.uid;
    document.getElementById('creditName').textContent = btn.dataset.name;
  });
});
document.querySelectorAll('[data-bs-target="#debitModal"]').forEach(btn => {
  btn.addEventListener('click', () => {
    document.getElementById('debitUid').value = btn.dataset.uid;
    document.getElementById('debitName').textContent = btn.dataset.name;
  });
});
</script>
<?php
// CSV export
if (isset($_GET['export']) && $_GET['export']==='csv') {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="users_'.date('Ymd').'.csv"');
    $out = fopen('php://output','w');
    fputcsv($out,['ID','First Name','Last Name','Email','Account #','Balance','KYC','Status','Country','Joined']);
    foreach ($users as $u) fputcsv($out,[$u['id'],$u['first_name'],$u['last_name'],$u['email'],$u['account_number'],$u['account_balance'],$u['kyc_status'],$u['account_status'],$u['country'],$u['created_at']]);
    fclose($out); exit;
}
?>
