<?php
session_start();
require_once '../assets/db_connect.php';

if (!isset($_SESSION['user'])) { 
    echo "Access denied"; 
    exit; 
}

$user_role = $_SESSION['user']['role'];
$user_shop_id = $_SESSION['user']['shop_id'];

$date = $_GET['date'] ?? date('Y-m-d');
$shop_id = $_GET['shop_id'] ?? 0;

// Fetch shop name
if ($shop_id == 0) {
    $shop_name = "All Shops";
} else {
    $stmt = $pdo->prepare("SELECT name FROM shops WHERE id=?");
    $stmt->execute([$shop_id]);
    $shop_name = $stmt->fetchColumn();
}

// Fetch daily sales
$sql = "
 SELECT
   COUNT(DISTINCT s.id) AS invoices,
   SUM(s.total) AS total_revenue,
   SUM(sl.qty) AS total_qty
 FROM sales s
 JOIN sale_lines sl ON sl.sale_id = s.id
 WHERE DATE(s.sale_date) = ?
";

$params = [$date];

if($shop_id && $shop_id != 0){
    $sql .= " AND s.shop_id = ?";
    $params[] = $shop_id;
}

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
    <title>Print Sales</title>
    <link rel="stylesheet" href="../libraries/bootstrap.css">

    <style>
        @media print {
            .no-print { display: none; }
            body { background: white; margin: 20px; }
            h3 { margin-bottom: 20px; }
            table { font-size: 14px; }
        }
        body { padding: 20px; }
    </style>
   
</head>
<body>

<div class="no-print mb-3">
    <button class="btn btn-primary" onclick="window.print()">
        <i class="fa fa-print"></i> Print Now
    </button>
</div>

<h3 class="text-center">Daily Sales Report</h3>
<h5 class="text-center"><?= htmlspecialchars($date) ?></h5>
<h6 class="text-center">Shop: <?= htmlspecialchars($shop_name) ?></h6>
<hr>

<table class="table table-bordered">
    <tr>
        <th>Total Invoices</th>
        <td><?= $row['invoices'] ?? 0 ?></td>
    </tr>
    <tr>
        <th>Total Revenue</th>
        <td><?= number_format($row['total_revenue'] ?? 0, 2) ?></td>
    </tr>
    <tr>
        <th>Total Quantity Sold</th>
        <td><?= $row['total_qty'] ?? 0 ?></td>
    </tr>
</table>

<p class="text-center mt-4">Printed on: <?= date("Y-m-d H:i") ?></p>

</body>
</html>
