<?php
include 'auth_check.php';

requireAdminAccess('credit_sale.php');

$today = date('Y-m-d');
$currentMonth = date('Y-m');
$currentWeekStart = date('Y-m-d', strtotime('monday this week'));
$currentWeekEnd = date('Y-m-d', strtotime('sunday this week'));

$dailyIncomeProfitQuery = $conn->query("
    SELECT 
        IFNULL(SUM(sell_amount), 0) AS total_sale,
        IFNULL(SUM(purchaing_amount), 0) AS total_income,
        IFNULL(SUM(profit), 0) AS total_profit
    FROM income_profit_data
    WHERE entered_date = '$today'
");
$dailyIncomeProfitData = $dailyIncomeProfitQuery->fetch_assoc();

$dailySale = $dailyIncomeProfitData['total_sale'];
$dailyIncome = $dailyIncomeProfitData['total_income'];
$dailyProfit = $dailyIncomeProfitData['total_profit'];

$dailyCreditPurchaseQuery = $conn->query("
    SELECT
        IFNULL(SUM(total_amount), 0) AS daily_purchases,
        IFNULL(SUM(pending_amount), 0) AS daily_purchases_credit
    FROM credit_purchaing_update
    WHERE entered_date = '$today'
");
$dailyCreditPurchaseData = $dailyCreditPurchaseQuery->fetch_assoc();

$dailyPurchases = $dailyCreditPurchaseData['daily_purchases'];
$dailyPurchasesCredit = $dailyCreditPurchaseData['daily_purchases_credit'];

$monthlyIncomeProfitQuery = $conn->query("
    SELECT 
        IFNULL(SUM(sell_amount), 0) AS total_sale,
        IFNULL(SUM(purchaing_amount), 0) AS total_income,
        IFNULL(SUM(profit), 0) AS total_profit
    FROM income_profit_data
    WHERE DATE_FORMAT(entered_date, '%Y-%m') = '$currentMonth'
");
$monthlyIncomeProfitData = $monthlyIncomeProfitQuery->fetch_assoc();

$monthlySale = $monthlyIncomeProfitData['total_sale'];
$monthlyIncome = $monthlyIncomeProfitData['total_income'];
$monthlyProfit = $monthlyIncomeProfitData['total_profit'];

$monthlyCreditPurchaseQuery = $conn->query("
    SELECT
        IFNULL(SUM(total_amount), 0) AS monthly_purchases,
        IFNULL(SUM(pending_amount), 0) AS monthly_purchases_credit
    FROM credit_purchaing_update
    WHERE DATE_FORMAT(entered_date, '%Y-%m') = '$currentMonth'
");
$monthlyCreditPurchaseData = $monthlyCreditPurchaseQuery->fetch_assoc();

$monthlyPurchases = $monthlyCreditPurchaseData['monthly_purchases'];
$monthlyPurchasesCredit = $monthlyCreditPurchaseData['monthly_purchases_credit'];

/* Weekly profit line chart data from income_profit_data table */
$weeklyProfitLabels = [];
$weeklyProfitValues = [];

$weeklyDays = [];
$startTimestamp = strtotime($currentWeekStart);

for ($i = 0; $i < 7; $i++) {
    $dateValue = date('Y-m-d', strtotime("+$i day", $startTimestamp));
    $weeklyDays[$dateValue] = 0;
}

$weeklyProfitQuery = $conn->query("
    SELECT entered_date, IFNULL(SUM(profit), 0) AS total_profit
    FROM income_profit_data
    WHERE entered_date BETWEEN '$currentWeekStart' AND '$currentWeekEnd'
    GROUP BY entered_date
    ORDER BY entered_date ASC
");

while ($row = $weeklyProfitQuery->fetch_assoc()) {
    $weeklyDays[$row['entered_date']] = (float)$row['total_profit'];
}

foreach ($weeklyDays as $dateKey => $profitValue) {
    $weeklyProfitLabels[] = date('D', strtotime($dateKey));
    $weeklyProfitValues[] = $profitValue;
}

/* Pie chart data from billing_data table - monthly product sale count */
$monthlySalePieLabels = [];
$monthlySalePieValues = [];

$monthlySalePieQuery = $conn->query("
    SELECT product_name, IFNULL(SUM(qty), 0) AS total_qty
    FROM billing_data
    WHERE DATE_FORMAT(entered_date, '%Y-%m') = '$currentMonth'
    GROUP BY product_name
    ORDER BY total_qty DESC, product_name ASC
");

while ($row = $monthlySalePieQuery->fetch_assoc()) {
    $monthlySalePieLabels[] = $row['product_name'];
    $monthlySalePieValues[] = (float)$row['total_qty'];
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Krushi Sewa Piyasa-Dashboard</title>
    <link rel="stylesheet" href="assets/style.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<div class="layout">
    <?php renderSidebar('dashboard'); ?>
    <main class="main-content">
        <div class="topbar">Logged User: <?php echo $_SESSION['name']; ?> | <?php echo $_SESSION['user_category']; ?></div>

        <div class="stats-main-card">
            <div class="stats-main-title">Daily Stats</div>
            <div class="stats-mini-grid">
                <div class="stats-mini-card">
                    <h3>Daily Sale</h3>
                    <p>Rs. <?php echo number_format((float)$dailySale, 2); ?></p>
                </div>
                <div class="stats-mini-card">
                    <h3>Daily Income</h3>
                    <p>Rs. <?php echo number_format((float)$dailyIncome, 2); ?></p>
                </div>
                <div class="stats-mini-card">
                    <h3>Daily Profit</h3>
                    <p>Rs. <?php echo number_format((float)$dailyProfit, 2); ?></p>
                </div>
                <div class="stats-mini-card">
                    <h3>Daily Purchases</h3>
                    <p>Rs. <?php echo number_format((float)$dailyPurchases, 2); ?></p>
                </div>
                <div class="stats-mini-card">
                    <h3>Daily Purchases Credit</h3>
                    <p>Rs. <?php echo number_format((float)$dailyPurchasesCredit, 2); ?></p>
                </div>
            </div>
        </div>

        <div class="stats-main-card monthly-stats-card">
            <div class="stats-main-title">Monthly Stats</div>
            <div class="stats-mini-grid">
                <div class="stats-mini-card monthly-mini-card">
                    <h3>Monthly Sale</h3>
                    <p>Rs. <?php echo number_format((float)$monthlySale, 2); ?></p>
                </div>
                <div class="stats-mini-card monthly-mini-card">
                    <h3>Monthly Income</h3>
                    <p>Rs. <?php echo number_format((float)$monthlyIncome, 2); ?></p>
                </div>
                <div class="stats-mini-card monthly-mini-card">
                    <h3>Monthly Profit</h3>
                    <p>Rs. <?php echo number_format((float)$monthlyProfit, 2); ?></p>
                </div>
                <div class="stats-mini-card monthly-mini-card">
                    <h3>Monthly Purchases</h3>
                    <p>Rs. <?php echo number_format((float)$monthlyPurchases, 2); ?></p>
                </div>
                <div class="stats-mini-card monthly-mini-card">
                    <h3>Monthly Purchases Credit</h3>
                    <p>Rs. <?php echo number_format((float)$monthlyPurchasesCredit, 2); ?></p>
                </div>
            </div>
        </div>

        <div class="dashboard-two-quadrant">
            <div class="dashboard-chart-card">
                <h3>Weekly Profit</h3>
                <div class="chart-box">
                    <canvas id="weeklyProfitLineChart"></canvas>
                </div>
            </div>

            <div class="dashboard-chart-card">
                <h3>Monthly Product Sale Count</h3>
                <div class="chart-box pie-chart-box">
                    <canvas id="expiryPieChart"></canvas>
                </div>
            </div>
        </div>
    </main>
</div>

<script>
const weeklyProfitLabels = <?php echo json_encode($weeklyProfitLabels); ?>;
const weeklyProfitValues = <?php echo json_encode($weeklyProfitValues); ?>;

const monthlySalePieLabels = <?php echo json_encode($monthlySalePieLabels); ?>;
const monthlySalePieValues = <?php echo json_encode($monthlySalePieValues); ?>;

const pieColors = [
    '#f4b400', '#ff7043', '#42a5f5', '#66bb6a', '#ab47bc',
    '#26a69a', '#ec407a', '#ffa726', '#5c6bc0', '#8d6e63',
    '#8bc34a', '#ff9800', '#03a9f4', '#e91e63', '#795548'
];

const weeklyProfitLineChartCtx = document.getElementById('weeklyProfitLineChart');
if (weeklyProfitLineChartCtx) {
    new Chart(weeklyProfitLineChartCtx, {
        type: 'line',
        data: {
            labels: weeklyProfitLabels,
            datasets: [{
                label: 'Profit',
                data: weeklyProfitValues,
                borderColor: '#1f7a3f',
                backgroundColor: 'rgba(31, 122, 63, 0.12)',
                fill: true,
                tension: 0.35,
                pointBackgroundColor: '#1f7a3f',
                pointBorderColor: '#1f7a3f',
                pointRadius: 4,
                pointHoverRadius: 5,
                borderWidth: 3
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            animation: false,
            plugins: {
                legend: {
                    display: true
                }
            },
            scales: {
                x: {
                    ticks: {
                        font: { size: 11 }
                    },
                    grid: { display: false }
                },
                y: {
                    beginAtZero: true,
                    ticks: {
                        font: { size: 11 },
                        callback: function(value) {
                            return 'Rs. ' + value;
                        }
                    }
                }
            }
        }
    });
}

const expiryPieChartCtx = document.getElementById('expiryPieChart');
if (expiryPieChartCtx) {
    new Chart(expiryPieChartCtx, {
        type: 'pie',
        data: {
            labels: monthlySalePieLabels.length ? monthlySalePieLabels : ['No Monthly Sales'],
            datasets: [{
                data: monthlySalePieValues.length ? monthlySalePieValues : [1],
                backgroundColor: monthlySalePieValues.length
                    ? monthlySalePieLabels.map((_, i) => pieColors[i % pieColors.length])
                    : ['#dfe6e9'],
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            animation: false,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        boxWidth: 12,
                        font: { size: 11 }
                    }
                }
            }
        }
    });
}
</script>
</body>
</html>