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

if (!isset($_SESSION['user'])) {
    header('Location: ../auth/login.php');
    exit;
}

$role = $_SESSION['user']['role'] ?? 'viewer';

require_once __DIR__ . '/../config/db_remote.php';

// Helper for queries
function q_total($sql) {
    global $mysqli;
    $res = $mysqli->query($sql);
    if ($res && $row = $res->fetch_assoc()) {
        return (int)$row['total'];
    }
    return 0;
}

// FULL BINS
$full_bins_inventory = q_total("
    SELECT COALESCE(SUM(quantity),0) AS total
    FROM bins_ingresso
    WHERE status='AVAILABLE'
");

// DUMPED STATS
$dumped_stats = [
    'today' => q_total("SELECT COALESCE(SUM(quantity),0) AS total FROM bins_ingresso WHERE status='DUMPED' AND DATE(updated_at)=CURDATE()"),
    'week'  => q_total("SELECT COALESCE(SUM(quantity),0) AS total FROM bins_ingresso WHERE status='DUMPED' AND YEARWEEK(updated_at,1)=YEARWEEK(CURDATE(),1)"),
    'month' => q_total("SELECT COALESCE(SUM(quantity),0) AS total FROM bins_ingresso WHERE status='DUMPED' AND YEAR(updated_at)=YEAR(CURDATE()) AND MONTH(updated_at)=MONTH(CURDATE())"),
    'total' => q_total("SELECT COALESCE(SUM(quantity),0) AS total FROM bins_ingresso WHERE status='DUMPED'")
];

// BOXES PRODUCED
$boxes_stats = [
    'today' => q_total("SELECT COALESCE(SUM(boxes_produced),0) AS total FROM activity_log WHERE DATE(timestamp)=CURDATE()"),
    'week'  => q_total("SELECT COALESCE(SUM(boxes_produced),0) AS total FROM activity_log WHERE YEARWEEK(timestamp,1)=YEARWEEK(CURDATE(),1)"),
    'month' => q_total("SELECT COALESCE(SUM(boxes_produced),0) AS total FROM activity_log WHERE YEAR(timestamp)=YEAR(CURDATE()) AND MONTH(timestamp)=MONTH(CURDATE())"),
    'total' => q_total("SELECT COALESCE(SUM(boxes_produced),0) AS total FROM activity_log")
];

// CHART DATA TODAY
$boxes_today_by_hour = array_fill(0, 24, 0);
$res = $mysqli->query("
    SELECT HOUR(timestamp) AS h, COALESCE(SUM(boxes_produced),0) AS total
    FROM activity_log
    WHERE DATE(timestamp)=CURDATE()
    GROUP BY HOUR(timestamp)
");
while ($row = $res->fetch_assoc()) {
    $boxes_today_by_hour[(int)$row['h']] = (int)$row['total'];
}

include __DIR__ . '/../includes/header.php';
?>

<h1 class="mt-4 mb-2">📊 Dashboard</h1>
<p class="text-muted mb-4">Overview of full bins, dumped bins and produced boxes.</p>

<div class="row g-4">

    <!-- FULL BINS -->
    <div class="col-md-4">
        <div class="card shadow-sm border-0">
            <div class="card-body">
                <div class="text-muted mb-1">📦 Full Bins in Inventory</div>
                <div class="fs-1 fw-bold"><?php echo $full_bins_inventory; ?></div>
            </div>
        </div>
    </div>

    <!-- DUMPED -->
    <div class="col-md-4">
        <div class="card shadow-sm border-0">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center mb-1">
                    <span class="text-muted">🗑 Dumped Bins</span>
                    <select id="dumpedRange" class="form-select form-select-sm w-auto">
                        <option value="today">Today</option>
                        <option value="week">This Week</option>
                        <option value="month">This Month</option>
                        <option value="total">Total</option>
                    </select>
                </div>
                <div class="fs-1 fw-bold" id="dumpedValue"><?php echo $dumped_stats['today']; ?></div>
                <div class="text-muted small" id="dumpedLabel">Total dumped quantity today</div>
            </div>
        </div>
    </div>

    <!-- BOXES -->
    <div class="col-md-4">
        <div class="card shadow-sm border-0">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center mb-1">
                    <span class="text-muted">📦 Boxes Produced</span>
                    <select id="boxesRange" class="form-select form-select-sm w-auto">
                        <option value="today">Today</option>
                        <option value="week">This Week</option>
                        <option value="month">This Month</option>
                        <option value="total">Total</option>
                    </select>
                </div>
                <div class="fs-1 fw-bold" id="boxesValue"><?php echo $boxes_stats['today']; ?></div>
                <div class="text-muted small" id="boxesLabel">Boxes produced today</div>
            </div>
        </div>
    </div>

</div>

<!-- CHART -->
<div class="card shadow-sm border-0 mt-4 mb-4">
    <div class="card-header bg-white">
        <span class="fw-semibold">📈 Boxes Produced Today (by hour)</span>
    </div>
    <div class="card-body">
        <canvas id="boxesChart" height="120"></canvas>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const dumpedStats = <?php echo json_encode($dumped_stats); ?>;
const boxesStats  = <?php echo json_encode($boxes_stats); ?>;
const boxesByHour = <?php echo json_encode($boxes_today_by_hour); ?>;

// dropdown handlers
document.getElementById('dumpedRange').addEventListener('change', function() {
    const v = this.value;
    document.getElementById('dumpedValue').textContent = dumpedStats[v];
    document.getElementById('dumpedLabel').textContent =
        v === 'today' ? 'Total dumped quantity today' :
        v === 'week'  ? 'Total dumped quantity this week' :
        v === 'month' ? 'Total dumped quantity this month' :
                        'Total dumped quantity (all time)';
});

document.getElementById('boxesRange').addEventListener('change', function() {
    const v = this.value;
    document.getElementById('boxesValue').textContent = boxesStats[v];
    document.getElementById('boxesLabel').textContent =
        v === 'today' ? 'Boxes produced today' :
        v === 'week'  ? 'Boxes produced this week' :
        v === 'month' ? 'Boxes produced this month' :
                        'Boxes produced (all time)';
});

// chart
new Chart(document.getElementById('boxesChart').getContext('2d'), {
    type: 'bar',
    data: {
        labels: [...Array(24).keys()].map(h => (h < 10 ? '0' : '') + h + ':00'),
        datasets: [{
            label: 'Boxes produced',
            data: boxesByHour
        }]
    },
    options: { responsive: true, scales: { y: { beginAtZero: true } } }
});
</script>

<?php include __DIR__ . '/../includes/footer.php'; ?>
