<?php
require_once "../config/auth.php";
require_once "../config/db.php";
require_once "../config/helpers.php";

$pageTitle = "Service Profit";
require_once "../includes/header.php";
require_once "../includes/sidebar.php";
require_once "../includes/topbar.php";

// ================= DATA =================
$result = $conn->query("
SELECT 
    s.id,
    s.service_name,
    s.type,
    s.amount,
    s.cost,
    (s.amount - s.cost) AS profit,
    c.name AS customer
FROM services s
JOIN customers c ON s.customer_id = c.id
ORDER BY profit DESC
");
?>

<div class="main-content">
<div class="col-lg-12">

<div class="topbar">
    <h5><i class="fa fa-chart-line"></i> Service Profit Report</h5>
</div>

<div class="p-4">

<div class="table-responsive">

<table class="table table-bordered table-striped">

<thead class="table-dark">
<tr>
    <th>Service</th>
    <th>Customer</th>
    <th>Selling</th>
    <th>Cost</th>
    <th>Profit</th>
</tr>
</thead>

<tbody>

<?php if($result->num_rows > 0){ ?>
    <?php while($row = $result->fetch_assoc()){ ?>

    <tr>
        <td><?= e($row['service_name']) ?></td>
        <td><?= e($row['customer']) ?></td>

        <td>₹<?= number_format($row['amount'],2) ?></td>
        <td>₹<?= number_format($row['cost'],2) ?></td>

        <td>
            <?php 
            $profit = $row['profit'];
            $color = $profit >= 0 ? 'success' : 'danger';
            ?>
            <span class="badge bg-<?= $color ?>">
                ₹<?= number_format($profit,2) ?>
            </span>
        </td>
    </tr>

    <?php } ?>
<?php } else { ?>
<tr>
<td colspan="5" class="text-center">No data found</td>
</tr>
<?php } ?>

</tbody>

</table>

</div>

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

<?php require_once "../includes/footer.php"; ?>
