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

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

// Add manual transaction
if ($_SERVER['REQUEST_METHOD'] === 'POST' && verify_csrf()) {
    $action = $_POST['action'] ?? '';
    if ($action === 'add_transaction') {
        $uid3   = (int)$_POST['user_id'];
        $type   = $_POST['transaction_type'] ?? 'credit';
        $amount = (float)$_POST['amount'];
        $desc   = trim($_POST['description'] ?? 'Manual Entry');
        $status = $_POST['status'] ?? 'completed';
        $benName= trim($_POST['beneficiary_name'] ?? '');
        $ref    = generateRef('ADM');

        if ($uid3 && $amount > 0) {
            $pdo->prepare("INSERT INTO transactions (user_id,transaction_type,amount,currency,description,reference_number,status,beneficiary_name,processed_at) VALUES (?,'$type',?,(SELECT currency FROM users WHERE id=? LIMIT 1),?,?,'$status',?,NOW())")->execute([$uid3,$amount,$uid3,$desc,$ref,$benName]);
            if ($type === 'credit' && $status === 'completed') {
                $pdo->prepare("UPDATE users SET account_balance=account_balance+?,available_balance=available_balance+? WHERE id=?")->execute([$amount,$amount,$uid3]);
            } elseif ($type === 'debit' && $status === 'completed') {
                $pdo->prepare("UPDATE users SET account_balance=account_balance-?,available_balance=available_balance-? WHERE id=?")->execute([$amount,$amount,$uid3]);
            }
            addNotification($pdo,$uid3,'Transaction Posted',"A $type of ".money($amount)." has been posted to your account. Ref: $ref",'transaction');
            logActivity($pdo,$uid3,(int)$_SESSION['admin_id'],'admin_transaction',"Admin posted $type of $amount");
            flash('success',"Transaction $ref posted successfully.");
        }
    }
    if ($action === 'update_status') {
        $tid = (int)$_POST['txn_id'];
        $s2  = $_POST['new_status'] ?? 'completed';
        $pdo->prepare("UPDATE transactions SET status=? WHERE id=?")->execute([$s2,$tid]);
        flash('success','Transaction status updated.');
    }
    header('Location: /admin/transactions.php'); exit;
}

// Filters
$search = trim($_GET['search'] ?? '');
$type   = $_GET['type'] ?? '';
$status = $_GET['status'] ?? '';
$from   = $_GET['from'] ?? '';
$to     = $_GET['to'] ?? '';
$uid3   = (int)($_GET['user'] ?? 0);
$page   = max(1,(int)($_GET['page']??1)); $perPage = 30;

$where = "WHERE 1"; $params = [];
if ($search) { $where .= " AND (t.reference_number LIKE ? OR t.description LIKE ? OR t.beneficiary_name LIKE ? OR u.email LIKE ?)"; $s="%$search%"; $params=[$s,$s,$s,$s]; }
if ($type)   { $where .= " AND t.transaction_type=?"; $params[] = $type; }
if ($status) { $where .= " AND t.status=?"; $params[] = $status; }
if ($from)   { $where .= " AND DATE(t.created_at)>=?"; $params[] = $from; }
if ($to)     { $where .= " AND DATE(t.created_at)<=?"; $params[] = $to; }
if ($uid3)   { $where .= " AND t.user_id=?"; $params[] = $uid3; }

$countStmt = $pdo->prepare("SELECT COUNT(*) FROM transactions t JOIN users u ON t.user_id=u.id $where");
$countStmt->execute($params); $total = (int)$countStmt->fetchColumn();
$pages = (int)ceil($total/$perPage); $offset=($page-1)*$perPage;

$txStmt = $pdo->prepare("SELECT t.*, CONCAT(u.first_name,' ',u.last_name) AS user_name, u.email AS user_email FROM transactions t JOIN users u ON t.user_id=u.id $where ORDER BY t.created_at DESC LIMIT $perPage OFFSET $offset");
$txStmt->execute($params); $txns = $txStmt->fetchAll();

$allUsers = $pdo->query("SELECT id, first_name, last_name, account_number FROM users WHERE id > 1 ORDER BY first_name")->fetchAll();
$pageTitle = 'Transactions';
?>
<?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-exchange-alt me-2 text-danger"></i>Transactions <span class="text-muted small fw-normal">(<?= $total ?> total)</span></div>
  <div class="d-flex gap-2">
    <button class="btn btn-sm btn-success" data-bs-toggle="modal" data-bs-target="#addTxnModal"><i class="fa fa-plus me-1"></i>Add Transaction</button>
    <a href="?export=csv&<?= http_build_query(array_filter(compact('search','type','status','from','to'))) ?>" class="btn btn-sm btn-outline-secondary"><i class="fa fa-download me-1"></i>CSV</a>
  </div>
</div>

<!-- Filters -->
<div class="card mb-3">
  <div class="card-body">
    <form method="GET" class="row g-2 align-items-end">
      <div class="col-md-3"><input type="text" name="search" class="form-control form-control-sm" placeholder="Ref, description, user..." value="<?= sanitize($search) ?>"></div>
      <div class="col-md-2"><select name="type" class="form-select form-select-sm"><option value="">All Types</option><option value="credit" <?= $type==='credit'?'selected':'' ?>>Credit</option><option value="debit" <?= $type==='debit'?'selected':'' ?>>Debit</option></select></div>
      <div class="col-md-2"><select name="status" class="form-select form-select-sm"><option value="">All Statuses</option><option value="completed" <?= $status==='completed'?'selected':'' ?>>Completed</option><option value="pending" <?= $status==='pending'?'selected':'' ?>>Pending</option><option value="failed" <?= $status==='failed'?'selected':'' ?>>Failed</option></select></div>
      <div class="col-md-2"><input type="date" name="from" class="form-control form-control-sm" value="<?= sanitize($from) ?>"></div>
      <div class="col-md-2"><input type="date" name="to" class="form-control form-control-sm" value="<?= sanitize($to) ?>"></div>
      <div class="col-md-1"><button class="btn btn-primary btn-sm w-100"><i class="fa fa-search"></i></button></div>
    </form>
  </div>
</div>

<div class="card">
  <div class="table-responsive">
    <table class="table table-hover mb-0 small">
      <thead><tr><th>Date</th><th>User</th><th>Reference</th><th>Description</th><th>Type</th><th>Amount</th><th>Fee</th><th>Status</th><th>Actions</th></tr></thead>
      <tbody>
      <?php if (empty($txns)): ?>
      <tr><td colspan="9" class="text-center py-4 text-muted">No transactions found.</td></tr>
      <?php else: foreach ($txns as $t): $isC=$t['transaction_type']==='credit'; ?>
      <tr>
        <td><?= formatDate($t['created_at'],'M j Y g:i A') ?></td>
        <td><div class="fw-bold"><?= sanitize($t['user_name']) ?></div><div class="text-muted" style="font-size:.75rem"><?= sanitize($t['user_email']) ?></div></td>
        <td><code><?= sanitize($t['reference_number']) ?></code> <button class="btn btn-xs btn-link p-0" data-copy="<?= sanitize($t['reference_number']) ?>"><i class="fa fa-copy"></i></button></td>
        <td><?= sanitize(substr($t['description'],0,35)) ?></td>
        <td><?= statusBadge($t['transaction_type']) ?></td>
        <td class="fw-bold <?= $isC?'text-success':'text-danger' ?>"><?= ($isC?'+':'-').money((float)$t['amount'],$t['currency']) ?></td>
        <td><?= $t['fee']>0 ? money((float)$t['fee'],$t['currency']) : '—' ?></td>
        <td>
          <form method="POST" class="d-flex gap-1 align-items-center">
            <?= csrf_field() ?><input type="hidden" name="action" value="update_status"><input type="hidden" name="txn_id" value="<?= $t['id'] ?>">
            <select name="new_status" class="form-select form-select-sm" style="width:110px">
              <?php foreach (['pending','processing','completed','failed','cancelled'] as $s3): ?>
              <option value="<?= $s3 ?>" <?= $t['status']===$s3?'selected':'' ?>><?= ucfirst($s3) ?></option>
              <?php endforeach; ?>
            </select>
            <button class="btn btn-xs btn-primary">Go</button>
          </form>
        </td>
      </tr>
      <?php endforeach; endif; ?>
      </tbody>
    </table>
  </div>
  <?php if ($pages > 1): ?>
  <div class="card-footer d-flex justify-content-between">
    <small>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','type','status','from','to'))) ?>"><?= $i ?></a></li>
      <?php endfor; ?>
    </ul></nav>
  </div>
  <?php endif; ?>
</div>
<?php include '../includes/footer.php'; ?>

<!-- Add Transaction Modal -->
<div class="modal fade" id="addTxnModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
  <div class="modal-header bg-success text-white"><h5 class="modal-title">Add Manual Transaction</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="add_transaction">
    <div class="mb-3"><label class="form-label">User</label>
      <select name="user_id" class="form-select" required>
        <option value="">Select user...</option>
        <?php foreach ($allUsers as $u): ?><option value="<?= $u['id'] ?>"><?= sanitize($u['first_name'].' '.$u['last_name']) ?> (<?= sanitize($u['account_number']) ?>)</option><?php endforeach; ?>
      </select>
    </div>
    <div class="row g-2">
      <div class="col-6"><label class="form-label">Type</label><select name="transaction_type" class="form-select"><option value="credit">Credit</option><option value="debit">Debit</option></select></div>
      <div class="col-6"><label class="form-label">Status</label><select name="status" class="form-select"><option value="completed">Completed</option><option value="pending">Pending</option><option value="failed">Failed</option></select></div>
      <div class="col-12"><label class="form-label">Amount</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="col-12"><label class="form-label">Description</label><input type="text" name="description" class="form-control" value="Manual Transaction" required></div>
      <div class="col-12"><label class="form-label">Beneficiary Name</label><input type="text" name="beneficiary_name" class="form-control"></div>
    </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">Post Transaction</button></div>
  </form>
</div></div></div>
<?php
if (isset($_GET['export']) && $_GET['export']==='csv') {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="transactions_'.date('Ymd').'.csv"');
    $out = fopen('php://output','w');
    fputcsv($out,['Date','User','Ref','Description','Type','Amount','Currency','Fee','Status','Beneficiary']);
    foreach ($txns as $t) fputcsv($out,[$t['created_at'],$t['user_name'],$t['reference_number'],$t['description'],$t['transaction_type'],$t['amount'],$t['currency'],$t['fee'],$t['status'],$t['beneficiary_name']]);
    fclose($out); exit;
}
?>
