<?php include 'inc/funtions.php';
if (isset($_SESSION['user_type']) && $_SESSION['user_type'] == 'Admin') {
    $user_id = $_SESSION['user_id'];
    $business_id = $_SESSION['business_id'];
    $user = getUserId($user_id);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Transaction Management | Admin</title>
    <link rel="stylesheet" href="assets/css/bootstrap.css">
    <link rel="stylesheet" href="assets/vendors/simple-datatables/style.css">
    <link rel="stylesheet" href="assets/css/app.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="shortcut icon" href="assets/images/favicon.png" type="image/x-icon">
</head>
<body>
    <div id="app">
        <?php include('inc/header.php'); ?>            
        <div class="main-content container-fluid">
            <div class="mb-4 d-flex justify-content-between align-items-center">
                <h3>Financial Management</h3>
                <span class="badge bg-primary px-3 py-2 rounded-pill">Admin Control</span>
            </div> 

            <section class="section mb-5">
                <div class="card border-0 shadow-sm rounded-4">
                    <div class="card-header bg-white"><h5 class="fw-bold">Export Customer Statement</h5></div>
                    <div class="card-body">
                        
                        <form action="" method="GET" class="row g-3">
                            <div class="col-md-3">
                                <label class="small fw-bold">Select Customer</label>
                                <select name="customer_id" class="form-select" required>
                                    <option value="">Choose Customer...</option>
                                    <?php 
                                    $customers = Querydb("SELECT customer_id, name FROM customers WHERE business_id = '$business_id'");
                                    if ($customers) {
                                        foreach($customers as $c) echo "<option value='{$c['customer_id']}'>{$c['name']}</option>";
                                    } else {echo "<option value=''>No Customers Found for your Business</option>";}
                                    ?>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="small fw-bold">Start Date</label>
                                <input type="date" name="start_date" class="form-control" required>
                            </div>
                            <div class="col-md-3">
                                <label class="small fw-bold">End Date</label>
                                <input type="date" name="end_date" class="form-control" required>
                            </div>
                            <div class="col-md-3 d-flex align-items-end gap-2">
                                <button type="submit" name="format" value="csv" class="btn btn-success flex-grow-1 rounded-pill fw-bold">
                                    <i class="fas fa-file-csv"></i> CSV
                                </button>
                                <button type="submit" name="format" value="pdf" class="btn btn-danger flex-grow-1 rounded-pill fw-bold">
                                    <i class="fas fa-file-pdf"></i> PDF
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </section>

            <section class="section">
                <div class="card border-0 shadow-sm rounded-4">
                    <div class="card-header bg-white py-3 d-flex justify-content-between">
                        <h5 class="fw-bold mb-0">Pending Credit Approvals</h5>
                    </div>
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0" id="table1">
                            <thead>
                                <tr>
                                    <th>TRANSACTION ID</th>
                                    <th>DESCRIPTION</th>
                                    <th>BAL BEFORE</th>
                                    <th>AMOUNT</th>
                                    <th>BAL AFTER</th>
                                    <th>TRANSACTION STATUS</th>
                                    <th class="text-center">ACTION</th>
                                </tr>
                            </thead>
                            <tbody class="text-center">
                                <?php
                                // Fetch only pending credits/topups
                                $credits = Querydb("SELECT t.*, c.name as customer_name FROM transactions t JOIN customers c ON t.customer_id = c.customer_id WHERE t.business_id = '$business_id' ORDER BY t.transaction_id DESC");
                                while($row = mysqli_fetch_assoc($credits)) { ?>
                                <tr style="cursor: pointer;" onclick="viewTransactionDetails('<?php echo $row['transaction_id']; ?>')">
                                    <td><?php echo $row['trans_id']; ?></td>
                                    <td><?php echo $row['description']; ?></td>
                                    <td class="text-muted small">₦<?php echo number_format($row['bal_before'], 2); ?></td>
                                    <td class="fw-bold <?php echo (strtolower($row['type']) == 'credit') ? 'text-success' : 'text-danger'; ?>">
                                        <?php echo (strtolower($row['type']) == 'credit' ? '+' : '-') . ' ₦' . number_format(abs($row['amount']), 2); ?>
                                    </td>
                                    <td class="fw-bold">₦<?php echo number_format($row['bal_after'], 2); ?></td>
                                    <td>
                                        <span class="badge rounded-pill <?php 
                                            if($row['transaction_status'] == 'Completed' || $row['transaction_status'] == 'Successful') echo 'bg-light-success text-success';
                                            elseif($row['transaction_status'] == 'Pending') echo 'bg-light-warning text-warning';
                                            else echo 'bg-light-danger text-danger'; 
                                        ?>">
                                            <?php echo $row['transaction_status']; ?>
                                        </span>
                                    </td>
                                    <td class="text-center" onclick="event.stopPropagation();">
                                        <?php if($row['transaction_status'] == 'Pending') { ?>
                                            <button onclick="approveCredit('<?php echo $row['transaction_id']; ?>', 'Approve')" class="btn btn-success btn-sm rounded-pill">Approve</button>
                                            <button onclick="approveCredit('<?php echo $row['transaction_id']; ?>', 'Decline')" class="btn btn-danger btn-sm rounded-pill">Decline</button>
                                        <?php } ?>
                                    </td>
                                </tr>
                                <?php } ?>
                                <div class="modal fade" id="transactionDetailModal" tabindex="-1" aria-hidden="true">
                                    <div class="modal-dialog modal-dialog-centered">
                                        <div class="modal-content border-0 shadow rounded-4">
                                            <div class="modal-header border-0">
                                                <h5 class="fw-bold">Transaction Details</h5>
                                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                            </div>
                                            <div class="modal-body" id="transaction_details_content">
                                                <div class="text-center p-4">
                                                    <div class="spinner-border text-primary" role="status"></div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </tbody>
                        </table>
                    </div>
                </div>
            </section>
        </div>
        <?php include('inc/footer.php'); ?>
    </div>

    <script src="assets/js/feather-icons/feather.min.js"></script>
    <script src="assets/vendors/perfect-scrollbar/perfect-scrollbar.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <script>
    function approveCredit(id, action) {
        Swal.fire({
            title: `Are you sure you want to ${action}?`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, proceed!'
        }).then((result) => {
            if (result.isConfirmed) {
                $.post('inc/code_query.php', {
                    action: 'admin_verify_topup',
                    topup_id: id,
                    status: action
                }, function(res) {
                    if(res.trim() == "1") {
                        Swal.fire('Success!', 'Transaction updated.', 'success').then(() => location.reload());
                    } else {
                        Swal.fire('Error', res, 'error');
                    }
                });
            }
        });
    }
    </script>
</body>
</html>
<?php 
} else {
    header('Location: pages-error-404.html');
    exit;
} ?>