<?= $this->extend('admin/layout') ?>

<?= $this->section('content') ?>
<div class="container-fluid">
    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
        <h1 class="h2">Transactions</h1>
        <div class="btn-toolbar mb-2 mb-md-0">
            <button id="export-excel" class="btn btn-success me-2">
                <i class="bi bi-file-earmark-excel"></i> Export to Excel
            </button>
            <form action="<?= base_url('admin/delete-failed-transactions') ?>" method="POST" class="d-inline" onsubmit="return confirm('Are you sure you want to delete ALL failed transactions? This action cannot be undone.')">
                <button type="submit" class="btn btn-danger me-2">
                    <i class="bi bi-trash"></i> Delete Failed Transactions
                </button>
            </form>
            <form action="<?= base_url('admin/delete-expired-subscription-transactions') ?>" method="POST" class="d-inline me-2" onsubmit="return confirm('Are you sure you want to delete ALL expired subscription transactions? This action cannot be undone.')">
                <button type="submit" class="btn btn-warning">
                    <i class="bi bi-clock-history"></i> Delete Expired Subscriptions
                </button>
            </form>
            <form action="<?= base_url('admin/award-pending-subscriptions') ?>" method="POST" class="d-inline" onsubmit="return confirm('Are you sure you want to award ALL pending subscriptions? This will create subscriptions for all successful subscription transactions that don\'t have subscriptions yet.')">
                <button type="submit" class="btn btn-primary">
                    <i class="bi bi-person-check-fill"></i> Award Pending Subscriptions
                </button>
            </form>
        </div>
    </div>

    <!-- Filters and Search -->
    <div class="card mb-4">
        <div class="card-body">
            <form method="get" action="" class="row g-3">
                <div class="col-md-3">
                    <div class="input-group">
                        <span class="input-group-text"><i class="bi bi-search"></i></span>
                        <input type="text" class="form-control" name="search" placeholder="Transaction ID or Phone" value="<?= $current_search ?? '' ?>">
                    </div>
                </div>
                <div class="col-md-3">
                    <select class="form-select" name="author">
                        <option value="">All Authors</option>
                        <?php foreach ($authors as $author): ?>
                            <option value="<?= $author->author_name ?>" <?= ($current_author ?? '') == $author->author_name ? 'selected' : '' ?>>
                                <?= $author->author_name ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <select class="form-select" name="status">
                        <option value="">All Status</option>
                        <option value="0" <?= ($current_status ?? '') === '0' ? 'selected' : '' ?>>Pending</option>
                        <option value="1" <?= ($current_status ?? '') === '1' ? 'selected' : '' ?>>Success</option>
                        <option value="2" <?= ($current_status ?? '') === '2' ? 'selected' : '' ?>>Failed</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <select class="form-select" name="type">
                        <option value="">All Types</option>
                        <option value="tip" <?= ($current_type ?? '') === 'tip' ? 'selected' : '' ?>>Tip Purchase</option>
                        <option value="subscription" <?= ($current_type ?? '') === 'subscription' ? 'selected' : '' ?>>Subscription</option>
                    </select>
                </div>
                <div class="col-md-2 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary me-2">Apply Filters</button>
                    <a href="<?= current_url() ?>" class="btn btn-outline-secondary">Clear</a>
                </div>
            </form>
        </div>
    </div>

    <!-- Transactions Table -->
    <div class="card">
        <div class="card-body">
            <div class="table-responsive">
                <table id="transactions-table" class="table table-striped table-hover">
                    <thead>
                        <tr>
                            <th>Transaction ID</th>
                            <th>Phone</th>
                            <th>Amount</th>
                            <th>Status</th>
                            <th>Type</th>
                            <th>Category</th>
                            <th>Author Name</th>
                            <th>Date</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($transactions as $txn): 
                            // Author: use tip_author (from tips join) when available, else parse narration (e.g. cash "Title by Author")
                            $authorName = $txn->tip_author ?? null;
                            if (empty($authorName) && !empty($txn->narration)) {
                                $parts = explode(' by ', $txn->narration);
                                if (count($parts) > 1) {
                                    $authorName = trim($parts[1]);
                                }
                            }
                            
                            // Determine status class
                            $statusClass = '';
                            $statusText = '';
                            if ($txn->status == 1) {
                                $statusClass = 'bg-success';
                                $statusText = 'SUCCESS';
                            } elseif ($txn->status == 2) {
                                $statusClass = 'bg-danger';
                                $statusText = 'FAILED';
                            } else {
                                $statusClass = 'bg-warning';
                                $statusText = 'PENDING';
                            }

                            // Check if tip unlock record exists
                            $unlockModel = new \App\Models\TipsUnlockModel();
                            $hasUnlockRecord = $unlockModel->where([
                                'msisdn' => $txn->msisdn,
                                'tip_id' => $txn->tip_id
                            ])->first();

                            // Determine transaction type
                            $transactionType = !empty($txn->plan_id) ? 'Subscription' : 'Tip Purchase';
                            $typeClass = !empty($txn->plan_id) ? 'bg-primary' : 'bg-info';
                        ?>
                            <tr>
                                <td><?= $txn->transaction_id ?></td>
                                <td><?= $txn->msisdn ?></td>
                                <td><?= number_format($txn->amount, 2) ?></td>
                                <td><span class="badge <?= $statusClass ?>"><?= $statusText ?></span></td>
                                <td><span class="badge <?= $typeClass ?>"><?= $transactionType ?></span></td>
                                <td><?= $txn->category ?></td>
                                <td><?= !empty($authorName) ? esc($authorName) : 'N/A' ?></td>
                                <td><?= date('M d, Y H:i', strtotime($txn->created_at)) ?></td>
                                <td>
                                    <?php if ($txn->status == 0): ?>
                                        <!-- Pending transactions - show Success/Failed buttons -->
                                        <form action="<?= base_url('admin/update-transaction-status/' . $txn->transaction_id) ?>" method="POST" class="d-inline">
                                            <input type="hidden" name="status" value="1">
                                            <button type="submit" class="btn btn-sm btn-success me-1" onclick="return confirm('Mark this transaction as Success?')">
                                                <i class="bi bi-check-circle"></i> Success
                                            </button>
                                        </form>
                                        <form action="<?= base_url('admin/update-transaction-status/' . $txn->transaction_id) ?>" method="POST" class="d-inline">
                                            <input type="hidden" name="status" value="2">
                                            <button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('Mark this transaction as Failed?')">
                                                <i class="bi bi-x-circle"></i> Failed
                                            </button>
                                        </form>
                                        
                                        <?php if (!empty($txn->plan_id)): ?>
                                            <div class="mt-1">
                                                <small class="text-muted">
                                                    <i class="bi bi-info-circle"></i> This is a subscription transaction
                                                </small>
                                            </div>
                                        <?php endif; ?>
                                    <?php elseif ($txn->status == 1): ?>
                                        <!-- Success transactions - show existing unlock/points functionality -->
                                        <?php if (!empty($txn->tip_id) && !$hasUnlockRecord): ?>
                                            <form action="<?= base_url('admin/manual-unlock/' . $txn->transaction_id) ?>" method="POST" class="d-inline">
                                                <button type="submit" class="btn btn-sm btn-success me-1" onclick="return confirm('Are you sure you want to unlock this tip?')">
                                                    <i class="bi bi-unlock"></i> Unlock Tip
                                                </button>
                                            </form>
                                        <?php elseif (!empty($txn->tip_id) && $hasUnlockRecord): ?>
                                            <span class="badge bg-success me-1">Tip Unlocked</span>
                                        <?php endif; ?>

                                        <?php if ($txn->points_awarded == 0): ?>
                                            <form action="<?= base_url('admin/award-points-transaction/' . $txn->transaction_id) ?>" method="POST" class="d-inline">
                                                <button type="submit" class="btn btn-sm btn-info me-1" onclick="return confirm('Are you sure you want to award points for this transaction?')">
                                                    <i class="bi bi-gift"></i> Award Points
                                                </button>
                                            </form>
                                        <?php elseif ($txn->points_awarded == 1): ?>
                                            <span class="badge bg-info me-1">Points Awarded</span>
                                        <?php endif; ?>

                                        <?php if (!empty($txn->plan_id)): ?>
                                            <?php
                                            // Check if subscription already exists for this transaction
                                            $subscriptionModel = new \App\Models\SubscriptionModel();
                                            $existingSubscription = $subscriptionModel->where('transaction_id', $txn->transaction_id)->first();
                                            ?>
                                            <?php if (!$existingSubscription): ?>
                                                <form action="<?= base_url('admin/manual-subscription/' . $txn->transaction_id) ?>" method="POST" class="d-inline">
                                                    <button type="submit" class="btn btn-sm btn-primary" onclick="return confirm('Are you sure you want to award subscription for this transaction?')">
                                                        <i class="bi bi-person-check"></i> Award Subscription
                                                    </button>
                                                </form>
                                            <?php else: ?>
                                                <span class="badge bg-primary">Subscription Awarded</span>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                    <?php elseif ($txn->status == 2): ?>
                                        <!-- Failed transactions - no actions available -->
                                        <span class="text-muted">No actions available</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>

<script>
$(document).ready(function() {
    // Initialize DataTable
    $('#transactions-table').DataTable({
        order: [[6, 'desc']], // Sort by date by default
        pageLength: 25,
        responsive: true
    });

    // Excel Export Functionality
    $('#export-excel').click(function() {
        const table = document.getElementById('transactions-table');
        const wb = XLSX.utils.table_to_book(table, {sheet: "Transactions"});
        const wbout = XLSX.write(wb, {bookType: 'xlsx', type: 'binary'});
        
        function s2ab(s) {
            const buf = new ArrayBuffer(s.length);
            const view = new Uint8Array(buf);
            for (let i = 0; i < s.length; i++) {
                view[i] = s.charCodeAt(i) & 0xFF;
            }
            return buf;
        }
        
        const currentDate = new Date().toISOString().slice(0,10);
        saveAs(new Blob([s2ab(wbout)], {type: "application/octet-stream"}), `Transactions_${currentDate}.xlsx`);
    });
});
</script>
<?= $this->endSection() ?>