<?php
require_once 'config.php';

// Redirect if not logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

// Today only
$dateToday = date('Y-m-d');

// =======================
// KPI Calculations
// =======================
function getKPIData($db, $date) {
    // Total Sales Today
    $totalSalesStmt = $db->prepare("
        SELECT IFNULL(SUM(total_amount), 0) as total
        FROM sales
        WHERE DATE(sale_date) = ?
    ");
    $totalSalesStmt->execute([$date]);
    $totalSales = $totalSalesStmt->fetch(PDO::FETCH_ASSOC)['total'];

    // Total Orders Today
    $totalOrdersStmt = $db->prepare("
        SELECT COUNT(*) as count
        FROM sales
        WHERE DATE(sale_date) = ?
    ");
    $totalOrdersStmt->execute([$date]);
    $totalOrders = $totalOrdersStmt->fetch(PDO::FETCH_ASSOC)['count'];

    // Average Order Value
    $avgOrderValue = $totalOrders > 0 ? $totalSales / $totalOrders : 0;

    // Low Stock Items
    $lowStockCount = $db->query("SELECT COUNT(*) as count FROM inventory WHERE stock < 10 AND is_active = 1")->fetch(PDO::FETCH_ASSOC)['count'];

    // Total Inventory Value
    $inventoryValue = $db->query("SELECT IFNULL(SUM(price * stock),0) as total FROM inventory WHERE is_active = 1")->fetch(PDO::FETCH_ASSOC)['total'];

    return [
        'totalSales' => $totalSales,
        'totalOrders' => $totalOrders,
        'avgOrderValue' => $avgOrderValue,
        'lowStockCount' => $lowStockCount,
        'inventoryValue' => $inventoryValue
    ];
}

// =======================
// Sales Analytics
// =======================
function getSalesAnalytics($db, $date) {
    // Daily sales (today only)
    $dailySalesStmt = $db->prepare("
        SELECT i.name, s.quantity, s.total_amount
        FROM sales s
        JOIN inventory i ON s.item_id = i.id
        WHERE DATE(s.sale_date) = ?
        ORDER BY s.total_amount DESC
    ");
    $dailySalesStmt->execute([$date]);
    $dailySales = $dailySalesStmt->fetchAll(PDO::FETCH_ASSOC);

    // Top Selling Items Today
    $topItemsStmt = $db->prepare("
        SELECT i.name, SUM(s.quantity) as total_sold, SUM(s.total_amount) as revenue
        FROM sales s
        JOIN inventory i ON s.item_id = i.id
        WHERE DATE(s.sale_date) = ?
        GROUP BY s.item_id
        ORDER BY total_sold DESC
        LIMIT 10
    ");
    $topItemsStmt->execute([$date]);
    $topItems = $topItemsStmt->fetchAll(PDO::FETCH_ASSOC);

    return [
        'dailySales' => $dailySales,
        'topItems' => $topItems
    ];
}

// =======================
// Inventory Analytics
// =======================
function getInventoryAnalytics($db) {
    // Stock Levels
    $stockAnalysis = $db->query("
        SELECT
            CASE
                WHEN stock = 0 THEN 'Out of Stock'
                WHEN stock < 10 THEN 'Low Stock'
                WHEN stock < 50 THEN 'Medium Stock'
                ELSE 'Well Stocked'
            END as stock_level,
            COUNT(*) as count,
            ROUND(COUNT(*) * 100.0 / (SELECT COUNT(*) FROM inventory WHERE is_active = 1), 2) as percentage
        FROM inventory
        WHERE is_active = 1
        GROUP BY stock_level
        ORDER BY count DESC
    ")->fetchAll(PDO::FETCH_ASSOC);

    // Turnover / Movement
    $turnoverAnalysis = $db->query("
        SELECT
            i.name,
            i.stock,
            i.price,
            COUNT(s.id) as sales_frequency,
            IFNULL(SUM(s.quantity),0) as total_sold,
            IFNULL(SUM(s.total_amount),0) as revenue,
            CASE
                WHEN COUNT(s.id) >= 20 THEN 'Fast Moving'
                WHEN COUNT(s.id) >= 5 THEN 'Moderate Moving'
                WHEN COUNT(s.id) > 0 THEN 'Slow Moving'
                ELSE 'No Sales'
            END as movement_category
        FROM inventory i
        LEFT JOIN sales s ON i.id = s.item_id
        WHERE i.is_active = 1
        GROUP BY i.id
        ORDER BY sales_frequency DESC
    ")->fetchAll(PDO::FETCH_ASSOC);

    return [
        'stockAnalysis' => $stockAnalysis,
        'turnoverAnalysis' => $turnoverAnalysis
    ];
}

// =======================
// Fetch Data
// =======================
$kpiData = getKPIData($db, $dateToday);
$salesAnalytics = getSalesAnalytics($db, $dateToday);
$inventoryAnalytics = getInventoryAnalytics($db);
?>

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Today Sales & Inventory Report</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
body { background: #f8fafc; }
.main-content { padding: 20px; }
.card { border-radius: 15px; box-shadow: 0 4px 15px rgba(0,0,0,0.08); margin-bottom:20px; }
.kpi-card { color:white; border:none; }
.kpi-card.success { background:linear-gradient(135deg,#56ab2f,#a8e6cf);}
.kpi-card.warning { background:linear-gradient(135deg,#f093fb,#f5576c);}
.kpi-card.info { background:linear-gradient(135deg,#4facfe,#00f2fe);}
.growth-positive { color:#28a745; font-weight:bold; }
.growth-negative { color:#dc3545; font-weight:bold; }
.chart-container { position:relative; height:300px; margin:20px 0;}
</style>
</head>
<body>
<div class="container-fluid main-content">
<h2><i class="bi bi-bar-chart-line"></i> Today Sales & Inventory Report (<?= date('F d, Y') ?>)</h2>

<!-- KPI Cards -->
<div class="row g-4 my-4">
    <div class="col-md-3">
        <div class="card kpi-card success text-center p-3">
            <i class="bi bi-currency-dollar fs-1 mb-2"></i>
            <h6>Total Sales</h6>
            <h4>₱<?= number_format($kpiData['totalSales'],2) ?></h4>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card kpi-card info text-center p-3">
            <i class="bi bi-cart-check fs-1 mb-2"></i>
            <h6>Total Orders</h6>
            <h4><?= $kpiData['totalOrders'] ?></h4>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card kpi-card info text-center p-3">
            <i class="bi bi-calculator fs-1 mb-2"></i>
            <h6>Avg Order Value</h6>
            <h4>₱<?= number_format($kpiData['avgOrderValue'],2) ?></h4>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card kpi-card <?= $kpiData['lowStockCount']>0?'warning':'success' ?> text-center p-3">
            <i class="bi bi-exclamation-triangle fs-1 mb-2"></i>
            <h6>Low Stock Items</h6>
            <h4><?= $kpiData['lowStockCount'] ?></h4>
        </div>
    </div>
</div>

<!-- Top Selling Items -->
<div class="card">
<div class="card-header bg-success text-white"><i class="bi bi-trophy"></i> Top Selling Items Today</div>
<div class="card-body">
<?php if(!empty($salesAnalytics['topItems'])): ?>
<?php foreach($salesAnalytics['topItems'] as $index => $item): ?>
<div class="d-flex justify-content-between align-items-center mb-2 p-2 bg-light rounded">
    <div><strong><?= htmlspecialchars($item['name']) ?></strong><br><small>₱<?= number_format($item['revenue'],2) ?> revenue</small></div>
    <span class="badge bg-success"><?= $item['total_sold'] ?> sold</span>
</div>
<?php endforeach; ?>
<?php else: ?>
<p>No sales today.</p>
<?php endif; ?>
</div>
</div>

<!-- Inventory Table -->
<div class="card">
<div class="card-header bg-dark text-white"><i class="bi bi-table"></i> Inventory Overview</div>
<div class="card-body p-0">
<div class="table-responsive">
<table class="table table-hover mb-0">
<thead class="table-dark">
<tr>
<th>Name</th><th class="text-center">Stock</th><th class="text-center">Price</th>
<th class="text-center">Sales Frequency</th><th class="text-center">Total Sold</th>
<th class="text-center">Revenue</th><th class="text-center">Category</th>
</tr>
</thead>
<tbody>
<?php foreach($inventoryAnalytics['turnoverAnalysis'] as $item): ?>
<tr>
<td><?= htmlspecialchars($item['name']) ?></td>
<td class="text-center"><span class="badge <?= $item['stock']<10?'bg-danger':($item['stock']<50?'bg-warning':'bg-success') ?>"><?= $item['stock'] ?></span></td>
<td class="text-center">₱<?= number_format($item['price'],2) ?></td>
<td class="text-center"><?= $item['sales_frequency'] ?></td>
<td class="text-center"><?= $item['total_sold'] ?></td>
<td class="text-center">₱<?= number_format($item['revenue'],2) ?></td>
<td class="text-center"><span class="badge <?= $item['movement_category']=='Fast Moving'?'bg-success':($item['movement_category']=='Moderate Moving'?'bg-warning':($item['movement_category']=='Slow Moving'?'bg-info':'bg-secondary')) ?>"><?= $item['movement_category'] ?></span></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
</div>

</div>
</body>
</html>
