<?php
session_start();
if (!isset($_SESSION['role_id']) || $_SESSION['role_id'] != 1) {
    header("Location: ../../index.php");
    exit();
}

include('../../includes/config.php');
include('../../includes/header.php');
include('../../includes/sidebar.php');
include('../../includes/footer.php');

// Get selected filter month/year or default to current month/year
$selectedYear = isset($_GET['year']) && is_numeric($_GET['year']) ? (int)$_GET['year'] : (int)date('Y');
$selectedMonth = isset($_GET['month']) && is_numeric($_GET['month']) ? (int)$_GET['month'] : (int)date('n');

// Calculate previous month/year for comparison
if ($selectedMonth == 1) {
    $prevMonth = 12;
    $prevYear = $selectedYear - 1;
} else {
    $prevMonth = $selectedMonth - 1;
    $prevYear = $selectedYear;
}

// Helper function for filtering by month and year
function getDateRange($year, $month) {
    $start = "$year-$month-01";
    $end = date("Y-m-t", strtotime($start)); // last day of the month
    return [$start, $end];
}

// Fetch total sales, expenses, profit per store for selected month
list($startDate, $endDate) = getDateRange($selectedYear, $selectedMonth);
list($prevStartDate, $prevEndDate) = getDateRange($prevYear, $prevMonth);

$storeLabels = [];
$salesData = [];
$expensesData = [];
$profitData = [];

$prevSalesData = [];
$prevExpensesData = [];
$prevProfitData = [];

// Fetch stores
$storesRes = $conn->query("SELECT id, store_name FROM stores ORDER BY store_name");
while ($store = $storesRes->fetch_assoc()) {
    $storeLabels[] = $store['store_name'];

    // Current month sales
    $stmt = $conn->prepare("
        SELECT 
            COALESCE(SUM(total_amount), 0) AS total_sales,
            (SELECT COALESCE(SUM(amount), 0) FROM expenses WHERE store_id = ? AND expense_date BETWEEN ? AND ?) AS total_expenses
        FROM sales_transactions
        WHERE store_id = ? AND created_at BETWEEN ? AND ?
    ");
    $stmt->bind_param("ississ", $store['id'], $startDate, $endDate, $store['id'], $startDate, $endDate);
    $stmt->execute();
    $stmt->bind_result($totalSales, $totalExpenses);
    $stmt->fetch();
    $stmt->close();

    $salesData[] = (float)$totalSales;
    $expensesData[] = (float)$totalExpenses;
    $profitData[] = (float)$totalSales - (float)$totalExpenses;

    // Previous month sales
    $stmt = $conn->prepare("
        SELECT 
            COALESCE(SUM(total_amount), 0) AS total_sales,
            (SELECT COALESCE(SUM(amount), 0) FROM expenses WHERE store_id = ? AND expense_date BETWEEN ? AND ?) AS total_expenses
        FROM sales_transactions
        WHERE store_id = ? AND created_at BETWEEN ? AND ?
    ");
    $stmt->bind_param("ississ", $store['id'], $prevStartDate, $prevEndDate, $store['id'], $prevStartDate, $prevEndDate);
    $stmt->execute();
    $stmt->bind_result($prevTotalSales, $prevTotalExpenses);
    $stmt->fetch();
    $stmt->close();

    $prevSalesData[] = (float)$prevTotalSales;
    $prevExpensesData[] = (float)$prevTotalExpenses;
    $prevProfitData[] = (float)$prevTotalSales - (float)$prevTotalExpenses;
}

// Totals for summary cards
$totalSales = array_sum($salesData);
$totalExpenses = array_sum($expensesData);
$totalProfit = array_sum($profitData);

// Month names for dropdowns
function getMonthName($num) {
    return date('F', mktime(0,0,0,$num,1));
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Admin Dashboard - Digital POS</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body {
            background: url('../../images/profile.jpg') no-repeat center center fixed;
            background-size: cover;
            font-family: 'Segoe UI', sans-serif;
            margin: 0;
            color: white;
        }
        .overlay {
            position: fixed;
            top: 0; left: 0;
            width: 100%; height: 100%;
            background: rgba(0,0,0,0.6);
            z-index: -1;
        }
        .content {
            margin-left: 220px;
            padding: 30px;
            margin-top: 80px;
        }
        .summary {
            display: flex;
            gap: 20px;
            flex-wrap: wrap;
            margin-bottom: 30px;
        }
        .summary-card {
            flex: 1;
            min-width: 240px;
            background: rgba(255,255,255,0.12);
            padding: 20px;
            border-radius: 12px;
            text-align: center;
            box-shadow: 0 8px 20px rgba(0,0,0,0.3);
            backdrop-filter: blur(10px);
        }
        .summary-card h3 {
            margin: 10px 0;
            color: #ffa500;
            font-size: 18px;
        }
        .summary-card p {
            font-size: 22px;
            font-weight: bold;
        }
        .charts {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
        }
        .chart-card {
            flex: 1;
            min-width: 320px;
            background: rgba(255,255,255,0.12);
            border-radius: 12px;
            padding: 20px;
            backdrop-filter: blur(10px);
            overflow-x: auto;
            display: flex;
            flex-direction: column;
        }
        canvas {
            width: 100% !important;
            max-width: 100%;
            height: 350px !important;
            background: white;
            border-radius: 10px;
        }
        @media (max-width: 768px) {
            .content {
                margin-left: 0;
            }
            .charts {
                flex-direction: column;
            }
        }
        /* Filter Form */
        .filter-form {
            margin-bottom: 25px;
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
            align-items: center;
        }
        .filter-form label {
            color: white;
            font-weight: 600;
        }
        .filter-form select {
            padding: 5px 10px;
            border-radius: 6px;
            border: none;
            font-size: 14px;
        }
        .filter-form button {
            background: #ffa500;
            color: #222;
            border: none;
            border-radius: 6px;
            padding: 7px 15px;
            cursor: pointer;
            font-weight: 700;
            transition: background-color 0.3s ease;
        }
        .filter-form button:hover {
            background: #e59400;
        }
        /* Comparison cards */
        .comparison-cards {
            display: flex;
            gap: 20px;
            flex-wrap: wrap;
            margin-bottom: 25px;
        }
        .comparison-card {
            flex: 1;
            min-width: 240px;
            background: rgba(255,255,255,0.15);
            padding: 18px 22px;
            border-radius: 12px;
            text-align: center;
            box-shadow: 0 5px 15px rgba(0,0,0,0.25);
            backdrop-filter: blur(12px);
            color: #fff;
        }
        .comparison-card h4 {
            margin-bottom: 8px;
            color: #ffb84d;
            font-size: 18px;
        }
        .comparison-card p {
            font-size: 20px;
            font-weight: bold;
        }
    </style>
</head>
<body>
<div class="overlay"></div>
<div class="content">
    <h2>📊 Admin Dashboard - System Overview</h2>

    <!-- Filters -->
    <form method="GET" class="filter-form" id="filterForm">
        <label for="month">Month:</label>
        <select name="month" id="month" onchange="document.getElementById('filterForm').submit()">
            <?php
            for ($m=1; $m<=12; $m++) {
                $selected = ($m === $selectedMonth) ? 'selected' : '';
                echo "<option value='$m' $selected>" . getMonthName($m) . "</option>";
            }
            ?>
        </select>

        <label for="year">Year:</label>
        <select name="year" id="year" onchange="document.getElementById('filterForm').submit()">
            <?php
            $currentYear = (int)date('Y');
            for ($y=$currentYear; $y >= 2020; $y--) {
                $selected = ($y === $selectedYear) ? 'selected' : '';
                echo "<option value='$y' $selected>$y</option>";
            }
            ?>
        </select>
        <button type="submit">Apply Filters</button>
    </form>

    <!-- Summary Cards -->
    <div class="summary">
        <div class="summary-card">
            <h3>Total Sales (<?= getMonthName($selectedMonth) . " $selectedYear" ?>)</h3>
            <p>MWK <?= number_format($totalSales, 2) ?></p>
        </div>
        <div class="summary-card">
            <h3>Total Expenses (<?= getMonthName($selectedMonth) . " $selectedYear" ?>)</h3>
            <p>MWK <?= number_format($totalExpenses, 2) ?></p>
        </div>
        <div class="summary-card">
            <h3>Total Profit (<?= getMonthName($selectedMonth) . " $selectedYear" ?>)</h3>
            <p>MWK <?= number_format($totalProfit, 2) ?></p>
        </div>
    </div>

    <!-- Comparison Cards -->
    <div class="comparison-cards">
        <div class="comparison-card">
            <h4>Current Month (<?= getMonthName($selectedMonth) . " $selectedYear" ?>) Sales</h4>
            <p>MWK <?= number_format($totalSales, 2) ?></p>
        </div>
        <div class="comparison-card">
            <h4>Previous Month (<?= getMonthName($prevMonth) . " $prevYear" ?>) Sales</h4>
            <p>MWK <?= number_format(array_sum($prevSalesData), 2) ?></p>
        </div>
    </div>

    <div class="charts">
        <div class="chart-card">
            <h3>Sales per Store</h3>
            <canvas id="salesChart"></canvas>
        </div>
        <div class="chart-card">
            <h3>Expenses per Store</h3>
            <canvas id="expensesChart"></canvas>
        </div>
        <div class="chart-card">
            <h3>Profit per Store</h3>
            <canvas id="profitChart"></canvas>
        </div>
        <div class="chart-card" style="flex-basis: 100%;">
            <h3>Sales Comparison: Current vs Previous Month</h3>
            <canvas id="comparisonChart"></canvas>
        </div>
    </div>
</div>

<script>
const storeLabels = <?= json_encode($storeLabels); ?>;
const salesData = <?= json_encode($salesData); ?>;
const expensesData = <?= json_encode($expensesData); ?>;
const profitData = <?= json_encode($profitData); ?>;

const prevSalesData = <?= json_encode($prevSalesData); ?>;
const prevExpensesData = <?= json_encode($prevExpensesData); ?>;
const prevProfitData = <?= json_encode($prevProfitData); ?>;

const salesCtx = document.getElementById('salesChart').getContext('2d');
const expensesCtx = document.getElementById('expensesChart').getContext('2d');
const profitCtx = document.getElementById('profitChart').getContext('2d');
const comparisonCtx = document.getElementById('comparisonChart').getContext('2d');

const salesChart = new Chart(salesCtx, {
    type: 'bar',
    data: {
        labels: storeLabels,
        datasets: [{
            label: 'Sales (MWK)',
            data: salesData,
            backgroundColor: '#ffa500'
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,

        
        scales: {
          y: {
            beginAtZero: true
          }
        },
        plugins: {
          legend: { position: 'top' },
          title: {
            display: false,
          }
        }
    }
});

const expensesChart = new Chart(expensesCtx, {
    type: 'line',
    data: {
        labels: storeLabels,
        datasets: [{
            label: 'Expenses (MWK)',
            data: expensesData,
            borderColor: '#00bfff',
            backgroundColor: 'rgba(0,191,255,0.2)',
            fill: true,
            tension: 0.4
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
          y: { beginAtZero: true }
        }
    }
});

const profitChart = new Chart(profitCtx, {
    type: 'pie',
    data: {
        labels: storeLabels,
        datasets: [{
            label: 'Profit Share',
            data: profitData,
            backgroundColor: [
                '#28a745',
                '#007bff',
                '#ffc107',
                '#ff6384',
                '#17a2b8',
                '#6f42c1',
                '#fd7e14',
                '#20c997',
                '#6610f2',
                '#e83e8c'
            ]
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: { position: 'bottom' },
            tooltip: {
                callbacks: {
                    label: function(ctx) {
                        const total = ctx.dataset.data.reduce((a, b) => a + b, 0);
                        const value = ctx.raw;
                        const pct = ((value / total) * 100).toFixed(1);
                        return `${ctx.label}: MWK ${value.toLocaleString()} (${pct}%)`;
                    }
                }
            }
        }
    }
});

// Comparison Chart: Current vs Previous Month Sales per store
const comparisonChart = new Chart(comparisonCtx, {
    type: 'bar',
    data: {
        labels: storeLabels,
        datasets: [
            {
                label: 'Current Month Sales',
                data: salesData,
                backgroundColor: 'rgba(255, 123, 0, 0.7)'
            },
            {
                label: 'Previous Month Sales',
                data: prevSalesData,
                backgroundColor: 'rgba(54, 162, 235, 0.7)'
            }
        ]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
            y: { beginAtZero: true }
        },
        plugins: {
            legend: { position: 'top' }
        }
    }
});
</script>
</body>
</html>
