<?php
session_start();
require_once '../assets/db_connect.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';
if (!isset($_SESSION['user']) || $_SESSION['user']['role']!=='admin') { echo "Access denied"; exit; }

$sql = "
 SELECT s.id, s.name, COUNT(p.id) AS invoices, COALESCE(SUM(p.total),0) AS total_supplied
 FROM suppliers s
 LEFT JOIN purchases p ON p.supplier_id = s.id
 GROUP BY s.id
 ORDER BY total_supplied DESC
";
$rows = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
?>

<style>
/* Back button styling - consistent with other pages */
.back-btn {
    display: inline-block;
    padding: 8px 16px;
    background-color: #6c757d;
    color: white;
    text-decoration: none;
    border-radius: 4px;
    border: none;
    cursor: pointer;
    font-size: 14px;
    margin-bottom: 15px;
    transition: background-color 0.2s;
}
.back-btn:hover {
    background-color: #5a6268;
    color: white;
    text-decoration: none;
}
.back-btn i {
    margin-right: 5px;
}
</style>

<div class="col-md-10 ml-sm-auto px-4 py-4">

<!-- BACK BUTTON at the top -->
<div class="mb-3">
    <a href="daily_sales.php" class="back-btn">
        <i>←</i> Back to Reports
    </a>
</div>

<h3 class="text-success">Supplier Purchase Summary</h3>

<div class="table-responsive">
<table class="table table-sm table-bordered">
<thead class="thead-dark">
    <tr>
        <th>#</th>
        <th>Supplier</th>
        <th>Invoices</th>
        <th>Total Supplied</th>
    </tr>
</thead>
<tbody>
<?php 
$total_invoices = 0;
$total_amount = 0;
$i = 1;

foreach($rows as $r): 
    $total_invoices += $r['invoices'];
    $total_amount += $r['total_supplied'];
?>
<tr>
    <td><?= $i++ ?></td>
    <td><?= htmlspecialchars($r['name']) ?></td>
    <td><?= $r['invoices'] ?></td>
    <td><?= number_format($r['total_supplied'],2) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
<tfoot>
    <tr class="table-secondary">
        <td colspan="2" class="text-right"><strong>Totals:</strong></td>
        <td><strong><?= $total_invoices ?></strong></td>
        <td><strong><?= number_format($total_amount,2) ?></strong></td>
    </tr>
</tfoot>
</table>
</div>

<!-- BACK BUTTON at the bottom -->
<div class="mt-4">
    <a href="daily_sales.php" class="back-btn">
        <i>←</i> Back to Reports
    </a>
</div>

</div>

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