<?php
include("db_connect.php");

date_default_timezone_set('Africa/Nairobi');
$today = date('Y-m-d');

// Fetch sales for today with time
$query = "
    SELECT s.*, p.name AS product_name 
    FROM sales s
    JOIN products p ON s.product_id = p.id
    WHERE DATE(s.sale_datetime) = '$today'
    ORDER BY s.sale_datetime DESC
";
$result = mysqli_query($conn, $query);

$total_sales = 0;
$total_profit = 0;
?>

<!DOCTYPE html>
<html>
<head>
    <title>Today's Sales Summary</title>
    <style>
       .styled-link {
        align-items: center;
        display: inline-block;
        padding: 10px 20px;
        background-color: #007bff;
        color: white;
        text-decoration: none;
        border-radius: 5px;
        font-weight: bold;
        transition: background-color 0.3s ease;

       }
        
        table { border-collapse: collapse; width: 95%; margin: auto; }
        th, td { border: 1px solid #ccc; padding: 10px; text-align: center; }
        th { background-color: #007bff; color: white; }
        h2 { text-align: center; margin-top: 20px; }
        .totals { text-align: center; margin-top: 15px; font-weight: bold; }
    </style>
</head>
<body>
    
    <h2>Sales Summary for <?= $today ?></h2>
    <div style="text-align: center; margin-top: 20px;">
    <a href="admin_dashboard.php" class="styled-link">Return to Dashboard</a><br>
</div>
    
    <table>
        <tr>
            <th>Date & Time</th>
            <th>Cashier</th>
            <th>Product</th>
            <th>Quantity</th>
            <th>Buying Price</th>
            <th>Selling Price</th>
            <th>Total Sale</th>
            <th>Profit</th>
        </tr>
        <?php while ($row = mysqli_fetch_assoc($result)): 
            $total_sales += $row['total_sale'];
            $total_profit += $row['profit'];
        ?>
        <tr>
            <td><?= date('Y-m-d H:i:s', strtotime($row['sale_datetime'])) ?></td>
            <td><?= $row['cashier'] ?></td>
            <td><?= $row['product_name'] ?></td>
            <td><?= $row['quantity'] ?></td>
            <td><?= number_format($row['buying_price'], 2) ?></td>
            <td><?= number_format($row['selling_price'], 2) ?></td>
            <td><?= number_format($row['total_sale'], 2) ?></td>
            <td><?= number_format($row['profit'], 2) ?></td>
        </tr>
        <?php endwhile; ?>
    </table>

    <div class="totals">
        <p>Total Sales: KES <?= number_format($total_sales, 2) ?></p>
        <p>Total Profit: KES <?= number_format($total_profit, 2) ?></p>
    </div>
    <?php include 'footer.php'; ?>
</body>
</html>
