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

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

$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');

if ($selectedMonth == 1) {
    $prevMonth = 12;
    $prevYear = $selectedYear - 1;
} else {
    $prevMonth = $selectedMonth - 1;
    $prevYear = $selectedYear;
}

function getDateRange($year, $month) {
    $start = "$year-$month-01";
    $end = date("Y-m-t", strtotime($start));
    return [$start, $end];
}

$accountantStoreId = $_SESSION['store_id'];
list($startDate, $endDate) = getDateRange($selectedYear, $selectedMonth);
list($prevStartDate, $prevEndDate) = getDateRange($prevYear, $prevMonth);

$storeLabels = $salesData = $expensesData = $profitData = [];
$prevSalesData = $prevExpensesData = $prevProfitData = [];

if ($accountantStoreId > 0) {
    $storeQuery = $conn->prepare("SELECT id, store_name FROM stores WHERE id = ?");
    $storeQuery->bind_param("i", $accountantStoreId);
    $storeQuery->execute();
    $storesRes = $storeQuery->get_result();
} else {
    $storesRes = $conn->query("SELECT id, store_name FROM stores ORDER BY store_name");
}

while ($store = $storesRes->fetch_assoc()) {
    $storeLabels[] = $store['store_name'];

   $stmt = $conn->prepare("
    SELECT 
        COALESCE(SUM(total_amount), 0),
        (SELECT COALESCE(SUM(amount), 0) FROM expenses WHERE store_id = ? AND expense_date BETWEEN ? AND ? AND status = 'approved')
    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;

    $stmt = $conn->prepare("
        SELECT 
            COALESCE(SUM(total_amount), 0),
            (SELECT COALESCE(SUM(amount), 0) FROM expenses WHERE store_id = ? AND expense_date BETWEEN ? AND ?)
        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($prevSales, $prevExpenses);
    $stmt->fetch();
    $stmt->close();

    $prevSalesData[] = (float)$prevSales;
    $prevExpensesData[] = (float)$prevExpenses;
    $prevProfitData[] = (float)$prevSales - (float)$prevExpenses;
}

$totalSales = array_sum($salesData);
$totalExpenses = array_sum($expensesData);
$totalProfit = array_sum($profitData);

function getMonthName($num) {
    return date('F', mktime(0,0,0,$num,1));
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Accountant 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 {
            margin: 0;
            background: #f5f7fa url('../../images/profile.jpg') no-repeat center center fixed;
            background-size: cover;
            font-family: 'Segoe UI', sans-serif;
            color: #eee;
        }

        .content {
            margin-left: 220px;
            padding: 30px 8px 100px;
            margin-top: 70px;
        }

        h2 {
            font-size: 24px;
            font-weight: 700;
            color: #ffa500;
            margin-bottom: 20px;
            text-transform: uppercase;
            letter-spacing: 0.04em;
            text-align: center;
        }

        .filter-form {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
            align-items: center;
            justify-content: center;
            background: rgba(30,30,30,0.85);
            padding: 15px 20px;
            border-radius: 10px;
            backdrop-filter: blur(6px);
            box-shadow: 0 0 10px rgba(255,165,0,0.4);
            margin-bottom: 30px;
        }

        .filter-form label {
            font-weight: 600;
            color: #eee;
        }

        .filter-form select,
        .filter-form button {
            padding: 10px 14px;
            border-radius: 6px;
            font-size: 14px;
            border: none;
            font-weight: 600;
            background: #fff;
            color: #333;
            min-width: 150px;
            transition: box-shadow 0.3s ease;
        }

        .filter-form button {
            background-color: #ffa500;
            color: #222;
            font-weight: bold;
            cursor: pointer;
        }

        .filter-form button:hover,
        .filter-form select:focus {
            box-shadow: 0 0 10px #ffa500;
            outline: none;
        }

        .summary,
        .comparison-cards,
        .charts {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 25px;
        }

        .summary-card,
        .comparison-card,
        .chart-card {
            flex: 1;
            min-width: 260px;
            background: rgba(255, 166, 0, 0.15);
            border: 1px solid rgba(255, 255, 255, 0.1);
            padding: 16px 10px;
            border-radius: 12px;
            backdrop-filter: blur(6px);
            box-shadow: 0 4px 14px rgba(255, 165, 0, 0.25);
            text-align: center;
        }

        .summary-card h3,
        .comparison-card h4,
        .chart-card h3 {
            margin-bottom: 8px;
            font-size: 18px;
            color: #ffa500;
            text-shadow: 0 0 2px #000;
        }

        .summary-card p,
        .comparison-card p {
            font-size: 22px;
            font-weight: bold;
            color: #fff;
            text-shadow: 0 0 2px #000;
        }

        .chart-card canvas {
            width: 100% !important;
            height: 320px !important;
            background: #1f1e1e;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(255,165,0,0.2);
        }

        @media (max-width: 768px) {
            .content {
                margin-left: 0;
                padding: 20px 15px 90px;
            }

            .summary-card,
            .comparison-card,
            .chart-card {
                min-width: 100%;
            }
        }

        @media print {
            .filter-form, .comparison-cards, .chart-card {
                display: none !important;
            }
        }
    </style>
</head>
<body>
<div class="content">
    <h2>📊 Accountant Dashboard - Financial Overview</h2>

    <form method="GET" class="filter-form" id="filterForm" autocomplete="off" aria-label="Filter accountant dashboard data">
        <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" aria-label="Apply filters">Apply Filters</button>
    </form>

    <div class="summary" role="region" aria-label="Summary financial data">
        <div class="summary-card" tabindex="0">
            <h3>Total Sales (<?= getMonthName($selectedMonth) . " $selectedYear" ?>)</h3>
            <p>MWK <?= number_format($totalSales, 2) ?></p>
        </div>
        <div class="summary-card" tabindex="0">
            <h3>Total Expenses (<?= getMonthName($selectedMonth) . " $selectedYear" ?>)</h3>
            <p>MWK <?= number_format($totalExpenses, 2) ?></p>
        </div>
        <div class="summary-card" tabindex="0">
            <h3>Total Profit (<?= getMonthName($selectedMonth) . " $selectedYear" ?>)</h3>
            <p>MWK <?= number_format($totalProfit, 2) ?></p>
        </div>
    </div>

    <div class="comparison-cards" role="region" aria-label="Sales comparison between current and previous month">
        <div class="comparison-card" tabindex="0">
            <h4>Current Month (<?= getMonthName($selectedMonth) . " $selectedYear" ?>) Sales</h4>
            <p>MWK <?= number_format($totalSales, 2) ?></p>
        </div>
        <div class="comparison-card" tabindex="0">
            <h4>Previous Month (<?= getMonthName($prevMonth) . " $prevYear" ?>) Sales</h4>
            <p>MWK <?= number_format(array_sum($prevSalesData), 2) ?></p>
        </div>
    </div>

    <div class="charts" role="region" aria-label="Financial charts per store">
        <div class="chart-card" tabindex="0">
            <h3>Sales per Store</h3>
            <canvas id="salesChart" role="img" aria-label="Bar chart showing sales per store"></canvas>
        </div>
        <div class="chart-card" tabindex="0">
            <h3>Expenses per Store</h3>
            <canvas id="expensesChart" role="img" aria-label="Line chart showing expenses per store"></canvas>
        </div>
        <div class="chart-card" tabindex="0">
            <h3>Profit per Store</h3>
            <canvas id="profitChart" role="img" aria-label="Pie chart showing profit share per store"></canvas>
        </div>
        <div class="chart-card" tabindex="0" style="flex-basis: 100%;">
            <h3>Sales Comparison: Current vs Previous Month</h3>
            <canvas id="comparisonChart" role="img" aria-label="Bar chart comparing current and previous month sales"></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 chartCommonOptions = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
        legend: {
            labels: {
                color: '#eee',
                font: { weight: '600' }
            }
        },
        tooltip: {
            backgroundColor: 'rgba(0,0,0,0.8)',
            titleColor: '#ffa500',
            bodyColor: '#eee',
            callbacks: {
                label: ctx => `${ctx.dataset.label}: MWK ${ctx.parsed.y?.toLocaleString(undefined, {minimumFractionDigits: 2}) ?? ctx.parsed} `
            }
        }
    },
    scales: {
        x: {
            ticks: {
                color: '#ffa500',
                font: { weight: '600' },
                maxRotation: 45,
                minRotation: 45,
            },
            grid: {
                color: 'rgba(255,165,0,0.15)'
            }
        },
        y: {
            beginAtZero: true,
            ticks: {
                color: '#eee',
                font: { weight: '600' },
                callback: value => 'MWK ' + value.toLocaleString()
            },
            grid: {
                color: 'rgba(255,165,0,0.15)'
            }
        }
    }
};

new Chart(document.getElementById('salesChart'), {
    type: 'bar',
    data: {
        labels: storeLabels,
        datasets: [{
            label: 'Sales',
            data: salesData,
            backgroundColor: '#0055a2'
        }]
    },
    options: chartCommonOptions
});

new Chart(document.getElementById('expensesChart'), {
    type: 'line',
    data: {
        labels: storeLabels,
        datasets: [{
            label: 'Expenses',
            data: expensesData,
            borderColor: '#dc3545',
            backgroundColor: 'rgba(220, 53, 69, 0.2)',
            fill: true,
            tension: 0.3,
            pointRadius: 5,
            pointHoverRadius: 7,
            pointBackgroundColor: '#dc3545'
        }]
    },
    options: chartCommonOptions
});

new Chart(document.getElementById('profitChart'), {
    type: 'pie',
    data: {
        labels: storeLabels,
        datasets: [{
            label: 'Profit Share',
            data: profitData,
            backgroundColor: [
                '#198754',
                '#0d6efd',
                '#ffc107',
                '#6f42c1',
                '#fd7e14',
                '#20c997',
                '#6610f2',
                '#e83e8c'
            ]
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                position: 'right',
                labels: {
                    color: '#eee',
                    font: { weight: '600' }
                }
            },
            tooltip: {
                backgroundColor: 'rgba(0,0,0,0.8)',
                titleColor: '#ffa500',
                bodyColor: '#eee',
                callbacks: {
                    label: ctx => `${ctx.label}: MWK ${ctx.parsed.toLocaleString(undefined, {minimumFractionDigits: 2})}`
                }
            }
        }
    }
});

new Chart(document.getElementById('comparisonChart'), {
    type: 'bar',
    data: {
        labels: storeLabels,
        datasets: [
            {
                label: 'Current Month',
                data: salesData,
                backgroundColor: '#0055a2'
            },
            {
                label: 'Previous Month',
                data: prevSalesData,
                backgroundColor: '#6c757d'
            }
        ]
    },
    options: chartCommonOptions
});
</script>
</body>
</html>
