<?php
  
	session_start();
	require_once __DIR__ . '/../../includes/auth.php';
	require_once __DIR__ . '/../../classes/Database.php';
	require_once __DIR__ . '/../../classes/Sales.php';
	require_once __DIR__ . '/../../classes/Branch.php';
	require_once __DIR__ . '/../../classes/Deposit.php';
	require_once __DIR__ . '/../../includes/dashboard_helper.php';
	require_once __DIR__ . '/../../classes/Laybuy.php';
	require_once __DIR__ . '/../../classes/Sales.php';
	require_once __DIR__ . '/../../classes/Expense.php';
	require_once __DIR__ . '/../../classes/Branch.php';
	require_once __DIR__ . '/../../classes/Notifications.php';
	require_once __DIR__ . '/../../classes/SystemSettings.php';

	
	
	
	$database = new Database();
	$conn = $database->getConnection();
	$sales = new Sales($conn);
	$expense = new Expense($conn);
	$laybuy = new Laybuy($conn);
	$systemSettings = new SystemSettings();
	$profitRate = $systemSettings->profitRate();
  
	$startDate = $start_date = $_POST["start_date"] ?? null;
	$endDate = $end_date = $_POST['end_date'] ?? null;
	$selectedBranchId = $branch_id = $_POST['branch_id'] ?? null;
	if ($selectedBranchId === 'all' || $selectedBranchId === '' || $selectedBranchId === null) {
		$selectedBranchId = null;
	} else {
		$selectedBranchId = (int)$selectedBranchId;
	}

  
//	echo "Start Date = ".$start_date." End Date =". $end_date." Branch ID = ".$branch_id;


	

	$salesData = $sales->getSalesForPeriod($startDate, $endDate, $selectedBranchId);


	$totalSales = 0;
	
	if (!empty($salesData)) {
		foreach ($salesData as $sale) {
			$totalSales += $sale['total_price'];
		}
	}

	$totalLaybuy = 0;
	if ($selectedBranchId) {
		$layBuyStats = $laybuy->getBranchLayBuyStats($selectedBranchId, $startDate, $endDate);
		foreach ($layBuyStats as $layBuyPayment) {
			$totalLaybuy += (float)($layBuyPayment['body_amount'] ?? 0);
		}
	} else {
		$branchStmt = $conn->prepare("SELECT branch_id FROM branches WHERE branch_id != 7");
		$branchStmt->execute();
		$branchIds = $branchStmt->fetchAll(PDO::FETCH_COLUMN);

		foreach ($branchIds as $branchId) {
			$layBuyStats = $laybuy->getBranchLayBuyStats($branchId, $startDate, $endDate);
			foreach ($layBuyStats as $layBuyPayment) {
				$totalLaybuy += (float)($layBuyPayment['body_amount'] ?? 0);
			}
		}
	}
	
	
	$totalExpenses = $expense->getTotalExpenses($startDate, $endDate, $selectedBranchId);

	
	
	
	$totalSales += $totalLaybuy;
	$salesRevenue = $totalSales * $profitRate;
	$totalProfit = $salesRevenue - $totalExpenses;
	$profitMargin = ($totalSales > 0) ? ($totalProfit / $totalSales) * 100 : 0;

// Today's transactions
$todayDate = date('Y-m-d');
$todaySalesData = $sales->getSalesForPeriod($todayDate, $todayDate, $selectedBranchId);
$todayIncome = 0;
foreach ($todaySalesData as $todaySale) {
	$todayIncome += (float)($todaySale['total_price'] ?? 0);
}

$todayLaybuyDetails = [];
$todayLaybuyTotal = 0;
if ($selectedBranchId) {
	$todayLaybuyDetails = $laybuy->getBranchLayBuyStats($selectedBranchId, $todayDate, $todayDate);
} else {
	$branchStmt = $conn->prepare("SELECT branch_id FROM branches WHERE branch_id != 7");
	$branchStmt->execute();
	$branchIds = $branchStmt->fetchAll(PDO::FETCH_COLUMN);
	foreach ($branchIds as $branchId) {
		$todayLaybuyDetails = array_merge($todayLaybuyDetails, $laybuy->getBranchLayBuyStats($branchId, $todayDate, $todayDate));
	}
}
foreach ($todayLaybuyDetails as $laybuyPayment) {
	$todayLaybuyTotal += (float)($laybuyPayment['body_amount'] ?? 0);
}
$todayIncome += $todayLaybuyTotal;

// Order deposits received today (initial deposit recorded at order creation)
$orderDepositSql = "SELECT o.order_id, o.order_number, o.item_name, o.customer_name, op.amount as amount_paid, b.branch_name, op.payment_date as created_at
    FROM order_payments op
    JOIN orders o ON o.order_id = op.order_id
    LEFT JOIN branches b ON b.branch_id = o.branch_id
    WHERE DATE(op.payment_date) = :today AND op.is_initial = 1";
if ($selectedBranchId) $orderDepositSql .= " AND o.branch_id = :branch_id";
$orderDepositStmt = $conn->prepare($orderDepositSql);
$orderDepositStmt->bindParam(':today', $todayDate);
if ($selectedBranchId) $orderDepositStmt->bindParam(':branch_id', $selectedBranchId, PDO::PARAM_INT);
$orderDepositStmt->execute();
$todayOrderDeposits = $orderDepositStmt->fetchAll(PDO::FETCH_ASSOC);
$todayOrderDepositsTotal = array_sum(array_column($todayOrderDeposits, 'amount_paid'));

// Additional/balance payments (including final payments) recorded against orders today —
// this is what add_order_payment.php writes to, so it must be sourced from order_payments,
// not orders.final_payment_amount (which is only ever set once, when an order is completed).
$orderFinalSql = "SELECT o.order_id, o.order_number, o.item_name, o.customer_name, op.amount as final_payment_amount, b.branch_name, op.payment_date as completed_at
    FROM order_payments op
    JOIN orders o ON o.order_id = op.order_id
    LEFT JOIN branches b ON b.branch_id = o.branch_id
    WHERE DATE(op.payment_date) = :today AND op.is_initial = 0";
if ($selectedBranchId) $orderFinalSql .= " AND o.branch_id = :branch_id";
$orderFinalStmt = $conn->prepare($orderFinalSql);
$orderFinalStmt->bindParam(':today', $todayDate);
if ($selectedBranchId) $orderFinalStmt->bindParam(':branch_id', $selectedBranchId, PDO::PARAM_INT);
$orderFinalStmt->execute();
$todayOrderFinals = $orderFinalStmt->fetchAll(PDO::FETCH_ASSOC);
$todayOrderFinalsTotal = array_sum(array_column($todayOrderFinals, 'final_payment_amount'));

// Credit sale payments received today
$creditPaySql = "SELECT cp.payment_id, cp.amount, cp.payment_method, cp.notes, cp.payment_date, b.branch_name,
       ca.credit_number, ca.customer_name
    FROM credit_payments cp
    LEFT JOIN credit_accounts ca ON ca.credit_id = cp.credit_id
    LEFT JOIN branches b ON b.branch_id = cp.branch_id
    WHERE DATE(cp.payment_date) = :today";
if ($selectedBranchId) $creditPaySql .= " AND cp.branch_id = :branch_id";
$creditPayStmt = $conn->prepare($creditPaySql);
$creditPayStmt->bindParam(':today', $todayDate);
if ($selectedBranchId) $creditPayStmt->bindParam(':branch_id', $selectedBranchId, PDO::PARAM_INT);
$creditPayStmt->execute();
$todayCreditPayments = $creditPayStmt->fetchAll(PDO::FETCH_ASSOC);
$todayCreditPaymentsTotal = array_sum(array_column($todayCreditPayments, 'amount'));

// Other branch income recorded today (branch_income table)
$branchIncomeSql = "SELECT bi.id, bi.income_type, bi.customer_name, bi.reference, bi.description, bi.amount, bi.payment_method, b.branch_name, bi.created_at
    FROM branch_income bi LEFT JOIN branches b ON b.branch_id = bi.branch_id
    WHERE DATE(bi.created_at) = :today";
if ($selectedBranchId) $branchIncomeSql .= " AND bi.branch_id = :branch_id";
$branchIncomeStmt = $conn->prepare($branchIncomeSql);
$branchIncomeStmt->bindParam(':today', $todayDate);
if ($selectedBranchId) $branchIncomeStmt->bindParam(':branch_id', $selectedBranchId, PDO::PARAM_INT);
$branchIncomeStmt->execute();
$todayBranchIncome = $branchIncomeStmt->fetchAll(PDO::FETCH_ASSOC);
$todayBranchIncomeTotal = array_sum(array_column($todayBranchIncome, 'amount'));

$todayIncome += $todayOrderDepositsTotal + $todayOrderFinalsTotal + $todayCreditPaymentsTotal + $todayBranchIncomeTotal;

$depositQuery = "SELECT d.id as deposit_id, d.branch_id, b.branch_name, d.deposit_date, d.amount, d.notes, u.username AS created_by FROM deposits d LEFT JOIN branches b ON d.branch_id = b.branch_id LEFT JOIN users u ON d.created_by = u.user_id WHERE DATE(d.deposit_date) = :today";
if (!empty($selectedBranchId)) {
	$depositQuery .= " AND d.branch_id = :branch_id";
}
$depositStmt = $conn->prepare($depositQuery);
$depositStmt->bindParam(':today', $todayDate);
if (!empty($selectedBranchId)) {
	$depositStmt->bindParam(':branch_id', $selectedBranchId, PDO::PARAM_INT);
}
$depositStmt->execute();
$todayDepositDetails = $depositStmt->fetchAll(PDO::FETCH_ASSOC);
$todayDeposits = 0;
foreach ($todayDepositDetails as $depositRecord) {
	$todayDeposits += (float)($depositRecord['amount'] ?? 0);
}

$expenseQuery = "SELECT e.*, c.category_name, b.branch_name FROM operational_expenses e LEFT JOIN expense_categories c ON e.expense_category_id = c.category_id LEFT JOIN branches b ON e.branch_id = b.branch_id WHERE DATE(e.expense_date) = :today";
if (!empty($selectedBranchId)) {
	$expenseQuery .= " AND e.branch_id = :branch_id";
}
$expenseStmt = $conn->prepare($expenseQuery);
$expenseStmt->bindParam(':today', $todayDate);
if (!empty($selectedBranchId)) {
	$expenseStmt->bindParam(':branch_id', $selectedBranchId, PDO::PARAM_INT);
}
$expenseStmt->execute();
$todayExpensesDetails = $expenseStmt->fetchAll(PDO::FETCH_ASSOC);
$todayExpenses = 0;
foreach ($todayExpensesDetails as $expenseRecord) {
	$todayExpenses += (float)($expenseRecord['amount'] ?? 0);
}


	$weekStartDate = date('Y-m-d', strtotime('-7 days'));
	$weekEndDate = date('Y-m-d');

	$weeklySalesData = $sales->getSalesForPeriod($weekStartDate, $weekEndDate);
	$weeklySalesTotal = 0;
	if (!empty($weeklySalesData)) {
		foreach ($weeklySalesData as $sale) {
			$weeklySalesTotal += $sale['total_price'];
		}
	}

	$weeklyExpenses = $expense->getTotalExpenses($weekStartDate, $weekEndDate, $selectedBranchId);


	$branch = new Branch($conn);


	$branchesResult = $branch->getAllBranches();
	$branches = $branchesResult->fetchAll(PDO::FETCH_ASSOC);


	$branchLabels = [];
	$branchSales = [];
	$branchExpenses = [];
	$branchProfits = [];


	foreach ($branches as $branchData) {
		$branchId = $branchData['branch_id'];
		if ($selectedBranchId && $branchId != $selectedBranchId) {
			continue;
		}

		$branchLabels[] = $branchData['branch_name'];


		$branchSalesData = $sales->getSalesByBranch($branchId, $startDate, $endDate);
		$branchSalesTotal = 0;
		foreach ($branchSalesData as $sale) {
			$branchSalesTotal += $sale['total_price'];
		}

		$branchLaybuyTotal = 0;
		$layBuyStats = $laybuy->getBranchLayBuyStats($branchId, $startDate, $endDate);
		foreach ($layBuyStats as $layBuyPayment) {
			$branchLaybuyTotal += (float)($layBuyPayment['body_amount'] ?? 0);
		}
		$branchSalesTotal += $branchLaybuyTotal;

		$branchSales[] = $branchSalesTotal;


		$branchExpenseTotal = $expense->getBranchExpenses($branchId, $startDate, $endDate);
		$branchExpenses[] = $branchExpenseTotal;



		$branchRevenue = $branchSalesTotal * $profitRate;
		$branchProfits[] = $branchRevenue - $branchExpenseTotal;
	}


	$expenseCategories = $expense->getExpenseCategories();
	$categoryLabels = [];
	$categoryExpenses = [];

	foreach ($expenseCategories as $category) {
		$categoryLabels[] = $category['category_name'];
		$amount = $expense->getCategoryExpenses($category['category_id'], $startDate, $endDate, $selectedBranchId);
		$categoryExpenses[] = $amount;
	}

	
	
	
?>


<div class="row mb-4">
	<div class="col-md-4">
		<div class="card summary-card">
			<div class="card-body text-center">
				<h5 class="card-title">Total Sales</h5>
				<h3 class="card-text">MWK <?php echo number_format($totalSales, 2); ?></h3>
			</div>
		</div>
	</div>
	<div class="col-md-4">
		<div class="card summary-card">
			<div class="card-body text-center">
				<h5 class="card-title">Total Expenses</h5>
				<h3 class="card-text">MWK <?php echo number_format($totalExpenses, 2); ?></h3>
			</div>
		</div>
	</div>
	<div class="col-md-4">
		<div class="card summary-card">
			<div class="card-body text-center">
				<h5 class="card-title">Net Profit/Loss</h5>
				<h3 class="card-text <?php echo ($totalProfit >= 0) ? 'profit' : 'loss'; ?>">
					MWK <?php echo number_format($totalProfit, 2); ?>
					(<?php echo number_format($profitMargin, 2); ?>%)
				</h3>
			</div>
		</div>
	</div>
</div>

<div class="row mb-4">
	<div class="col-md-4">
		<div class="card summary-card today-summary-card" data-target="#today-income-details" style="cursor:pointer;">
			<div class="card-body text-center">
				<h5 class="card-title">Today's Income</h5>
				<h3 class="card-text">MWK <?php echo number_format($todayIncome, 2); ?></h3>
				<small class="text-muted">Sales, Lay-Buys, Orders, Credit &amp; Other</small>
			</div>
		</div>
	</div>
	<div class="col-md-4">
		<div class="card summary-card today-summary-card" data-target="#today-deposits-details" style="cursor:pointer;">
			<div class="card-body text-center">
				<h5 class="card-title">Today's Deposits</h5>
				<h3 class="card-text">MWK <?php echo number_format($todayDeposits, 2); ?></h3>
				<small class="text-muted">Deposits recorded today</small>
			</div>
		</div>
	</div>
	<div class="col-md-4">
		<div class="card summary-card today-summary-card" data-target="#today-expenses-details" style="cursor:pointer;">
			<div class="card-body text-center">
				<h5 class="card-title">Today's Expenses</h5>
				<h3 class="card-text">MWK <?php echo number_format($todayExpenses, 2); ?></h3>
				<small class="text-muted">Expenses recorded today</small>
			</div>
		</div>
	</div>
</div>

<div class="row mb-4">
	<div class="col-12">
		<div class="card d-none today-details-card" id="today-income-details">
			<div class="card-header">
				<h5>Today's Income Details</h5>
			</div>
			<div class="card-body">
				<?php
				$hasAnyIncome = !empty($todaySalesData) || !empty($todayLaybuyDetails)
					|| !empty($todayOrderDeposits) || !empty($todayOrderFinals)
					|| !empty($todayCreditPayments) || !empty($todayBranchIncome);
				?>
				<?php if (!$hasAnyIncome): ?>
					<p class="text-muted">No income transactions were recorded today.</p>
				<?php else: ?>
					<div class="table-responsive">
						<table class="table table-sm">
							<thead>
								<tr>
									<th>Type</th>
									<th>Description</th>
									<th>Branch</th>
									<th>Amount</th>
									<th>Time</th>
								</tr>
							</thead>
							<tbody>
								<?php foreach ($todaySalesData as $sale): ?>
									<tr>
										<td><span class="badge bg-primary">Sale</span></td>
										<td><?php echo htmlspecialchars($sale['item_name'] ?? 'Sale'); ?></td>
										<td><?php echo htmlspecialchars($sale['branch_name'] ?? ''); ?></td>
										<td>MWK <?php echo number_format($sale['total_price'], 2); ?></td>
										<td><?php echo date('H:i', strtotime($sale['sold_at'] ?? $todayDate)); ?></td>
									</tr>
								<?php endforeach; ?>
								<?php foreach ($todayLaybuyDetails as $lp): ?>
									<tr>
										<td><span class="badge bg-info text-dark">Lay-Buy</span></td>
										<td><?php echo htmlspecialchars($lp['notes'] ?? 'Lay-Buy payment'); ?></td>
										<td><?php echo htmlspecialchars($lp['branch_name'] ?? ''); ?></td>
										<td>MWK <?php echo number_format($lp['body_amount'] ?? 0, 2); ?></td>
										<td><?php echo date('M d', strtotime($lp['payment_date'] ?? $todayDate)); ?></td>
									</tr>
								<?php endforeach; ?>
								<?php foreach ($todayOrderDeposits as $od): ?>
									<tr>
										<td><span class="badge bg-warning text-dark">Order Deposit</span></td>
										<td><?php echo htmlspecialchars($od['customer_name'] . ' — ' . $od['item_name']); ?></td>
										<td><?php echo htmlspecialchars($od['branch_name'] ?? ''); ?></td>
										<td>MWK <?php echo number_format($od['amount_paid'], 2); ?></td>
										<td><?php echo date('H:i', strtotime($od['created_at'])); ?></td>
									</tr>
								<?php endforeach; ?>
								<?php foreach ($todayOrderFinals as $of): ?>
									<tr>
										<td><span class="badge bg-success">Order Balance</span></td>
										<td><?php echo htmlspecialchars($of['customer_name'] . ' — ' . $of['item_name']); ?></td>
										<td><?php echo htmlspecialchars($of['branch_name'] ?? ''); ?></td>
										<td>MWK <?php echo number_format($of['final_payment_amount'], 2); ?></td>
										<td><?php echo date('H:i', strtotime($of['completed_at'])); ?></td>
									</tr>
								<?php endforeach; ?>
								<?php foreach ($todayCreditPayments as $cp): ?>
									<tr>
										<td><span class="badge bg-secondary">Credit Payment</span></td>
										<td><?php echo htmlspecialchars($cp['customer_name'] . ' (' . $cp['credit_number'] . ')'); ?></td>
										<td><?php echo htmlspecialchars($cp['branch_name'] ?? ''); ?></td>
										<td>MWK <?php echo number_format($cp['amount'], 2); ?></td>
										<td><?php echo date('H:i', strtotime($cp['payment_date'])); ?></td>
									</tr>
								<?php endforeach; ?>
								<?php foreach ($todayBranchIncome as $bi): ?>
									<tr>
										<td><span class="badge bg-dark">Other</span></td>
										<td><?php echo htmlspecialchars($bi['description'] ?? $bi['reference'] ?? 'Income'); ?></td>
										<td><?php echo htmlspecialchars($bi['branch_name'] ?? ''); ?></td>
										<td>MWK <?php echo number_format($bi['amount'], 2); ?></td>
										<td><?php echo date('H:i', strtotime($bi['created_at'])); ?></td>
									</tr>
								<?php endforeach; ?>
							</tbody>
						</table>
					</div>
				<?php endif; ?>
			</div>
		</div>
		<div class="card d-none today-details-card" id="today-deposits-details">
			<div class="card-header">
				<h5>Today's Deposits Details</h5>
			</div>
			<div class="card-body">
				<?php if (empty($todayDepositDetails)): ?>
					<p class="text-muted">No deposits were recorded today.</p>
				<?php else: ?>
					<div class="table-responsive">
						<table class="table table-sm">
							<thead>
								<tr>
									<th>Branch</th>
									<th>Deposit Date</th>
									<th>Amount</th>
									<th>Recorded By</th>
									<th>Notes</th>
								</tr>
							</thead>
							<tbody>
								<?php foreach ($todayDepositDetails as $depositRecord): ?>
									<tr>
										<td><?php echo htmlspecialchars($depositRecord['branch_name'] ?? ''); ?></td>
										<td><?php echo htmlspecialchars(date('M d, Y', strtotime($depositRecord['deposit_date']))); ?></td>
										<td>MWK <?php echo number_format($depositRecord['amount'], 2); ?></td>
										<td><?php echo htmlspecialchars($depositRecord['created_by'] ?? ''); ?></td>
										<td><?php echo htmlspecialchars($depositRecord['notes'] ?? ''); ?></td>
									</tr>
								<?php endforeach; ?>
							</tbody>
						</table>
					</div>
				<?php endif; ?>
			</div>
		</div>
		<div class="card d-none today-details-card" id="today-expenses-details">
			<div class="card-header">
				<h5>Today's Expenses Details</h5>
			</div>
			<div class="card-body">
				<?php if (empty($todayExpensesDetails)): ?>
					<p class="text-muted">No expenses were recorded today.</p>
				<?php else: ?>
					<div class="table-responsive">
						<table class="table table-sm">
							<thead>
								<tr>
									<th>Branch</th>
									<th>Date</th>
									<th>Category</th>
									<th>Description</th>
									<th>Amount</th>
								</tr>
							</thead>
							<tbody>
								<?php foreach ($todayExpensesDetails as $expenseRecord): ?>
									<tr>
										<td><?php echo htmlspecialchars($expenseRecord['branch_name'] ?? ''); ?></td>
										<td><?php echo htmlspecialchars(date('M d, Y', strtotime($expenseRecord['expense_date']))); ?></td>
										<td><?php echo htmlspecialchars($expenseRecord['category_name'] ?? ''); ?></td>
										<td><?php echo htmlspecialchars($expenseRecord['description'] ?? ''); ?></td>
										<td>MWK <?php echo number_format($expenseRecord['amount'], 2); ?></td>
									</tr>
								<?php endforeach; ?>
							</tbody>
						</table>
					</div>
				<?php endif; ?>
			</div>
		</div>
	</div>
</div>

<div class="row mb-4">
	<div class="col-md-6 mb-4">
		<div class="card">
			<div class="card-header">
				<h5>Sales by Branch</h5>
			</div>
			<div class="card-body">
				<div class="chart-container">
					<canvas id="salesChart"></canvas>
				</div>
			</div>
		</div>
	</div>

	<div class="col-md-6 mb-4">
		<div class="card">
			<div class="card-header">
				<h5>Expenses by Category</h5>
			</div>
			<div class="card-body">
				<div class="chart-container">
					<canvas id="expensesChart"></canvas>
				</div>
			</div>
		</div>
	</div>

	<div class="col-md-12 mb-4">
		<div class="card">
			<div class="card-header">
				<h5>Profit/Loss by Branch</h5>
			</div>
			<div class="card-body">
				<div class="chart-container">
					<canvas id="profitLossChart"></canvas>
				</div>
			</div>
		</div>
	</div>
</div>

<script>
(function () {
	if (typeof Chart === 'undefined') {
		return;
	}

	if (window.dashboardCharts) {
		Object.keys(window.dashboardCharts).forEach(function (key) {
			if (window.dashboardCharts[key]) {
				window.dashboardCharts[key].destroy();
			}
		});
	}

	window.dashboardCharts = {};

	const branchLabels = <?php echo json_encode($branchLabels); ?>;
	const branchSales = <?php echo json_encode(array_map('floatval', $branchSales)); ?>;
	const categoryLabels = <?php echo json_encode($categoryLabels); ?>;
	const categoryExpenses = <?php echo json_encode(array_map('floatval', $categoryExpenses)); ?>;
	const branchProfits = <?php echo json_encode(array_map('floatval', $branchProfits)); ?>;

	const salesCanvas = document.getElementById('salesChart');
	if (salesCanvas) {
		window.dashboardCharts.sales = new Chart(salesCanvas, {
			type: 'bar',
			data: {
				labels: branchLabels,
				datasets: [{
					label: 'Sales + Laybuy',
					data: branchSales,
					backgroundColor: 'rgba(78, 115, 223, 0.8)',
					borderColor: 'rgba(78, 115, 223, 1)',
					borderWidth: 1
				}]
			},
			options: {
				responsive: true,
				maintainAspectRatio: false,
				scales: {
					y: {
						beginAtZero: true,
						ticks: {
							callback: function (value) {
								return 'MWK ' + Number(value).toLocaleString();
							}
						}
					}
				}
			}
		});
	}

	const expensesCanvas = document.getElementById('expensesChart');
	if (expensesCanvas) {
		window.dashboardCharts.expenses = new Chart(expensesCanvas, {
			type: 'doughnut',
			data: {
				labels: categoryLabels,
				datasets: [{
					data: categoryExpenses,
					backgroundColor: [
						'rgba(231, 74, 59, 0.8)',
						'rgba(246, 194, 62, 0.8)',
						'rgba(28, 200, 138, 0.8)',
						'rgba(54, 185, 204, 0.8)',
						'rgba(133, 135, 150, 0.8)'
					]
				}]
			},
			options: {
				responsive: true,
				maintainAspectRatio: false
			}
		});
	}

	const profitCanvas = document.getElementById('profitLossChart');
	if (profitCanvas) {
		window.dashboardCharts.profit = new Chart(profitCanvas, {
			type: 'bar',
			data: {
				labels: branchLabels,
				datasets: [{
					label: 'Profit/Loss',
					data: branchProfits,
					backgroundColor: branchProfits.map(function (profit) {
						return profit >= 0 ? 'rgba(28, 200, 138, 0.8)' : 'rgba(231, 74, 59, 0.8)';
					}),
					borderColor: branchProfits.map(function (profit) {
						return profit >= 0 ? 'rgba(28, 200, 138, 1)' : 'rgba(231, 74, 59, 1)';
					}),
					borderWidth: 1
				}]
			},
			options: {
				responsive: true,
				maintainAspectRatio: false,
				scales: {
					y: {
						ticks: {
							callback: function (value) {
								return 'MWK ' + Number(value).toLocaleString();
							}
						}
					}
				}
			}
		});
	}
})();
</script>
