<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech
include('include/header.php');
$page_title = WEB_NAME . " | Transactions";

// Filter parameters
$status_filter = isset($_GET['status'])           ? trim($_GET['status'])           : 'all';
$type_filter   = isset($_GET['transaction_type']) ? trim($_GET['transaction_type']) : 'all';
$search        = isset($_GET['search'])           ? trim($_GET['search'])           : '';
$date_from     = isset($_GET['date_from'])        ? trim($_GET['date_from'])        : '';
$date_to       = isset($_GET['date_to'])          ? trim($_GET['date_to'])          : '';

// Build WHERE clause
$where  = "WHERE 1=1";
$params = [];

if ($status_filter !== 'all') {
    $where .= " AND t.status = :status";
    $params['status'] = $status_filter;
}
if ($type_filter !== 'all') {
    $where .= " AND t.transaction_type = :transaction_type";
    $params['transaction_type'] = $type_filter;
}
if (!empty($search)) {
    $where .= " AND (t.transaction_ref LIKE :s1 OR t.gateway_reference LIKE :s2
                     OR u.username LIKE :s3 OR u.email LIKE :s4 OR u.full_name LIKE :s5)";
    $params['s1'] = "%$search%"; $params['s2'] = "%$search%";
    $params['s3'] = "%$search%"; $params['s4'] = "%$search%";
    $params['s5'] = "%$search%";
}
if (!empty($date_from)) {
    $where .= " AND DATE(t.created_at) >= :date_from";
    $params['date_from'] = $date_from;
}
if (!empty($date_to)) {
    $where .= " AND DATE(t.created_at) <= :date_to";
    $params['date_to'] = $date_to;
}

try {
    $stmt = $pdo->prepare("
        SELECT t.*, u.username, u.email, u.full_name, u.main_balance
        FROM transactions t
        LEFT JOIN users u ON t.user_id = u.id
        $where
        ORDER BY t.created_at DESC
    ");
    $stmt->execute($params);
    $transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $transactions = [];
    error_log("Transactions fetch error: " . $e->getMessage());
}

// Summary stats
try {
    $stats = $pdo->query("
        SELECT
            COUNT(*) AS total,
            SUM(CASE WHEN status='successful' THEN 1 ELSE 0 END) AS successful,
            SUM(CASE WHEN status='pending'    THEN 1 ELSE 0 END) AS pending,
            SUM(CASE WHEN status='failed'     THEN 1 ELSE 0 END) AS failed,
            SUM(CASE WHEN status='successful' THEN amount ELSE 0 END) AS total_successful_amount,
            SUM(CASE WHEN status='pending'    THEN amount ELSE 0 END) AS total_pending_amount
        FROM transactions
    ")->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $stats = ['total'=>0,'successful'=>0,'pending'=>0,'failed'=>0,'total_successful_amount'=>0,'total_pending_amount'=>0];
}
?>
<title>Transactions - <?php echo $site_data['web_name']; ?></title>

<link href="vendor/datatables/dataTables.bootstrap4.min.css" rel="stylesheet">

<style>
  .btn-group { white-space: nowrap; }
  .dropdown-item { cursor: pointer; }
  .dropdown-item i { width: 20px; margin-right: 5px; }
</style>

<div class="container-fluid" id="container-wrapper">
  <div class="d-sm-flex align-items-center justify-content-between mb-4">
    <h1 class="h3 mb-0 text-gray-800">Transactions</h1>
    <ol class="breadcrumb">
      <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
      <li class="breadcrumb-item active" aria-current="page">Transactions</li>
    </ol>
  </div>

  <!-- Summary Cards -->
  <div class="row mb-4">
    <div class="col-xl-3 col-md-6 mb-4">
      <div class="card border-left-primary shadow h-100 py-2">
        <div class="card-body">
          <div class="row no-gutters align-items-center">
            <div class="col mr-2">
              <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Total Transactions</div>
              <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($stats['total']); ?></div>
            </div>
            <div class="col-auto"><i class="fas fa-exchange-alt fa-2x text-gray-300"></i></div>
          </div>
        </div>
      </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-4">
      <div class="card border-left-success shadow h-100 py-2">
        <div class="card-body">
          <div class="row no-gutters align-items-center">
            <div class="col mr-2">
              <div class="text-xs font-weight-bold text-success text-uppercase mb-1">Successful</div>
              <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($stats['successful']); ?></div>
              <small class="text-muted">₦<?php echo number_format($stats['total_successful_amount'], 2); ?></small>
            </div>
            <div class="col-auto"><i class="fas fa-check-circle fa-2x text-gray-300"></i></div>
          </div>
        </div>
      </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-4">
      <div class="card border-left-warning shadow h-100 py-2">
        <div class="card-body">
          <div class="row no-gutters align-items-center">
            <div class="col mr-2">
              <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Pending</div>
              <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($stats['pending']); ?></div>
              <small class="text-muted">₦<?php echo number_format($stats['total_pending_amount'], 2); ?></small>
            </div>
            <div class="col-auto"><i class="fas fa-clock fa-2x text-gray-300"></i></div>
          </div>
        </div>
      </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-4">
      <div class="card border-left-danger shadow h-100 py-2">
        <div class="card-body">
          <div class="row no-gutters align-items-center">
            <div class="col mr-2">
              <div class="text-xs font-weight-bold text-danger text-uppercase mb-1">Failed</div>
              <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($stats['failed']); ?></div>
            </div>
            <div class="col-auto"><i class="fas fa-times-circle fa-2x text-gray-300"></i></div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Filters -->
  <div class="card mb-4 shadow">
    <div class="card-body">
      <form method="GET" action="">
        <div class="row">
          <div class="col-md-3 mb-2">
            <input type="text" name="search" class="form-control"
                   placeholder="Search ref, username, email..."
                   value="<?php echo htmlspecialchars($search); ?>">
          </div>
          <div class="col-md-2 mb-2">
            <select name="status" class="form-control">
              <option value="all"        <?php echo $status_filter=='all'        ? 'selected':''; ?>>All Status</option>
              <option value="pending"    <?php echo $status_filter=='pending'    ? 'selected':''; ?>>Pending</option>
              <option value="successful" <?php echo $status_filter=='successful' ? 'selected':''; ?>>Successful</option>
              <option value="failed"     <?php echo $status_filter=='failed'     ? 'selected':''; ?>>Failed</option>
              <option value="cancelled"  <?php echo $status_filter=='cancelled'  ? 'selected':''; ?>>Cancelled</option>
            </select>
          </div>
          <div class="col-md-2 mb-2">
            <select name="transaction_type" class="form-control">
              <option value="all"            <?php echo $type_filter=='all'            ? 'selected':''; ?>>All Types</option>
              <option value="deposit"        <?php echo $type_filter=='deposit'        ? 'selected':''; ?>>Deposit</option>
              <option value="number_purchase"<?php echo $type_filter=='number_purchase'? 'selected':''; ?>>Number Purchase</option>
              <option value="social_boost"   <?php echo $type_filter=='social_boost'   ? 'selected':''; ?>>Social Boost</option>
              <option value="logs_purchase"  <?php echo $type_filter=='logs_purchase'  ? 'selected':''; ?>>Logs Purchase</option>
              <option value="refund"         <?php echo $type_filter=='refund'         ? 'selected':''; ?>>Refund</option>
            </select>
          </div>
          <div class="col-md-2 mb-2">
            <input type="date" name="date_from" class="form-control" value="<?php echo htmlspecialchars($date_from); ?>">
          </div>
          <div class="col-md-2 mb-2">
            <input type="date" name="date_to" class="form-control" value="<?php echo htmlspecialchars($date_to); ?>">
          </div>
          <div class="col-md-1 mb-2">
            <button type="submit" class="btn btn-primary btn-block"><i class="fas fa-search"></i></button>
          </div>
        </div>
        <?php if ($search || $status_filter!='all' || $type_filter!='all' || $date_from || $date_to): ?>
        <div class="row mt-2">
          <div class="col-12">
            <a href="transactions.php" class="btn btn-secondary btn-sm">
              <i class="fas fa-redo"></i> Reset Filters
            </a>
          </div>
        </div>
        <?php endif; ?>
      </form>
    </div>
  </div>

  <!-- Transactions Table -->
  <div class="row">
    <div class="col-lg-12">
      <div class="card mb-4 shadow">
        <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
          <h6 class="m-0 font-weight-bold text-primary">All Transactions (<?php echo count($transactions); ?> records)</h6>
        </div>
        <div class="table-responsive p-3">
          <table class="table align-items-center table-flush table-hover" id="dataTable">
            <thead class="thead-light">
              <tr>
                <th>#</th>
                <th>Reference</th>
                <th>User</th>
                <th>Type</th>
                <th>Amount</th>
                <th>Gateway</th>
                <th>Method</th>
                <th>Status</th>
                <th>Date</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <?php $i = 1; foreach ($transactions as $txn):
                // Status badge
                switch ($txn['status']) {
                  case 'successful': $sbadge = 'badge-success';  $slabel = 'Successful'; break;
                  case 'pending':    $sbadge = 'badge-warning';  $slabel = 'Pending';    break;
                  case 'failed':     $sbadge = 'badge-danger';   $slabel = 'Failed';     break;
                  case 'cancelled':  $sbadge = 'badge-secondary';$slabel = 'Cancelled';  break;
                  default:           $sbadge = 'badge-secondary';$slabel = ucfirst($txn['status']);
                }
                // Type badge
                switch ($txn['transaction_type']) {
                  case 'deposit':         $tbadge = 'badge-primary'; $tlabel = 'Deposit';         break;
                  case 'number_purchase': $tbadge = 'badge-info';    $tlabel = 'Number Purchase';  break;
                  case 'social_boost':    $tbadge = 'badge-purple';  $tlabel = 'Social Boost';     break;
                  case 'logs_purchase':   $tbadge = 'badge-dark';    $tlabel = 'Logs Purchase';    break;
                  case 'refund':          $tbadge = 'badge-success'; $tlabel = 'Refund';           break;
                  default:                $tbadge = 'badge-secondary';$tlabel = $txn['transaction_type'] ?? '—';
                }
                $display_name = !empty($txn['full_name']) ? $txn['full_name'] : ($txn['username'] ?? '—');
              ?>
              <tr>
                <td><?php echo $i; ?></td>
                <td>
                  <code style="font-size:0.75rem;"><?php echo htmlspecialchars($txn['transaction_ref']); ?></code>
                  <?php if (!empty($txn['gateway_reference'])): ?>
                    <br><small class="text-muted"><?php echo htmlspecialchars($txn['gateway_reference']); ?></small>
                  <?php endif; ?>
                </td>
                <td>
                  <strong><?php echo htmlspecialchars($display_name); ?></strong><br>
                  <small class="text-muted"><?php echo htmlspecialchars($txn['email'] ?? '—'); ?></small><br>
                  <small class="text-muted">@<?php echo htmlspecialchars($txn['username'] ?? '—'); ?></small>
                </td>
                <td><span class="badge <?php echo $tbadge; ?>"><?php echo $tlabel; ?></span></td>
                <td>
                  <strong>₦<?php echo number_format($txn['amount'], 2); ?></strong><br>
                  <small class="text-muted"><?php echo htmlspecialchars($txn['currency'] ?? 'NGN'); ?></small>
                </td>
                <td><span class="badge badge-light border"><?php echo htmlspecialchars(strtoupper($txn['payment_gateway'])); ?></span></td>
                <td><?php echo !empty($txn['payment_method']) ? htmlspecialchars(ucwords(str_replace('_',' ',$txn['payment_method']))) : '<span class="text-muted">—</span>'; ?></td>
                <td><span class="badge <?php echo $sbadge; ?>"><?php echo $slabel; ?></span></td>
                <td>
                  <small><?php echo date('M d, Y', strtotime($txn['created_at'])); ?></small><br>
                  <small class="text-muted"><?php echo date('h:i A', strtotime($txn['created_at'])); ?></small>
                </td>
                <td>
                  <div class="btn-group" role="group">
                    <button type="button"
                            class="btn btn-sm btn-primary dropdown-toggle"
                            data-toggle="dropdown"
                            aria-haspopup="true"
                            aria-expanded="false">
                      <i class="fas fa-cog"></i> Actions
                    </button>
                    <div class="dropdown-menu">
                      <?php if ($txn['status'] === 'pending'): ?>
                        <a class="dropdown-item" href="#"
                           onclick="approveTransaction(<?php echo $txn['id']; ?>, '<?php echo htmlspecialchars($txn['transaction_ref'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($display_name, ENT_QUOTES); ?>', '<?php echo $txn['amount']; ?>', '<?php echo htmlspecialchars($txn['transaction_type'] ?? 'deposit', ENT_QUOTES); ?>')">
                          <i class="fas fa-check-circle text-success"></i> Approve
                        </a>
                        <a class="dropdown-item" href="#"
                           onclick="cancelTransaction(<?php echo $txn['id']; ?>, '<?php echo htmlspecialchars($txn['transaction_ref'], ENT_QUOTES); ?>')">
                          <i class="fas fa-ban text-warning"></i> Cancel
                        </a>
                        <div class="dropdown-divider"></div>
                      <?php endif; ?>
                      <a class="dropdown-item" href="#"
                         onclick="deleteTransaction(<?php echo $txn['id']; ?>, '<?php echo htmlspecialchars($txn['transaction_ref'], ENT_QUOTES); ?>')">
                        <i class="fas fa-trash text-danger"></i> Delete
                      </a>
                    </div>
                  </div>
                </td>
              </tr>
              <?php $i++; endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Page level plugins -->
<script src="vendor/datatables/jquery.dataTables.min.js"></script>
<script src="vendor/datatables/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
  $(document).ready(function() {
    $('#dataTable').DataTable({
      ordering: true,
      pageLength: 25,
      order: [[0, 'desc']]
    });
  });

  // Approve transaction
  function approveTransaction(txnId, txnRef, userName, amount, txnType) {
    const isDeposit = (txnType === 'deposit');
    const balanceNote = isDeposit
      ? `<br><small class="text-success"><i class="fas fa-info-circle"></i> ₦${parseFloat(amount).toLocaleString('en-NG', {minimumFractionDigits:2})} will be credited to <strong>${userName}</strong>'s main balance.</small>`
      : `<br><small class="text-info"><i class="fas fa-info-circle"></i> Transaction type: <strong>${txnType.replace(/_/g,' ')}</strong>. No balance change for non-deposit types.</small>`;

    Swal.fire({
      title: 'Approve Transaction?',
      html: `Approve <strong>${txnRef}</strong> for <strong>${userName}</strong>?${balanceNote}`,
      icon: 'question',
      showCancelButton: true,
      confirmButtonColor: '#1cc88a',
      cancelButtonColor: '#858796',
      confirmButtonText: 'Yes, Approve'
    }).then((result) => {
      if (result.isConfirmed) {
        Swal.fire({ title: 'Processing...', allowOutsideClick: false, didOpen: () => { Swal.showLoading(); } });

        $.ajax({
          url: 'ajax/approve_transaction.php',
          type: 'POST',
          data: { transaction_id: txnId },
          dataType: 'json',
          success: function(data) {
            Swal.close();
            if (data.status == '1') {
              Swal.fire({ title: 'Approved!', text: data.msg, icon: 'success', confirmButtonColor: '#1cc88a' })
                .then(() => { location.reload(); });
            } else {
              Swal.fire('Error!', data.msg, 'error');
            }
          },
          error: function() {
            Swal.close();
            Swal.fire('Error!', 'An error occurred. Please try again.', 'error');
          }
        });
      }
    });
  }

  // Cancel transaction
  function cancelTransaction(txnId, txnRef) {
    Swal.fire({
      title: 'Cancel Transaction?',
      html: `Mark <strong>${txnRef}</strong> as cancelled?`,
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#f6c23e',
      cancelButtonColor: '#858796',
      confirmButtonText: 'Yes, Cancel It'
    }).then((result) => {
      if (result.isConfirmed) {
        Swal.fire({ title: 'Processing...', allowOutsideClick: false, didOpen: () => { Swal.showLoading(); } });

        $.ajax({
          url: 'ajax/cancel_transaction.php',
          type: 'POST',
          data: { transaction_id: txnId },
          dataType: 'json',
          success: function(data) {
            Swal.close();
            if (data.status == '1') {
              Swal.fire({ title: 'Done!', text: data.msg, icon: 'success', confirmButtonColor: '#1cc88a' })
                .then(() => { location.reload(); });
            } else {
              Swal.fire('Error!', data.msg, 'error');
            }
          },
          error: function() {
            Swal.close();
            Swal.fire('Error!', 'An error occurred. Please try again.', 'error');
          }
        });
      }
    });
  }

  // Delete transaction
  function deleteTransaction(txnId, txnRef) {
    Swal.fire({
      title: 'Delete Transaction?',
      html: `<p>Permanently delete <strong>${txnRef}</strong>?</p><p style="color:#e74a3b;"><strong>This cannot be undone.</strong></p>`,
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#e74a3b',
      cancelButtonColor: '#858796',
      confirmButtonText: 'Yes, Delete',
      focusCancel: true
    }).then((result) => {
      if (result.isConfirmed) {
        Swal.fire({ title: 'Processing...', allowOutsideClick: false, didOpen: () => { Swal.showLoading(); } });

        $.ajax({
          url: 'ajax/delete_transaction.php',
          type: 'POST',
          data: { transaction_id: txnId },
          dataType: 'json',
          success: function(data) {
            Swal.close();
            if (data.status == '1') {
              Swal.fire({ title: 'Deleted!', text: data.msg, icon: 'success', confirmButtonColor: '#1cc88a' })
                .then(() => { location.reload(); });
            } else {
              Swal.fire('Error!', data.msg, 'error');
            }
          },
          error: function() {
            Swal.close();
            Swal.fire('Error!', 'An error occurred. Please try again.', 'error');
          }
        });
      }
    });
  }
</script>

<?php include('include/footer.php'); ?>