// Check if accountant is logged in
if (!isset($_SESSION['accountant_id'])) {
header("Location: login.php");
exit();
}
// Function to sanitize output
function sanitize_output(data) {
return htmlspecialchars(data, ENT_QUOTES, 'UTF-8');
}
// Initialize variables for form feedback
successmessage=′′error_message = '';
Assistant
;
// Handle form submission for adding a new budget
if (_SERVER['REQUEST_METHOD'] === 'POST') {
month = POST[′month′];budgeted_revenue = POST[′budgetedbudgeted_expenses = POST[′budgetednotes = $_POST['notes'];
code
// Validate inputs
if (empty($month) || empty($budgeted_revenue) || empty($budgeted_expenses)) {
$error_message = 'Please fill in all required fields.';
} else {
// Validate month format
if (!preg_match('/^\d{4}-\d{2}$/', $month)) {
$error_message = 'Invalid month format. Please use YYYY-MM.';
} else {
try {
// Check if budget for the month already exists
$stmt = $pdo->prepare("SELECT COUNT(*) FROM budgets WHERE month = ?");
$stmt->execute([$month]);
$count = $stmt->fetchColumn();
if ($count > 0) {
$error_message = 'Budget for this month already exists.';
} else {
$stmt = $pdo->prepare("INSERT INTO budgets (month, budgeted_revenue, budgeted_expenses, notes) VALUES (?, ?, ?, ?)");
$stmt->execute([$month, $budgeted_revenue, $budgeted_expenses, $notes]);
$success_message = 'Budget added successfully.';
}
} catch (PDOException $e) {
$error_message = 'An error occurred while adding the budget.';
}
}
}
}
// Fetch budgets
try {
stmt=pdo->prepare("SELECT * FROM budgets ORDER BY month DESC");
stmt−>execute();budgets = $stmt->fetchAll(PDO::FETCH_ASSOC);
code
// Fetch actual revenues and expenses for variance analysis
foreach ($budgets as &$budget) {
$month_start = $budget['month'] . '-01';
$month_end = date('Y-m-t', strtotime($month_start));
// Actual revenue
$stmt = $pdo->prepare("
SELECT SUM(total_amount) AS actual_revenue
FROM invoices
WHERE invoice_date BETWEEN ? AND ?
");
$stmt->execute([$month_start, $month_end]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$budget['actual_revenue'] = $row['actual_revenue'] ?? 0;
// Actual expenses
$stmt = $pdo->prepare("
SELECT SUM(net_salary) AS actual_expenses
FROM salaries
WHERE payment_date BETWEEN ? AND ?
AND status = 'Paid'
");
$stmt->execute([$month_start, $month_end]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$budget['actual_expenses'] = $row['actual_expenses'] ?? 0;
// Variance calculation
$budget['revenue_variance'] = $budget['actual_revenue'] - $budget['budgeted_revenue'];
$budget['expenses_variance'] = $budget['actual_expenses'] - $budget['budgeted_expenses'];
}