<?php
require_once __DIR__ . '/../actions/admin_auth.php';
require_once __DIR__ . '/../includes/db.php';

$search = trim($_GET['search'] ?? '');
$typeFilter = trim($_GET['type'] ?? '');
$statusFilter = trim($_GET['status'] ?? '');
$limit = 10;
$page = max(1, intval($_GET['page'] ?? 1));
$offset = ($page - 1) * $limit;

$where = [];
$params = [];

// 🔍 Filters
if ($search !== '') {
    $where[] = "(u.firstname LIKE ? OR u.lastname LIKE ? OR u.account_number LIKE ? OR t.reference LIKE ?)";
    $params = array_merge($params, ["%$search%", "%$search%", "%$search%", "%$search%"]);
}
if ($typeFilter !== '') {
    $where[] = "t.type = ?";
    $params[] = $typeFilter;
}
if ($statusFilter !== '') {
    $where[] = "t.status = ?";
    $params[] = $statusFilter;
}

$whereSQL = count($where) ? "WHERE " . implode(" AND ", $where) : "";

// 🧮 Count total
$countStmt = $pdo->prepare("SELECT COUNT(*) 
    FROM transactions t 
    JOIN users u ON t.user_id = u.id 
    $whereSQL");
$countStmt->execute($params);
$total = (int)$countStmt->fetchColumn();
$totalPages = ceil($total / $limit);

// 🧾 Fetch transactions
$stmt = $pdo->prepare("SELECT 
    t.id, t.type, t.amount, t.description, t.reference, t.status, t.created_at,
    u.firstname, u.lastname, u.account_number, u.currency
    FROM transactions t
    JOIN users u ON t.user_id = u.id
    $whereSQL
    ORDER BY t.id DESC
    LIMIT $limit OFFSET $offset");
$stmt->execute($params);
$transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<style>
    body {
      background: #f5f6fa;
      font-family: 'Poppins', sans-serif;
    }
    .navbar {
      background: #0f2027;
      background: linear-gradient(90deg, #203a43, #2c5364);
    }
    .navbar-brand {
      color: #fff !important;
      font-weight: 600;
    }
    .card {
      border-radius: 1rem;
      box-shadow: 0 2px 15px rgba(0,0,0,0.1);
    }
    .btn-action {
      padding: 3px 10px;
      font-size: 0.85rem;
    }
  </style>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Transactions - Admin Panel</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-dark">
<nav class="navbar navbar-dark px-3">
  <a class="navbar-brand" href="../users">User Dashboard</a>
  <div>
      <a href="." class="btn btn-primary btn-sm"><i class="bi bi-box-arrow-right"></i> Dashboard</a>
  <a href="transactions" class="btn btn-primary btn-sm"><i class="bi bi-box-arrow-right"></i> Transactions</a>
  </div>
</nav>

<div class="container py-5">
  <div class="card shadow-sm">
   

    <div class="card-body">
      <!-- 🔍 Filters -->
      <form method="get" class="row g-2 mb-4">
        <div class="col-md-4">
          <input type="text" name="search" value="<?= htmlspecialchars($search) ?>" class="form-control" placeholder="Search by name, account or reference">
        </div>
        <div class="col-md-3">
          <select name="type" class="form-select">
            <option value="">All Types</option>
            <option value="deposit" <?= $typeFilter==='deposit'?'selected':'' ?>>Deposit</option>
            <option value="withdrawal" <?= $typeFilter==='withdrawal'?'selected':'' ?>>Withdrawal</option>
            <option value="transfer" <?= $typeFilter==='transfer'?'selected':'' ?>>Transfer</option>
          </select>
        </div>
        <div class="col-md-3">
          <select name="status" class="form-select">
            <option value="">All Status</option>
            <option value="successful" <?= $statusFilter==='successful'?'selected':'' ?>>Successful</option>
            <option value="pending" <?= $statusFilter==='pending'?'selected':'' ?>>Pending</option>
            <option value="failed" <?= $statusFilter==='failed'?'selected':'' ?>>Failed</option>
          </select>
        </div>
        <div class="col-md-2 d-grid">
          <button class="btn btn-primary">Filter</button>
        </div>
      </form>


<button class="btn btn-warning" data-bs-toggle="modal" data-bs-target="#createHistoryModal">
                            <i class="bi bi-plus-circle"></i> ➕    Create History                   </button><br><br>
                            
      <div class="table-responsive">
        <?php if (count($transactions) > 0): ?>
          <table class="table table-striped table-bordered align-middle">
            <thead class="table-dark">
              <tr>
                <th>Action</th>
                <th>User</th>
                <th>Account No.</th>
                <th>Type</th>
                <th>Amount</th>
                <th>Status</th>
                <th>Reference</th>
                <th>Date</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($transactions as $i => $t): ?>
                <tr>
                  <!--<td><?= $offset + $i + 1 ?></td>-->
                  
                  
                  <td>
                      <!-- Create History Button -->
                        

    
    <button class="btn btn-warning btn-sm editBtn"
        data-id="<?= $t['id'] ?>"
        data-user="<?= htmlspecialchars($t['firstname'].' '.$t['lastname']) ?>"
        data-account="<?= $t['account_number'] ?>"
        data-type="<?= $t['type'] ?>"
        data-amount="<?= $t['amount'] ?>"
        data-status="<?= $t['status'] ?>"
        data-reference="<?= $t['reference'] ?>"
        data-description="<?= htmlspecialchars($t['description']) ?>"
        data-date="<?= $t['created_at'] ?>">
        ✏ Edit
    </button>

    <!-- Delete Button -->
    <button class="btn btn-danger btn-sm deleteBtn" data-id="<?= $t['id'] ?>">🗑 Delete</button>
</td>


                  <td><?= htmlspecialchars($t['firstname'] . ' ' . $t['lastname']) ?></td>
                  <td><?= htmlspecialchars($t['account_number']) ?></td>
                  <td>
                    <?php if ($t['type'] === 'deposit'): ?>
                      <span class="badge bg-success">Deposit</span>
                    <?php elseif ($t['type'] === 'withdrawal'): ?>
                      <span class="badge bg-danger">Withdrawal</span>
                    <?php else: ?>
                      <span class="badge bg-info text-dark">Transfer</span>
                    <?php endif; ?>
                  </td>
                  <td><?= htmlspecialchars($t['currency']) . ' ' . number_format($t['amount'], 2) ?></td>
                  <td>
                    <?php if ($t['status'] === 'successful'): ?>
                      <span class="badge bg-success">Successful</span>
                    <?php elseif ($t['status'] === 'pending'): ?>
                      <span class="badge bg-warning text-dark">Pending</span>
                      <?php elseif ($t['status'] === 'reversed'): ?>
                      <span class="badge bg-primary text-white">Reversed</span>
                    <?php else: ?>
                      <span class="badge bg-danger">Failed</span>
                    <?php endif; ?>

                  </td>
                  <td><code><?= htmlspecialchars($t['reference']) ?></code></td>
                  <td><?= htmlspecialchars(date('M d, Y h:i A', strtotime($t['created_at']))) ?></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>

          <!-- Pagination -->
          <nav>
            <ul class="pagination justify-content-center">
              <?php if ($page > 1): ?>
                <li class="page-item"><a class="page-link" href="?page=<?= $page - 1 ?>&search=<?= urlencode($search) ?>">Previous</a></li>
              <?php endif; ?>
              <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                <li class="page-item <?= $i === $page ? 'active' : '' ?>">
                  <a class="page-link" href="?page=<?= $i ?>&search=<?= urlencode($search) ?>"><?= $i ?></a>
                </li>
              <?php endfor; ?>
              <?php if ($page < $totalPages): ?>
                <li class="page-item"><a class="page-link" href="?page=<?= $page + 1 ?>&search=<?= urlencode($search) ?>">Next</a></li>
              <?php endif; ?>
            </ul>
          </nav>

        <?php else: ?>
          <div class="alert alert-info text-center">No transactions found.</div>
        <?php endif; ?>
      </div>
    </div>
    
    
    <!-- 🧾 Add Transaction Modal -->
<!-- 🧾 Add Transaction Modal -->
<div class="modal fade" id="addTransactionModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title">Add Transaction</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <form id="addTransactionForm">
          <div class="mb-3">
            <label class="form-label">User Account Number</label>
            <input type="text" name="account_number" class="form-control" required placeholder="Enter user's account number">
          </div>

          <div class="mb-3">
            <label class="form-label">Transaction Type</label>
            <select name="type" id="type" class="form-control" required>
              <option value="">-- Select Transaction Type --</option>
              <option value="deposit">Deposit</option>
              <option value="withdrawal">Withdrawal</option>
              <option value="transfer">Transfer</option>
            </select>

          </div>

          <div class="mb-3">
            <label class="form-label">Amount</label>
            <input type="number" step="0.01" name="amount" class="form-control" required>
          </div>

          <div class="mb-3">
            <label class="form-label">Status</label>
            <select id="status" name="status" class="form-select">
              <option value="successful" selected>Successful</option>
              <option value="pending">Pending</option>
              <option value="reversed">Reversed</option>
              <option value="failed">Failed</option>
            </select>

          </div>

          <div class="mb-3">
            <label class="form-label">Description</label>
            <textarea name="description" class="form-control" placeholder="Enter description"></textarea>
          </div>

          <div id="modalMessage" class="mb-2"></div>

          <div class="text-end">
            <button type="submit" class="btn btn-primary">Submit</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>





<div class="modal fade" id="editTransactionModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <form id="editTransactionForm">
        <div class="modal-header bg-warning text-dark">
          <h5 class="modal-title">Edit Transaction</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>

        <div class="modal-body">

          <input type="hidden" name="id" id="edit_id">

          <div class="mb-3">
            <label class="form-label">Account Number</label>
            <input type="text" name="account_number" id="edit_account" class="form-control" required>
          </div>

          <div class="mb-3">
            <label class="form-label">Type</label>
            <select name="type" id="edit_type" class="form-select">
              <option value="deposit">Deposit</option>
              <option value="withdrawal">Withdrawal</option>
              <option value="transfer">Transfer</option>
            </select>
          </div>

          <div class="mb-3">
            <label class="form-label">Amount</label>
            <input type="number" step="0.01" name="amount" id="edit_amount" class="form-control" required>
          </div>

          <div class="mb-3">
            <label class="form-label">Status</label>
            <select name="status" id="edit_status" class="form-select">
              <option value="successful">Successful</option>
              <option value="pending">Pending</option>
              <option value="reversed">Reversed</option>
              <option value="failed">Failed</option>
            </select>
          </div>

          <div class="mb-3">
            <label class="form-label">Reference</label>
            <input type="text" name="reference" id="edit_reference" class="form-control">
          </div>

          <div class="mb-3">
            <label class="form-label">Description</label>
            <textarea name="description" id="edit_description" class="form-control"></textarea>
          </div>

          <div class="mb-3">
            <label class="form-label">Transaction Date</label>
            <input type="datetime-local" name="created_at" id="edit_date" class="form-control" required>
          </div>

          <div id="editMessage"></div>

        </div>

        <div class="modal-footer">
          <button type="submit" class="btn btn-warning">Save Changes</button>
        </div>
      </form>
    </div>
  </div>
</div>






  </div>
</div>





<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>


document.addEventListener('DOMContentLoaded', () => {
    let deleteTransactionId = null;
    const deleteModalEl = document.getElementById('deleteConfirmModal');
    const deleteModalInstance = new bootstrap.Modal(deleteModalEl);

    // Bind Delete buttons
    document.querySelectorAll('.deleteBtn').forEach(btn => {
        btn.addEventListener('click', () => {
            deleteTransactionId = btn.dataset.id;
            const userRow = btn.closest('tr');
            const userName = userRow.querySelector('td:nth-child(2)').textContent;
            const reference = userRow.querySelector('td:nth-child(7) code').textContent;

            document.getElementById('deleteTransactionInfo').textContent = `${userName} | Ref: ${reference}`;

            deleteModalInstance.show();
        });
    });

    // Confirm delete
    document.getElementById('confirmDeleteBtn').addEventListener('click', async () => {
        if (!deleteTransactionId) return;

        const btn = document.getElementById('confirmDeleteBtn');
        btn.disabled = true;
        btn.textContent = 'Deleting...';
        document.getElementById('deleteMessage').innerHTML = '';

        try {
            const res = await fetch('../actions/delete_transaction_action', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({id: deleteTransactionId})
            });

            const data = await res.json();
            if (data.status === 'success') {
                document.getElementById('deleteMessage').innerHTML = `<div class="alert alert-success">${data.message}</div>`;
                setTimeout(() => location.reload(), 800);
            } else {
                document.getElementById('deleteMessage').innerHTML = `<div class="alert alert-danger">${data.message}</div>`;
            }
        } catch (err) {
            document.getElementById('deleteMessage').innerHTML = `<div class="alert alert-danger">Error: ${err.message}</div>`;
        } finally {
            btn.disabled = false;
            btn.textContent = 'Delete';
        }
    });
});



document.getElementById('addTransactionForm').addEventListener('submit', async function(e) {
  e.preventDefault();
  const form = e.target;
  const formData = new FormData(form);
  const msgBox = document.getElementById('modalMessage');
  
  try {
    const res = await fetch('../actions/add_transaction_action', {
      method: 'POST',
      body: formData
    });

    const text = await res.text();
    let data;
    try {
      data = JSON.parse(text);
    } catch (e) {
      throw new Error('Server returned invalid response: ' + text);
    }

    if (data.status === 'success') {
      msgBox.innerHTML = `<div class="alert alert-success">${data.message}</div>`;
      setTimeout(() => location.reload(), 1200);
    } else {
      msgBox.innerHTML = `<div class="alert alert-danger">${data.message}</div>`;
    }

  } catch (err) {
    msgBox.innerHTML = `<div class="alert alert-danger">Error: ${err.message}</div>`;
  }
});
</script>





<script>
document.querySelectorAll('.editBtn').forEach(btn => {
  btn.addEventListener('click', () => {

    document.getElementById('edit_id').value = btn.dataset.id;
    document.getElementById('edit_account').value = btn.dataset.account;
    document.getElementById('edit_type').value = btn.dataset.type;
    document.getElementById('edit_amount').value = btn.dataset.amount;
    document.getElementById('edit_status').value = btn.dataset.status;
    document.getElementById('edit_reference').value = btn.dataset.reference;
    document.getElementById('edit_description').value = btn.dataset.description;

    // Format date for datetime-local
    let dt = new Date(btn.dataset.date);
    document.getElementById('edit_date').value = dt.toISOString().slice(0,16);

    new bootstrap.Modal(document.getElementById('editTransactionModal')).show();
  });
});

document.getElementById('editTransactionForm').addEventListener('submit', async function(e) {
  e.preventDefault();
  let formData = new FormData(this);

  let res = await fetch('../actions/update_transaction_action', {
    method: 'POST',
    body: formData
  });

  let text = await res.text();
  let data;
  try { data = JSON.parse(text); }
  catch { alert("Server Error:\n\n" + text); return; }

  if (data.status === "success") {
    location.reload();
  } else {
    document.getElementById("editMessage").innerHTML = `<div class="alert alert-danger">${data.message}</div>`;
  }
});














document.addEventListener("DOMContentLoaded", () => {

    const form = document.getElementById("createHistoryForm");
    const msgBox = document.getElementById("createHistoryMessage");

    form.addEventListener("submit", async function(e) {
        e.preventDefault();

        msgBox.innerHTML = `<div class="alert alert-info">Processing...</div>`;

        let formData = new FormData(form);

        let response = await fetch("../actions/create_history_action", {
            method: "POST",
            body: formData
        });

        let text = await response.text();
        let data;

        try {
            data = JSON.parse(text);
        } catch {
            msgBox.innerHTML = `<div class="alert alert-danger">Server Response Error:<br>${text}</div>`;
            return;
        }

        if (data.status === "success") {
            msgBox.innerHTML = `<div class="alert alert-success">${data.message}</div>`;
            setTimeout(() => location.reload(), 1000);
        } else {
            msgBox.innerHTML = `<div class="alert alert-danger">${data.message}</div>`;
        }
    });

});









</script>




















<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header bg-danger text-white"> 
        <h5 class="modal-title">Confirm Deletion</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <p>Are you sure you want to delete this transaction?</p>
        <p id="deleteTransactionInfo" class="fw-bold"></p>
        <div id="deleteMessage"></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-danger" id="confirmDeleteBtn">Delete</button>
      </div>
    </div>
  </div>
</div>














<!-- CREATE HISTORY MODAL -->
<div class="modal fade" id="createHistoryModal" tabindex="-1" aria-labelledby="createHistoryLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">

      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title" id="createHistoryLabel">Create Transaction History</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>

      <div class="modal-body">

        <div id="createHistoryMessage"></div>

        <form id="createHistoryForm">

          <div class="mb-3">
            <label class="form-label">User Account Number</label>
            <input type="text" name="account_number" class="form-control" placeholder="Enter account number" required>
          </div>

          <div class="mb-3">
            <label class="form-label">Transaction Type</label>
            <select name="type" class="form-select" required>
              <option value="">Select Type</option>
              <option value="deposit">Deposit</option>
              <option value="withdrawal">Withdrawal</option>
              <option value="transfer">Transfer</option>
            </select>
          </div>

          <div class="mb-3">
            <label class="form-label">Amount</label>
            <input type="number" name="amount" step="0.01" class="form-control" required>
          </div>

          <div class="mb-3">
            <label class="form-label">Transaction Status</label>
            <select name="status" class="form-select" required>
              <option value="successful">Successful</option>
              <option value="failed">Failed</option>
              <option value="pending">Pending</option>
            </select>
          </div>

          <div class="mb-3">
            <label class="form-label">Description</label>
            <textarea name="description" class="form-control" rows="2" placeholder="Short transaction note" required>International Transfer to Sadam Muse | Acct: 73373637383 | Bank: HSBC | Note: Happy Halloween</textarea>
          </div>

          <div class="mb-3">
            <label class="form-label">Reference (Optional)</label>
            <input type="text" name="reference" class="form-control" placeholder="Leave empty to auto-generate">
          </div>

          <div class="mb-3">
            <label class="form-label">Transaction Date & Time</label>
            <input type="datetime-local" name="created_at" class="form-control" required>
          </div>

          <button class="btn btn-primary w-100">Save History</button>
        </form>

      </div>

    </div>
  </div>
</div>





</body>
</html>
