<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

$pageName = "All Transactions";
include($_SERVER['DOCUMENT_ROOT'] . "/admin/layout/header.php");

?>

<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <section class="content-header">
        <h1>
            All Transactions
            <small>Complete transaction history</small>
        </h1>
        <ol class="breadcrumb">
            <li><a href="./dashboard.php"><i class="fa fa-dashboard"></i> Dashboard</a></li>
            <li class="active">All Transactions</li>
        </ol>
    </section>

    <!-- Main content -->
    <section class="content">

        
        <div class="row">
            <div class="col-xs-12">
                <div class="box">
                    <div class="box-header with-border">
                        <h3 class="box-title">Transaction Records</h3>

                        <!-- Filter Form -->
                        <div class="box-tools pull-right">
                            <form method="GET" action="" class="form-inline" style="margin-top:5px;">
                                <div class="form-group" style="margin-right:5px;">
                                    <select name="trans_type" class="form-control input-sm">
                                        <option value="">-- All Types --</option>
                                        <option value="Interbank transfer"   <?= (isset($_GET['trans_type']) && $_GET['trans_type'] == 'Interbank transfer')   ? 'selected' : '' ?>>Interbank Transfer</option>
                                        <option value="Local transfer"       <?= (isset($_GET['trans_type']) && $_GET['trans_type'] == 'Local transfer')       ? 'selected' : '' ?>>Local Transfer</option>
                                        <option value="Crypto"               <?= (isset($_GET['trans_type']) && $_GET['trans_type'] == 'Crypto')               ? 'selected' : '' ?>>Crypto</option>
                                        <option value="Deposit"              <?= (isset($_GET['trans_type']) && $_GET['trans_type'] == 'Deposit')              ? 'selected' : '' ?>>Deposit</option>
                                        <option value="Withdrawal"           <?= (isset($_GET['trans_type']) && $_GET['trans_type'] == 'Withdrawal')           ? 'selected' : '' ?>>Withdrawal</option>
                                    </select>
                                </div>
                                <div class="form-group" style="margin-right:5px;">
                                    <select name="trans_status" class="form-control input-sm">
                                        <option value="">-- All Statuses --</option>
                                        <option value="approved" <?= (isset($_GET['trans_status']) && $_GET['trans_status'] == 'approved') ? 'selected' : '' ?>>Approved</option>
                                        <option value="pending"  <?= (isset($_GET['trans_status']) && $_GET['trans_status'] == 'pending')  ? 'selected' : '' ?>>Pending</option>
                                        <option value="failed"   <?= (isset($_GET['trans_status']) && $_GET['trans_status'] == 'failed')   ? 'selected' : '' ?>>Failed</option>
                                    </select>
                                </div>
                                <button type="submit" class="btn btn-primary btn-sm">
                                    <i class="fa fa-filter"></i> Filter
                                </button>
                                <a href="./transactions.php" class="btn btn-default btn-sm">
                                    <i class="fa fa-refresh"></i> Reset
                                </a>
                            </form>
                        </div>
                    </div>

                    <!-- /.box-header -->
                    <div class="box-body">
                        <div class="table-responsive">
                            <table id="allTransTable" class="table table-bordered table-hover table-striped">
                                <thead>
                                    <tr>
                                        <th>S/N</th>
                                        <th>Date / Time</th>
                                        <th>User</th>
                                        <th>Amount</th>
                                        <th>Account Name</th>
                                        <th>Account No.</th>
                                        <th>Bank Name</th>
                                        <th>Trans Type</th>
                                        <th>Direction</th>
                                        <th>Reference ID</th>
                                        <th>Status</th>
                                        <th class="text-center dt-no-sorting">Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    // Build dynamic query with optional filters
                                    $conditions = [];
                                    $params     = [];

                                    if (!empty($_GET['trans_type'])) {
                                        $conditions[] = "t.trans_type = :trans_type";
                                        $params[':trans_type'] = $_GET['trans_type'];
                                    }

                                    if (!empty($_GET['trans_status'])) {
                                        $conditions[] = "t.trans_status = :trans_status";
                                        $params[':trans_status'] = $_GET['trans_status'];
                                    }

                                    $whereClause = count($conditions) ? "WHERE " . implode(" AND ", $conditions) : "";

                                    $sql = "SELECT 
                                                t.trans_id,
                                                t.user_id,
                                                t.amount,
                                                t.account_name,
                                                t.account_number,
                                                t.bank_name,
                                                t.trans_type,
                                                t.transaction_type,
                                                t.trans_status,
                                                t.refrence_id,
                                                t.trans_date,
                                                t.trans_time,
                                                u.firstname,
                                                u.lastname
                                            FROM transactions t
                                            LEFT JOIN users u ON t.user_id = u.id
                                            $whereClause
                                            ORDER BY t.trans_id DESC";

                                    $stmt = $conn->prepare($sql);
                                    $stmt->execute($params);
                                    $sn = 1;

                                    while ($result = $stmt->fetch(PDO::FETCH_ASSOC)):
                                        $transStatus = TranStatus($result);
                                        $fullName    = htmlspecialchars(($result['firstname'] ?? '') . " " . ($result['lastname'] ?? ''));
                                        $amount      = (float)($result['amount'] ?? 0);
                                        $refId       = $result['refrence_id'] ?? '';
                                        $transType   = $result['trans_type'] ?? 'N/A';
                                        $direction   = $result['transaction_type'] ?? 'N/A';

                                        // Direction badge
                                        if (strtolower($direction) == 'credit') {
                                            $dirBadge = '<span class="label label-success">Credit</span>';
                                        } elseif (strtolower($direction) == 'debit') {
                                            $dirBadge = '<span class="label label-danger">Debit</span>';
                                        } else {
                                            $dirBadge = '<span class="label label-default">' . htmlspecialchars($direction) . '</span>';
                                        }

                                        // Trans type badge color
                                        $typeColors = [
                                            'Interbank transfer' => 'primary',
                                            'Local transfer'     => 'info',
                                            'Crypto'             => 'warning',
                                            'Deposit'            => 'success',
                                            'Withdrawal'         => 'danger',
                                        ];
                                        $typeColor = $typeColors[$transType] ?? 'default';
                                    ?>
                                        <tr>
                                            <td><?= $sn++ ?></td>
                                            <td>
                                                <small>
                                                    <?= htmlspecialchars($result['trans_date'] ?? '') ?><br>
                                                    <span class="text-muted"><?= htmlspecialchars($result['trans_time'] ?? '') ?></span>
                                                </small>
                                            </td>
                                            <td><?= $fullName ?></td>
                                            <td><strong><?= number_format($amount, 2, '.', ',') ?></strong></td>
                                            <td><?= htmlspecialchars($result['account_name'] ?? 'N/A') ?></td>
                                            <td><?= htmlspecialchars($result['account_number'] ?? 'N/A') ?></td>
                                            <td><?= htmlspecialchars($result['bank_name'] ?? 'N/A') ?></td>
                                            <td>
                                                <span class="label label-<?= $typeColor ?>">
                                                    <?= htmlspecialchars($transType) ?>
                                                </span>
                                            </td>
                                            <td><?= $dirBadge ?></td>
                                            <td><small><?= htmlspecialchars($refId) ?></small></td>
                                            <td><?= $transStatus ?></td>
                                            <td class="text-center">
                                                <a href="./view-transaction.php?id=<?= urlencode($refId) ?>" class="btn btn-primary btn-xs" title="View / Edit">
                                                    <i class="fa fa-eye"></i> View
                                                </a>
                                                <a href="./delete-transaction.php?id=<?= urlencode($refId) ?>"
                                                   class="btn btn-danger btn-xs confirm-delete" title="Delete">
                                                    <i class="fa fa-trash"></i> Del
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endwhile; ?>
                                </tbody>
                                <tfoot>
                                    <tr>
                                        <th>S/N</th>
                                        <th>Date / Time</th>
                                        <th>User</th>
                                        <th>Amount</th>
                                        <th>Account Name</th>
                                        <th>Account No.</th>
                                        <th>Bank Name</th>
                                        <th>Trans Type</th>
                                        <th>Direction</th>
                                        <th>Reference ID</th>
                                        <th>Status</th>
                                        <th></th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                    <!-- /.box-body -->
                </div>
                <!-- /.box -->
            </div>
            <!-- /.col -->
        </div>
        <!-- /.row -->
    </section>
    <!-- /.content -->
</div>
<!-- /.content-wrapper -->

<script>
$(document).ready(function () {
    $('#allTransTable').DataTable({
        "order": [[0, "desc"]],
        "pageLength": 25,
        "responsive": true,
        "columnDefs": [
            { "orderable": false, "targets": 11 }
        ]
    });

    // Confirm before delete
    $(document).on('click', '.confirm-delete', function (e) {
        if (!confirm('Are you sure you want to delete this transaction? This action cannot be undone.')) {
            e.preventDefault();
        }
    });
});
</script>

<?php
include($_SERVER['DOCUMENT_ROOT'] . "/admin/layout/footer.php");
?>