<?php
session_start();
require_once '../config.php';

function e($v) {
    return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8');
}

function money($amount) {
    return number_format((float)$amount, 2);
}

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

/*
|--------------------------------------------------------------------------
| SUMMARY
|--------------------------------------------------------------------------
*/
$summary_sql = "
    SELECT 
        COUNT(*) AS total_bills,
        COALESCE(SUM(total_amount), 0) AS total_sales
    FROM bills
    WHERE DATE(created_at) = ?
";
$summary_stmt = $conn->prepare($summary_sql);
$summary_stmt->bind_param("s", $selected_date);
$summary_stmt->execute();
$summary_result = $summary_stmt->get_result();
$summary = $summary_result->fetch_assoc() ?: ['total_bills' => 0, 'total_sales' => 0];

$grand_bills = (int)$summary['total_bills'];
$grand_sales = (float)$summary['total_sales'];

/*
|--------------------------------------------------------------------------
| PANEL WISE BILLS
|--------------------------------------------------------------------------
*/
$panel_sql = "
    SELECT 
        CASE
            WHEN u.role = 'sales_manager' THEN 'Sales Manager'
            WHEN u.role = 'sales_executive' THEN 'Sales Executive'
            ELSE 'Other'
        END AS panel_name,
        COUNT(*) AS total_bills
    FROM bills b
    LEFT JOIN users u ON u.id = b.created_by
    WHERE DATE(b.created_at) = ?
    GROUP BY u.role
    ORDER BY 
        FIELD(u.role, 'sales_manager', 'sales_executive'),
        panel_name
";
$panel_stmt = $conn->prepare($panel_sql);
$panel_stmt->bind_param("s", $selected_date);
$panel_stmt->execute();
$panel_result = $panel_stmt->get_result();

$panel_data = [];
$panel_bill_map = [];
while ($row = $panel_result->fetch_assoc()) {
    $panel_data[] = $row;
    $panel_bill_map[$row['panel_name']] = (int)$row['total_bills'];
}

/*
|--------------------------------------------------------------------------
| PRODUCT WISE SALES
|--------------------------------------------------------------------------
*/
$product_sql = "
    SELECT 
        panel_name,
        product_name,
        SUM(qty) AS total_qty,
        SUM(product_total_with_gst) AS total_product_sales
    FROM (
        SELECT 
            CASE
                WHEN u.role = 'sales_manager' THEN 'Sales Manager'
                WHEN u.role = 'sales_executive' THEN 'Sales Executive'
                ELSE 'Other'
            END AS panel_name,

            bi.product_name,
            bi.qty,

            -- GST distributed per product (CORRECT)
            (bi.total / bill_sum.total_without_gst) * b.total_amount AS product_total_with_gst

        FROM bills b

        INNER JOIN bill_items bi ON bi.bill_id = b.id

        LEFT JOIN users u ON u.id = b.created_by

        -- total of items per bill
        INNER JOIN (
            SELECT bill_id, SUM(total) AS total_without_gst
            FROM bill_items
            GROUP BY bill_id
        ) bill_sum ON bill_sum.bill_id = b.id

        WHERE DATE(b.created_at) = ?
    ) t

    GROUP BY panel_name, product_name
    ORDER BY 
        FIELD(panel_name, 'Sales Manager', 'Sales Executive'),
        total_product_sales DESC
";
$product_stmt = $conn->prepare($product_sql);
$product_stmt->bind_param("s", $selected_date);
$product_stmt->execute();
$product_result = $product_stmt->get_result();

$grouped = [];
while ($row = $product_result->fetch_assoc()) {
    $grouped[$row['panel_name']][] = $row;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Daily Sales</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

<style>
body {
    font-family: 'Segoe UI', sans-serif;
    background: #eef2f7;
    margin: 0;
}

.container {
    margin-left: 250px;
    padding: 70px;
}

.card {
    background: #fff;
    padding: 25px;
    border-radius: 15px;
    box-shadow: 0 10px 25px rgba(0,0,0,0.05);
    margin-bottom: 25px;
}

h2 {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 25px;
    flex-wrap: wrap;
}

.filter {
    display: flex;
    gap: 10px;
    margin-bottom: 25px;
    align-items: center;
    flex-wrap: wrap;
}

.filter input {
    padding: 8px 12px;
    border: 1px solid #ccc;
    border-radius: 6px;
}

.filter button {
    background: #000;
    color: #fff;
    border: none;
    padding: 8px 15px;
    border-radius: 6px;
    cursor: pointer;
}

.summary {
    display: flex;
    gap: 20px;
    margin-bottom: 25px;
    flex-wrap: wrap;
}

.box {
    flex: 1;
    min-width: 240px;
    display: flex;
    align-items: center;
    gap: 15px;
    padding: 20px;
    border-radius: 12px;
    color: #000;
    background: #fff;
    box-shadow: 0 6px 20px rgba(0,0,0,0.08);
}

.box i {
    font-size: 28px;
    padding: 15px;
    border-radius: 50%;
    background: rgba(0,0,0,0.08);
}

.box .text h3 {
    margin: 0;
    font-size: 14px;
    opacity: 0.9;
}

.box .text p {
    font-size: 26px;
    font-weight: bold;
    margin: 5px 0 0;
}

table {
    width: 100%;
    border-collapse: collapse;
    border-radius: 10px;
    overflow: hidden;
    background: #fff;
}

thead {
    background: #1f2937;
    color: #fff;
}

th {
    padding: 12px;
    text-align: center;
    font-size: 14px;
    white-space: nowrap;
}

td {
    padding: 12px;
    text-align: center;
}

tbody tr {
    border-bottom: 1px solid #eee;
    transition: 0.2s;
}

tbody tr:hover {
    background: #f1f5f9;
}

tbody tr:nth-child(even) {
    background: #fafafa;
}

.total-row {
    background: #e2e8f0 !important;
    font-weight: bold;
}

.section-title {
    margin: 25px 0 15px;
    font-size: 20px;
    font-weight: 700;
    color: #111827;
}

.empty-box {
    padding: 18px;
    text-align: center;
    background: #f8fafc;
    border: 1px dashed #cbd5e1;
    border-radius: 10px;
    color: #64748b;
}

.panel-name-cell {
    font-weight: bold;
    background: #f9fafb;
    vertical-align: top;
}

@media (max-width: 900px) {
    .container {
        margin-left: 0;
        padding: 15px;
    }
}
</style>
</head>

<body>

<?php include "adminsidebar.php"; ?>
<?php include "../header.php"; ?>

<div class="container">
    <div class="card">
        <h2>
            <i class="fa-solid fa-chart-line"></i>
            Daily Sales
            <small style="font-size:14px;color:#777;">
                (<?php echo date('d M Y', strtotime($selected_date)); ?>)
            </small>
        </h2>

        <form method="GET" class="filter">
            <label>Select Date:</label>
            <input type="date" name="date" value="<?php echo e($selected_date); ?>">
            <button type="submit">Filter</button>
        </form>

        <div class="summary">
            <div class="box">
                <i class="fa-solid fa-file-invoice"></i>
                <div class="text">
                    <h3>Total Bills</h3>
                    <p><?php echo $grand_bills; ?></p>
                </div>
            </div>

            <div class="box">
                <i class="fa-solid fa-indian-rupee-sign"></i>
                <div class="text">
                    <h3>Total Sales</h3>
                    <p>₹<?php echo money($grand_sales); ?></p>
                </div>
            </div>
        </div>



        <table>
            <thead>
                <tr>
                    <th>Panel Name</th>
                    <th>Product Name</th>
                    <th>Total Bill</th>
                    <th>Total Qty</th>
                    <th>Product Sales (₹)</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!empty($grouped)): ?>
                    <?php foreach ($grouped as $panel => $items): 
                        $first = true;
                        $rowspan = count($items);
                        $panel_bills = $panel_bill_map[$panel] ?? 0;
                    ?>
                        <?php foreach ($items as $item): ?>
                            <tr>
                                <?php if ($first): ?>
                                    <td rowspan="<?php echo $rowspan; ?>" class="panel-name-cell">
                                        <?php echo e($panel); ?>
                                    </td>
                                    <?php $first = false; ?>
                                <?php endif; ?>

                                <td><?php echo e($item['product_name']); ?></td>

                                <?php if ($item === reset($items)): ?>
                                    <td rowspan="<?php echo $rowspan; ?>"><?php echo (int)$panel_bills; ?></td>
                                <?php endif; ?>

                                <td><?php echo number_format((float)$item['total_qty'], 2); ?></td>
                                <td>₹<?php echo money($item['total_product_sales']); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="5">
                            <div class="empty-box">No product sales found for selected date.</div>
                        </td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>

    </div>
</div>

</body>
</html>