<?php
require '../includes/db.php';
require '../includes/functions.php';

// ===============================
// ✅ HANDLE PAYMENT
// ===============================
if(isset($_GET['pay'])){

    $bill_id = (int)$_GET['pay'];

    $bill = $conn->prepare("SELECT * FROM billings WHERE id=? LIMIT 1");
    $bill->bind_param("i", $bill_id);
    $bill->execute();
    $result = $bill->get_result();
    $b = $result->fetch_assoc();

    if($b && $b['status'] != 'paid'){

        // Mark billing as paid
        $update = $conn->prepare("UPDATE billings SET status='paid' WHERE id=?");
        $update->bind_param("i", $bill_id);
        $update->execute();

        // Add balance
        $bal = $conn->prepare("UPDATE users SET balance = balance + ? WHERE id=?");
        $bal->bind_param("di", $b['amount'], $b['user_id']);
        $bal->execute();
    }

    header("Location: billings.php");
    exit;
}

// ===============================
// 🗑️ HANDLE DELETE
// ===============================
if(isset($_GET['delete'])){

    $id = (int)$_GET['delete'];

    $stmt = $conn->prepare("DELETE FROM billings WHERE id=?");
    $stmt->bind_param("i", $id);

    if($stmt->execute()){
        header("Location: billings.php?msg=deleted");
        exit;
    } else {
        echo "Error deleting record";
    }
}
?>

<?php include 'includes/header.php'; ?>
<?php include 'includes/sidebar.php'; ?>

<?php
// SUCCESS MESSAGE
if(isset($_GET['msg']) && $_GET['msg'] == 'deleted'){
    echo '<div class="alert alert-success">Billing deleted successfully</div>';
}

// FETCH DATA
$res = mysqli_query($conn,"
SELECT b.*,u.email FROM billings b
JOIN users u ON u.id=b.user_id
ORDER BY b.id DESC
");
?>

<div class="container-fluid">

    <div class="row">
        <div class="col-xl-8 col-lg-11 mx-auto">

            <div class="card p-3">

                <!-- Header -->
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h4 class="text-primary mb-0">📄 Billings</h4>
                </div>

                <!-- Table -->
                <div class="table-responsive">
                    <table class="table table-dark table-hover align-middle">

                        <thead>
                            <tr>
                                <th>User</th>
                                <th>Amount</th>
                                <th>Status</th>
                                <th>Action</th>
                            </tr>
                        </thead>

                        <tbody>

                        <?php while($b=mysqli_fetch_assoc($res)): ?>
                            <tr>

                                <td><?php echo $b['email']; ?></td>

                                <td>
                                    <span class="fw-semibold text-info">
                                        BTC <?php echo $b['amount']; ?>
                                    </span>
                                </td>

                                <td>
                                    <?php if($b['status']=='paid'): ?>
                                        <span class="badge bg-success">Paid ✅</span>
                                    <?php else: ?>
                                        <span class="badge bg-warning text-dark">Pending</span>
                                    <?php endif; ?>
                                </td>

                                <td>

                                    <?php if($b['status']=='pending'): ?>
                                        <a href="?pay=<?php echo $b['id']; ?>" 
                                           class="btn btn-sm btn-success">
                                           Mark Paid
                                        </a>
                                    <?php else: ?>
                                        <span class="text-success small">Completed</span>
                                    <?php endif; ?>

                                    <!-- DELETE BUTTON -->
                                    <a href="?delete=<?php echo $b['id']; ?>" 
                                       class="btn btn-sm btn-danger ms-2"
                                       onclick="return confirm('Delete this billing?')">
                                       Delete
                                    </a>

                                </td>

                            </tr>
                        <?php endwhile; ?>

                        </tbody>

                    </table>
                </div>

            </div>

        </div>
    </div>

</div>

<?php include 'includes/footer.php'; ?>