i need to update to accountant part, and this database (-- phpMyAdmin SQL Dump
-- version 5.2.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1:3306
-- Generation Time: Oct 07, 2024 at 05:21 PM
-- Server version: 10.11.9-MariaDB
-- PHP Version: 7.2.34

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `u406552082_info`
--

-- --------------------------------------------------------

--
-- Table structure for table `admins`
--

CREATE TABLE `admins` (
  `id` int(11) NOT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(255) NOT NULL,
  `email` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `budgets`
--

CREATE TABLE `budgets` (
  `id` int(11) NOT NULL,
  `month` varchar(7) DEFAULT NULL,
  `budgeted_revenue` decimal(10,2) DEFAULT NULL,
  `budgeted_expenses` decimal(10,2) DEFAULT NULL,
  `notes` text DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `comments`
--

CREATE TABLE `comments` (
  `id` int(11) NOT NULL,
  `patient_id` int(11) NOT NULL,
  `sender` enum('patient','doctor','admin') NOT NULL,
  `message` text NOT NULL,
  `timestamp` datetime DEFAULT current_timestamp(),
  `parent_id` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `doctors`
--

CREATE TABLE `doctors` (
  `id` int(11) NOT NULL,
  `employee_id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `username` varchar(100) NOT NULL,
  `password` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `specialization` varchar(255) DEFAULT NULL,
  `phone` varchar(20) DEFAULT NULL,
  `registration_date` date DEFAULT curdate(),
  `profile_picture` varchar(255) DEFAULT NULL,
  `department` varchar(100) DEFAULT NULL,
  `date_of_joining` date DEFAULT NULL,
  `status` enum('active','inactive') DEFAULT 'active'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `doctor_patient`
--

CREATE TABLE `doctor_patient` (
  `id` int(11) NOT NULL,
  `doctor_id` int(11) NOT NULL,
  `patient_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `employees`
--

CREATE TABLE `employees` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `role` enum('admin','doctor','staff','accountant') NOT NULL,
  `email` varchar(255) NOT NULL,
  `phone` varchar(20) DEFAULT NULL,
  `department` varchar(100) DEFAULT NULL,
  `date_of_joining` date DEFAULT NULL,
  `status` enum('active','inactive') DEFAULT 'active',
  `username` varchar(100) NOT NULL,
  `password` varchar(255) NOT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  `profile_picture` varchar(255) DEFAULT NULL,
  `specialization` varchar(255) DEFAULT NULL,
  `is_online` tinyint(1) DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `health_records`
--

CREATE TABLE `health_records` (
  `id` int(11) NOT NULL,
  `patient_id` int(11) NOT NULL,
  `blood_pressure` varchar(20) DEFAULT NULL,
  `weight` decimal(5,2) DEFAULT NULL,
  `bmi` decimal(4,2) DEFAULT NULL,
  `cholesterol` decimal(5,2) DEFAULT NULL,
  `prescription` text DEFAULT NULL,
  `treatment_progress` text DEFAULT NULL,
  `record_date` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `insurance_claims`
--

CREATE TABLE `insurance_claims` (
  `id` int(11) NOT NULL,
  `patient_id` int(11) DEFAULT NULL,
  `invoice_id` int(11) DEFAULT NULL,
  `claim_amount` decimal(10,2) DEFAULT NULL,
  `status` enum('Pending','Approved','Rejected') DEFAULT NULL,
  `submission_date` date DEFAULT NULL,
  `processing_date` date DEFAULT NULL,
  `notes` text DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `invoices`
--

CREATE TABLE `invoices` (
  `id` int(11) NOT NULL,
  `patient_id` int(11) NOT NULL,
  `service_name` varchar(255) NOT NULL,
  `service_description` text DEFAULT NULL,
  `cost` decimal(10,2) NOT NULL,
  `tax_rate` decimal(5,2) DEFAULT 0.00,
  `discount` decimal(5,2) DEFAULT 0.00,
  `total_amount` decimal(10,2) NOT NULL,
  `invoice_date` date DEFAULT curdate(),
  `notes` text DEFAULT NULL,
  `tax` decimal(5,2) DEFAULT 0.00
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `invoice_services`
--

CREATE TABLE `invoice_services` (
  `id` int(11) NOT NULL,
  `invoice_id` int(11) NOT NULL,
  `service_id` int(11) NOT NULL,
  `service_name` varchar(255) NOT NULL,
  `cost` decimal(10,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `patients`
--

CREATE TABLE `patients` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `gender` enum('Male','Female','Other') NOT NULL,
  `phone` varchar(20) DEFAULT NULL,
  `email` varchar(100) DEFAULT NULL,
  `medical_history` text DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  `date_of_birth` date DEFAULT NULL,
  `registration_datetime` datetime DEFAULT current_timestamp(),
  `registration_date` date DEFAULT NULL,
  `status` enum('Initial Consultation','Diagnostic Phase','Treatment in Progress','Improving','Monitoring','Maintenance Phase','Awaiting Test Results','Follow-up Needed','Paused','Completed Program','Relapsed','Discontinued','Inactive') DEFAULT 'Initial Consultation',
  `doctor_id` int(11) DEFAULT NULL,
  `address` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `patient_logins`
--

CREATE TABLE `patient_logins` (
  `id` int(11) NOT NULL,
  `patient_id` int(11) NOT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `payments`
--

CREATE TABLE `payments` (
  `id` int(11) NOT NULL,
  `patient_id` int(11) NOT NULL,
  `invoice_id` int(11) NOT NULL,
  `amount_paid` decimal(10,2) NOT NULL,
  `payment_date` date NOT NULL,
  `payment_method` varchar(50) DEFAULT NULL,
  `notes` text DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `prescriptions`
--

CREATE TABLE `prescriptions` (
  `id` int(11) NOT NULL,
  `patient_id` int(11) NOT NULL,
  `doctor_id` int(11) DEFAULT NULL,
  `medications` text NOT NULL,
  `instructions` text DEFAULT NULL,
  `date_prescribed` datetime DEFAULT current_timestamp(),
  `status` enum('active','inactive') DEFAULT 'active'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `salaries`
--

CREATE TABLE `salaries` (
  `id` int(11) NOT NULL,
  `employee_id` int(11) NOT NULL,
  `basic_salary` decimal(10,2) NOT NULL,
  `bonuses` decimal(10,2) DEFAULT 0.00,
  `deductions` decimal(10,2) DEFAULT 0.00,
  `overtime_hours` int(11) DEFAULT 0,
  `overtime_rate` decimal(10,2) DEFAULT 0.00,
  `tax` decimal(10,2) DEFAULT 0.00,
  `payment_date` date NOT NULL,
  `net_salary` decimal(10,2) NOT NULL,
  `status` enum('Pending','Paid') DEFAULT 'Pending',
  `notes` text DEFAULT NULL,
  `payslip_path` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `services`
--

CREATE TABLE `services` (
  `service_id` int(11) NOT NULL,
  `service_name` varchar(255) NOT NULL,
  `service_price` decimal(10,2) NOT NULL,
  `service_description` text DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `admins`
--
ALTER TABLE `admins`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `username` (`username`);

--
-- Indexes for table `budgets`
--
ALTER TABLE `budgets`
  ADD PRIMARY KEY (`id`);

--
-- Indexes for table `comments`
--
ALTER TABLE `comments`
  ADD PRIMARY KEY (`id`),
  ADD KEY `patient_id` (`patient_id`);

--
-- Indexes for table `doctors`
--
ALTER TABLE `doctors`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `username` (`username`),
  ADD UNIQUE KEY `email` (`email`),
  ADD KEY `employee_id` (`employee_id`);

--
-- Indexes for table `doctor_patient`
--
ALTER TABLE `doctor_patient`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `doctor_id` (`doctor_id`,`patient_id`),
  ADD KEY `fk_doctor_patient_patient_id` (`patient_id`);

--
-- Indexes for table `employees`
--
ALTER TABLE `employees`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `email` (`email`),
  ADD UNIQUE KEY `username` (`username`);

--
-- Indexes for table `health_records`
--
ALTER TABLE `health_records`
  ADD PRIMARY KEY (`id`),
  ADD KEY `patient_id` (`patient_id`);

--
-- Indexes for table `insurance_claims`
--
ALTER TABLE `insurance_claims`
  ADD PRIMARY KEY (`id`),
  ADD KEY `patient_id` (`patient_id`),
  ADD KEY `invoice_id` (`invoice_id`);

--
-- Indexes for table `invoices`
--
ALTER TABLE `invoices`
  ADD PRIMARY KEY (`id`),
  ADD KEY `patient_id` (`patient_id`);

--
-- Indexes for table `invoice_services`
--
ALTER TABLE `invoice_services`
  ADD PRIMARY KEY (`id`),
  ADD KEY `invoice_id` (`invoice_id`),
  ADD KEY `service_id` (`service_id`);

--
-- Indexes for table `patients`
--
ALTER TABLE `patients`
  ADD PRIMARY KEY (`id`),
  ADD KEY `doctor_id` (`doctor_id`);

--
-- Indexes for table `patient_logins`
--
ALTER TABLE `patient_logins`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `patient_id` (`patient_id`),
  ADD UNIQUE KEY `username` (`username`);

--
-- Indexes for table `payments`
--
ALTER TABLE `payments`
  ADD PRIMARY KEY (`id`),
  ADD KEY `patient_id` (`patient_id`),
  ADD KEY `invoice_id` (`invoice_id`);

--
-- Indexes for table `prescriptions`
--
ALTER TABLE `prescriptions`
  ADD PRIMARY KEY (`id`),
  ADD KEY `patient_id` (`patient_id`),
  ADD KEY `doctor_id` (`doctor_id`);

--
-- Indexes for table `salaries`
--
ALTER TABLE `salaries`
  ADD PRIMARY KEY (`id`),
  ADD KEY `employee_id` (`employee_id`);

--
-- Indexes for table `services`
--
ALTER TABLE `services`
  ADD PRIMARY KEY (`service_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `admins`
--
ALTER TABLE `admins`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `budgets`
--
ALTER TABLE `budgets`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `comments`
--
ALTER TABLE `comments`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `doctors`
--
ALTER TABLE `doctors`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `doctor_patient`
--
ALTER TABLE `doctor_patient`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `employees`
--
ALTER TABLE `employees`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `health_records`
--
ALTER TABLE `health_records`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `insurance_claims`
--
ALTER TABLE `insurance_claims`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `invoices`
--
ALTER TABLE `invoices`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `invoice_services`
--
ALTER TABLE `invoice_services`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `patients`
--
ALTER TABLE `patients`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `patient_logins`
--
ALTER TABLE `patient_logins`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `payments`
--
ALTER TABLE `payments`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `prescriptions`
--
ALTER TABLE `prescriptions`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `salaries`
--
ALTER TABLE `salaries`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `services`
--
ALTER TABLE `services`
  MODIFY `service_id` int(11) NOT NULL AUTO_INCREMENT;

--
-- Constraints for dumped tables
--

--
-- Constraints for table `comments`
--
ALTER TABLE `comments`
  ADD CONSTRAINT `comments_ibfk_1` FOREIGN KEY (`patient_id`) REFERENCES `patients` (`id`);

--
-- Constraints for table `doctors`
--
ALTER TABLE `doctors`
  ADD CONSTRAINT `doctors_ibfk_1` FOREIGN KEY (`employee_id`) REFERENCES `employees` (`id`);

--
-- Constraints for table `doctor_patient`
--
ALTER TABLE `doctor_patient`
  ADD CONSTRAINT `doctor_patient_fk_doctor_id` FOREIGN KEY (`doctor_id`) REFERENCES `doctors` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `doctor_patient_ibfk_2` FOREIGN KEY (`patient_id`) REFERENCES `patients` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `fk_doctor` FOREIGN KEY (`doctor_id`) REFERENCES `doctors` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `fk_doctor_patient_doctor_id` FOREIGN KEY (`doctor_id`) REFERENCES `doctors` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `fk_doctor_patient_patient_id` FOREIGN KEY (`patient_id`) REFERENCES `patients` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

--
-- Constraints for table `health_records`
--
ALTER TABLE `health_records`
  ADD CONSTRAINT `health_records_ibfk_1` FOREIGN KEY (`patient_id`) REFERENCES `patients` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `insurance_claims`
--
ALTER TABLE `insurance_claims`
  ADD CONSTRAINT `insurance_claims_ibfk_1` FOREIGN KEY (`patient_id`) REFERENCES `patients` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `insurance_claims_ibfk_2` FOREIGN KEY (`invoice_id`) REFERENCES `invoices` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `invoices`
--
ALTER TABLE `invoices`
  ADD CONSTRAINT `invoices_ibfk_1` FOREIGN KEY (`patient_id`) REFERENCES `patients` (`id`);

--
-- Constraints for table `invoice_services`
--
ALTER TABLE `invoice_services`
  ADD CONSTRAINT `invoice_services_ibfk_1` FOREIGN KEY (`invoice_id`) REFERENCES `invoices` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `invoice_services_ibfk_2` FOREIGN KEY (`service_id`) REFERENCES `services` (`service_id`) ON DELETE CASCADE;

--
-- Constraints for table `patients`
--
ALTER TABLE `patients`
  ADD CONSTRAINT `patients_ibfk_1` FOREIGN KEY (`doctor_id`) REFERENCES `doctors` (`id`) ON DELETE SET NULL ON UPDATE CASCADE;

--
-- Constraints for table `patient_logins`
--
ALTER TABLE `patient_logins`
  ADD CONSTRAINT `patient_logins_ibfk_1` FOREIGN KEY (`patient_id`) REFERENCES `patients` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `payments`
--
ALTER TABLE `payments`
  ADD CONSTRAINT `payments_ibfk_1` FOREIGN KEY (`patient_id`) REFERENCES `patients` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `payments_ibfk_2` FOREIGN KEY (`invoice_id`) REFERENCES `invoices` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

--
-- Constraints for table `prescriptions`
--
ALTER TABLE `prescriptions`
  ADD CONSTRAINT `prescriptions_ibfk_1` FOREIGN KEY (`patient_id`) REFERENCES `patients` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `prescriptions_ibfk_2` FOREIGN KEY (`doctor_id`) REFERENCES `doctors` (`id`) ON DELETE SET NULL;

--
-- Constraints for table `salaries`
--
ALTER TABLE `salaries`
  ADD CONSTRAINT `salaries_ibfk_1` FOREIGN KEY (`employee_id`) REFERENCES `employees` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;) and path (./accountant/dashboard.php
./accountant/manage_invoices.php
./accountant/view_invoice.php
./accountant/patient_financial_summary.php
./accountant/create_insurance_claim.php
./accountant/financial_forecasting.php
./accountant/mark_paid.php
./accountant/login.php
./accountant/important_text (should be renamed for clarity)
./accountant/edit_invoice.php
./accountant/generate_report.php
./accountant/view_patient_financial_summary.php
./accountant/manage_salaries.php
./accountant/manage_payments.php
./accountant/accountant_profile.php
./accountant/delete_payment.php
./accountant/generate_payslip.php
./accountant/budget_management.php
./accountant/edit_salary.php
./accountant/insurance_claim_tracker.php
./accountant/delete_invoice.php
./accountant/logout.php
./accountant/trend_analysis.php
./accountant/create_payment.php
./accountant/financial_dashboard.php
./accountant/add_salary.php
./accountant/edit_payment.php
./accountant/create_invoice.php
./accountant/delete_salary.php
./accountant/upload/payslips/payslip_1.pdf
./accountant/upload/payslips/payslip_5.pdf
./accountant/upload/payslips/payslip_6.pdf
./accountant/edit_salary_form.php
./accountant/view_salaries.php
./accountant/bulk_actions.php
) so tell me what needs to add or the important things and this dasboard of codes (<?php
// accountant/dashboard.php

session_start();
require_once '../db_connect.php';

// Disable error reporting in production
// ini_set('display_errors', 0);
// error_reporting(0);

// Enable error reporting during development (comment out in production)
// ini_set('display_errors', 1);
// error_reporting(E_ALL);

// Function to sanitize output
function sanitize_output($data) {
    return htmlspecialchars($data ?? '', ENT_QUOTES, 'UTF-8');
}

// Check if accountant is logged in
if (!isset($_SESSION['accountant_id'])) {
    // Not logged in, redirect to login page
    header("Location: login.php");
    exit();
}

// Retrieve and validate date range from GET parameters
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-d', strtotime('-30 days'));
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d');

// Validate date formats
function validate_date($date, $format = 'Y-m-d') {
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) === $date;
}

if (!validate_date($start_date) || !validate_date($end_date)) {
    // Invalid date format, set to default last 30 days
    $start_date = date('Y-m-d', strtotime('-30 days'));
    $end_date = date('Y-m-d');
}

// Ensure start_date is not after end_date
if ($start_date > $end_date) {
    // Swap dates
    $temp = $start_date;
    $start_date = $end_date;
    $end_date = $temp;
}

try {
    // Total number of invoices
    $stmt = $pdo->prepare("
        SELECT COUNT(*) AS total_invoices
        FROM invoices
        WHERE invoice_date BETWEEN ? AND ?
    ");
    $stmt->execute([$start_date, $end_date]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $total_invoices = $row['total_invoices'];

    // Total revenue from invoices with corrected calculations
    $stmt = $pdo->prepare("
        SELECT SUM((i.cost - i.discount) + ((i.cost - i.discount) * (i.tax_rate / 100))) AS total_revenue
        FROM invoices i
        WHERE i.invoice_date BETWEEN ? AND ?
    ");
    $stmt->execute([$start_date, $end_date]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $total_revenue = $row['total_revenue'] ?? 0;

    // Average revenue per invoice
    $average_revenue = $total_invoices > 0 ? $total_revenue / $total_invoices : 0;

    // Total salaries paid (sum of net_salary where status is 'Paid')
    $stmt = $pdo->prepare("
        SELECT SUM(net_salary) AS total_salaries
        FROM salaries
        WHERE payment_date BETWEEN ? AND ? AND status = 'Paid'
    ");
    $stmt->execute([$start_date, $end_date]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $total_salaries = $row['total_salaries'] ?? 0;

    // Total expenses (assuming salaries are the primary expenses)
    $total_expenses = $total_salaries;

    // Profit (Revenue - Expenses)
    $profit = $total_revenue - $total_expenses;

    // Outstanding payments (invoices not fully paid)
    $stmt = $pdo->prepare("
        SELECT i.id, i.invoice_date, i.patient_id,
            (i.cost - i.discount) + ((i.cost - i.discount) * (i.tax_rate / 100)) AS invoice_total,
            IFNULL(SUM(p.amount_paid), 0) AS total_paid
        FROM invoices i
        LEFT JOIN payments p ON i.id = p.invoice_id
        WHERE i.invoice_date BETWEEN ? AND ?
        GROUP BY i.id
        HAVING invoice_total > total_paid
    ");
    $stmt->execute([$start_date, $end_date]);
    $outstanding_rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $outstanding_payments = 0;
    foreach ($outstanding_rows as $out) {
        $outstanding_payments += ($out['invoice_total'] - $out['total_paid']);
    }

    // Total payments received
    $stmt = $pdo->prepare("
        SELECT SUM(amount_paid) AS total_payments
        FROM payments
        WHERE payment_date BETWEEN ? AND ?
    ");
    $stmt->execute([$start_date, $end_date]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $total_payments = $row['total_payments'] ?? 0;

    // Fetch data for charts
    // Revenue over time (grouped by month) with corrected calculations
    $stmt = $pdo->prepare("
        SELECT DATE_FORMAT(i.invoice_date, '%Y-%m') AS month,
            SUM((i.cost - i.discount) + ((i.cost - i.discount) * (i.tax_rate / 100))) AS revenue
        FROM invoices i
        WHERE i.invoice_date BETWEEN ? AND ?
        GROUP BY month
        ORDER BY month ASC
    ");
    $stmt->execute([$start_date, $end_date]);
    $revenue_data = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Expenses over time (grouped by month)
    $stmt = $pdo->prepare("
        SELECT DATE_FORMAT(payment_date, '%Y-%m') AS month, SUM(net_salary) AS expenses
        FROM salaries
        WHERE payment_date BETWEEN ? AND ? AND status = 'Paid'
        GROUP BY month
        ORDER BY month ASC
    ");
    $stmt->execute([$start_date, $end_date]);
    $expenses_data = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Budget Variance Analysis
    // Convert start_date and end_date to months
    $start_month = date('Y-m', strtotime($start_date));
    $end_month = date('Y-m', strtotime($end_date));

    // Get all months between start_month and end_month
    $budget_period = new DatePeriod(
        new DateTime($start_month . '-01'),
        new DateInterval('P1M'),
        (new DateTime($end_month . '-01'))->modify('+1 month')
    );

    $total_budgeted_revenue = 0;
    $total_budgeted_expenses = 0;
    $budgeted_revenues = [];
    $budgeted_expenses = [];

    foreach ($budget_period as $dt) {
        $month = $dt->format('Y-m');
        // Fetch budget data for the month
        $stmt = $pdo->prepare("SELECT * FROM budgets WHERE month = ?");
        $stmt->execute([$month]);
        $budget = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($budget) {
            $total_budgeted_revenue += $budget['budgeted_revenue'];
            $total_budgeted_expenses += $budget['budgeted_expenses'];
            $budgeted_revenues[$month] = $budget['budgeted_revenue'];
            $budgeted_expenses[$month] = $budget['budgeted_expenses'];
        } else {
            // If no budget exists for the month, assume 0
            $budgeted_revenues[$month] = 0;
            $budgeted_expenses[$month] = 0;
        }
    }

    // Calculate variances
    $revenue_variance = $total_revenue - $total_budgeted_revenue;
    $expenses_variance = $total_expenses - $total_budgeted_expenses;

} catch (PDOException $e) {
    // Log the error to a file (for production)
    // error_log($e->getMessage(), 3, '../logs/error.log');

    // Display a user-friendly message
    echo "An error occurred while fetching dashboard data. Please try again later.";
    exit();
}

// Prepare data for charts
$months = [];
$revenues = [];
$expenses = [];
$budgeted_revenues_chart = [];
$budgeted_expenses_chart = [];
$profits = [];

$start = new DateTime($start_month . '-01');
$end = new DateTime($end_month . '-01');
$end->modify('+1 month');
$period = new DatePeriod($start, new DateInterval('P1M'), $end);

foreach ($period as $dt) {
    $current_month = $dt->format('Y-m');
    $months[] = $current_month;
    $revenues[$current_month] = 0; // Initialize with 0
    $expenses[$current_month] = 0; // Initialize with 0
    $budgeted_revenues_chart[$current_month] = $budgeted_revenues[$current_month] ?? 0; // budgeted revenue for the month
    $budgeted_expenses_chart[$current_month] = $budgeted_expenses[$current_month] ?? 0; // budgeted expenses for the month
}

// Map revenue data
foreach ($revenue_data as $data) {
    $month = $data['month'];
    if (isset($revenues[$month])) {
        $revenues[$month] = $data['revenue'];
    }
}

// Map expenses data
foreach ($expenses_data as $data) {
    $month = $data['month'];
    if (isset($expenses[$month])) {
        $expenses[$month] = $data['expenses'];
    }
}

// Calculate profits for each month
$profits = [];
foreach ($months as $month) {
    $profit = $revenues[$month] - $expenses[$month];
    $profits[] = $profit;
}

// Prepare data arrays for charts
$chart_months = array_values($months);
$chart_revenues = array_values($revenues);
$chart_expenses = array_values($expenses);
$chart_budgeted_revenues = array_values($budgeted_revenues_chart);
$chart_budgeted_expenses = array_values($budgeted_expenses_chart);
$chart_profits = $profits;

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Accountant Dashboard</title>
    <!-- Meta tags for responsiveness -->
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Bootstrap CSS and Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Chart.js Library -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <!-- Custom Styles -->
    <style>
        /* Import Google Fonts */
        @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700&display=swap');

        /* Root Variables */
        :root {
            --primary-color: #4F3F02;
            --secondary-color: #D1C287;
            --background-color: #F8F9FA;
            --card-background: #FFFFFF;
            --text-color: #333333;
            --success-color: #28a745;
            --danger-color: #dc3545;
            --info-color: #17a2b8;
            --font-family: 'Poppins', sans-serif;
        }

        body {
            background-color: var(--background-color);
            font-family: var(--font-family);
            color: var(--text-color);
        }

        /* Header */
        .dashboard-header {
            background-color: var(--primary-color);
            color: #fff;
            padding: 20px;
            text-align: center;
            border-radius: 0 0 20px 20px;
            margin-bottom: 30px;
            position: relative;
        }

        .dashboard-header h1 {
            font-weight: 700;
            margin-bottom: 10px;
        }

        .dashboard-header p a {
            color: #fff;
            margin: 0 10px;
            text-decoration: none;
        }

        .dashboard-header p a:hover {
            text-decoration: underline;
        }

        /* Cards */
        .card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            margin-bottom: 25px;
            background-color: var(--card-background);
        }

        .card .card-body {
            padding: 20px;
        }

        .card .card-title {
            color: var(--primary-color);
            font-weight: 600;
            margin-bottom: 10px;
            font-size: 1.1em;
        }

        .card .card-text {
            font-size: 1.8em;
            font-weight: 700;
        }

        /* Buttons */
        .btn-custom {
            background-color: var(--secondary-color);
            border-color: var(--secondary-color);
            color: var(--primary-color);
            font-weight: 600;
            width: 100%;
            padding: 12px;
            border-radius: 8px;
            transition: all 0.3s ease;
            text-decoration: none;
            text-align: center;
            display: inline-block;
        }

        .btn-custom:hover {
            background-color: var(--primary-color);
            color: #fff;
            border-color: var(--secondary-color);
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
        }

        /* Filters */
        .filters {
            background-color: var(--card-background);
            padding: 20px;
            border-radius: 15px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            margin-bottom: 30px;
        }

        /* Charts */
        .chart-container {
            position: relative;
            height: 400px;
            margin-bottom: 30px;
        }

        /* Responsive Adjustments */
        @media (max-width: 768px) {
            .dashboard-header h1 {
                font-size: 22px;
            }

            .btn-custom {
                margin-bottom: 15px;
            }
        }

        @media (max-width: 576px) {
            .dashboard-header h1 {
                font-size: 18px;
            }

            .card .card-body {
                padding: 15px;
            }

            .card .card-text {
                font-size: 1.4em;
            }

            .filters {
                padding: 15px;
            }

            .chart-container {
                height: 250px;
            }
        }

        /* Dark Mode Styles */
        body.dark-mode {
            background-color: #1F1F1F;
            color: #e0e0e0;
        }

        body.dark-mode .dashboard-header {
            background-color: #121212;
        }

        body.dark-mode .card {
            background-color: #2C2C2C;
            box-shadow: none;
        }

        body.dark-mode .filters {
            background-color: #2C2C2C;
            box-shadow: none;
        }

        body.dark-mode .btn-custom {
            background-color: #3A3A3A;
            border-color: #3A3A3A;
            color: #fff;
        }

        body.dark-mode .btn-custom:hover {
            background-color: #555;
            border-color: #555;
            color: #fff;
        }

        /* Dark Mode Toggle Button */
        .dark-mode-toggle {
            position: absolute;
            top: 20px;
            right: 20px;
        }

        /* Tooltip Styles */
        .chartjs-tooltip {
            opacity: 1;
            position: absolute;
            background: rgba(0, 0, 0, .7);
            color: white;
            padding: 6px;
            border-radius: 3px;
            pointer-events: none;
            transform: translate(-50%, 0);
        }

        .tooltip-title {
            font-weight: 600;
            margin-bottom: 4px;
        }

        .tooltip-item {
            display: flex;
            align-items: center;
        }

        .tooltip-box {
            width: 10px;
            height: 10px;
            background-color: red;
            display: inline-block;
            margin-right: 6px;
        }

    </style>
</head>
<body>
    <div class="dashboard-header">
        <h1>Welcome, <?php echo sanitize_output($_SESSION['accountant_username']); ?></h1>
        <p>
            <a href="accountant_profile.php">Profile</a> | <a href="logout.php">Logout</a>
        </p>
        <button id="toggleDarkMode" class="btn btn-secondary btn-sm dark-mode-toggle">Toggle Dark Mode</button>
    </div>

    <div class="container">

        <!-- Date Range Filters -->
        <div class="filters">
            <form method="GET" action="" class="row g-3">
                <div class="col-md-5">
                    <label for="start_date" class="form-label">Start Date:</label>
                    <input type="date" id="start_date" name="start_date" class="form-control" value="<?php echo sanitize_output($start_date); ?>" required>
                </div>
                <div class="col-md-5">
                    <label for="end_date" class="form-label">End Date:</label>
                    <input type="date" id="end_date" name="end_date" class="form-control" value="<?php echo sanitize_output($end_date); ?>" required>
                </div>
                <div class="col-md-2 d-flex align-items-end">
                    <button type="submit" class="btn btn-custom">Apply Filters</button>
                </div>
            </form>
        </div>

        <!-- Financial Metrics -->
        <div class="row">
            <!-- Revenue Metrics -->
            <div class="col-lg-6">
                <h4 style="color: var(--primary-color); font-weight: 700; margin-bottom: 20px;">Revenue Metrics</h4>
                <div class="row">
                    <!-- Total Revenue -->
                    <div class="col-md-6">
                        <div class="card text-center">
                            <div class="card-body">
                                <h5 class="card-title">Total Revenue</h5>
                                <p class="card-text">$<?php echo number_format($total_revenue, 2); ?></p>
                            </div>
                        </div>
                    </div>
                    <!-- Budgeted Revenue -->
                    <div class="col-md-6">
                        <div class="card text-center">
                            <div class="card-body">
                                <h5 class="card-title">Budgeted Revenue</h5>
                                <p class="card-text">$<?php echo number_format($total_budgeted_revenue, 2); ?></p>
                            </div>
                        </div>
                    </div>
                    <!-- Revenue Variance -->
                    <div class="col-md-6">
                        <div class="card text-center">
                            <div class="card-body">
                                <h5 class="card-title">Revenue Variance</h5>
                                <p class="card-text" style="color: <?php echo $revenue_variance >= 0 ? 'var(--success-color)' : 'var(--danger-color)'; ?>">
                                    $<?php echo number_format($revenue_variance, 2); ?>
                                </p>
                            </div>
                        </div>
                    </div>
                    <!-- Average Revenue per Invoice -->
                    <div class="col-md-6">
                        <div class="card text-center">
                            <div class="card-body">
                                <h5 class="card-title">Avg. Revenue per Invoice</h5>
                                <p class="card-text">$<?php echo number_format($average_revenue, 2); ?></p>
                            </div>
                        </div>
                    </div>
                    <!-- Total Invoices -->
                    <div class="col-md-12">
                        <div class="card text-center">
                            <div class="card-body">
                                <h5 class="card-title">Total Invoices</h5>
                                <p class="card-text"><?php echo number_format($total_invoices); ?></p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- Expense Metrics -->
            <div class="col-lg-6">
                <h4 style="color: var(--primary-color); font-weight: 700; margin-bottom: 20px;">Expense Metrics</h4>
                <div class="row">
                    <!-- Total Expenses -->
                    <div class="col-md-6">
                        <div class="card text-center">
                            <div class="card-body">
                                <h5 class="card-title">Total Expenses</h5>
                                <p class="card-text">$<?php echo number_format($total_expenses, 2); ?></p>
                            </div>
                        </div>
                    </div>
                    <!-- Budgeted Expenses -->
                    <div class="col-md-6">
                        <div class="card text-center">
                            <div class="card-body">
                                <h5 class="card-title">Budgeted Expenses</h5>
                                <p class="card-text">$<?php echo number_format($total_budgeted_expenses, 2); ?></p>
                            </div>
                        </div>
                    </div>
                    <!-- Expenses Variance -->
                    <div class="col-md-6">
                        <div class="card text-center">
                            <div class="card-body">
                                <h5 class="card-title">Expenses Variance</h5>
                                <p class="card-text" style="color: <?php echo $expenses_variance <= 0 ? 'var(--success-color)' : 'var(--danger-color)'; ?>">
                                    $<?php echo number_format($expenses_variance, 2); ?>
                                </p>
                            </div>
                        </div>
                    </div>
                    <!-- Profit -->
                    <div class="col-md-6">
                        <div class="card text-center">
                            <div class="card-body">
                                <h5 class="card-title">Profit</h5>
                                <p class="card-text" style="color: <?php echo $profit >= 0 ? 'var(--success-color)' : 'var(--danger-color)'; ?>">
                                    $<?php echo number_format($profit, 2); ?>
                                </p>
                            </div>
                        </div>
                    </div>
                    <!-- Outstanding Payments -->
                    <div class="col-md-12">
                        <div class="card text-center">
                            <div class="card-body">
                                <h5 class="card-title">Outstanding Payments</h5>
                                <p class="card-text" style="color: var(--danger-color);">
                                    $<?php echo number_format($outstanding_payments, 2); ?>
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Charts -->
        <div class="row">
            <!-- Revenue vs. Expenses Chart -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">Revenue vs. Expenses Over Time</h5>
                        <div class="chart-container">
                            <canvas id="revenueExpensesChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            <!-- Profit Over Time Chart -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">Profit Over Time</h5>
                        <div class="chart-container">
                            <canvas id="profitChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Actions -->
        <h3 class="mt-5 mb-4" style="color: var(--primary-color); font-weight: 700;">Actions</h3>
        <div class="row">
            <div class="col-md-4 mb-3">
                <a href="manage_invoices.php" class="btn btn-custom">Manage Invoices</a>
            </div>
            <div class="col-md-4 mb-3">
                <a href="manage_payments.php" class="btn btn-custom">Manage Payments</a>
            </div>
            <div class="col-md-4 mb-3">
                <a href="manage_salaries.php" class="btn btn-custom">Manage Salaries</a>
            </div>
            <div class="col-md-4 mb-3">
                <a href="budget_management.php" class="btn btn-custom">Budget Management</a>
            </div>
            <div class="col-md-4 mb-3">
                <a href="financial_dashboard.php" class="btn btn-custom">Financial Dashboard</a>
            </div>
            <div class="col-md-4 mb-3">
                <a href="financial_forecasting.php" class="btn btn-custom">Financial Forecasting</a>
            </div>
            <div class="col-md-6 mb-3">
                <a href="insurance_claim_tracker.php" class="btn btn-custom">Insurance Claim Tracker</a>
            </div>
            <div class="col-md-6 mb-3">
                <a href="patient_financial_summary.php" class="btn btn-custom">Patient Financial Summary</a>
            </div>
        </div>

    </div>

    <!-- Bootstrap JS and dependencies -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- Chart.js Script -->
    <script>
        (function() {
            // Revenue vs. Expenses Chart
            const ctx1 = document.getElementById('revenueExpensesChart').getContext('2d');
            const revenueExpensesChart = new Chart(ctx1, {
                type: 'line',
                data: {
                    labels: <?php echo json_encode($chart_months); ?>,
                    datasets: [
                        {
                            label: 'Actual Revenue',
                            data: <?php echo json_encode($chart_revenues); ?>,
                            borderColor: 'rgba(40, 167, 69, 1)', // Green
                            backgroundColor: 'rgba(40, 167, 69, 0.2)',
                            fill: true,
                            tension: 0.3,
                            pointRadius: 3,
                        },
                        {
                            label: 'Actual Expenses',
                            data: <?php echo json_encode($chart_expenses); ?>,
                            borderColor: 'rgba(220, 53, 69, 1)', // Red
                            backgroundColor: 'rgba(220, 53, 69, 0.2)',
                            fill: true,
                            tension: 0.3,
                            pointRadius: 3,
                        },
                        {
                            label: 'Budgeted Revenue',
                            data: <?php echo json_encode($chart_budgeted_revenues); ?>,
                            borderColor: 'rgba(23, 162, 184, 1)', // Blue
                            backgroundColor: 'rgba(23, 162, 184, 0.0)',
                            fill: false,
                            tension: 0.3,
                            borderDash: [5, 5],
                            pointRadius: 3,
                        },
                        {
                            label: 'Budgeted Expenses',
                            data: <?php echo json_encode($chart_budgeted_expenses); ?>,
                            borderColor: 'rgba(255, 193, 7, 1)', // Yellow
                            backgroundColor: 'rgba(255, 193, 7, 0.0)',
                            fill: false,
                            tension: 0.3,
                            borderDash: [5, 5],
                            pointRadius: 3,
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    interaction: {
                        mode: 'index',
                        intersect: false
                    },
                    plugins: {
                        legend: {
                            labels: {
                                font: {
                                    family: 'Poppins',
                                    size: 14,
                                    weight: '600'
                                }
                            }
                        },
                        tooltip: {
                            enabled: true,
                            callbacks: {
                                label: function(context) {
                                    let label = context.dataset.label || '';
                                    if (label) {
                                        label += ': ';
                                    }
                                    if (context.parsed.y !== null) {
                                        label += '$' + parseFloat(context.parsed.y).toLocaleString();
                                    }
                                    return label;
                                }
                            }
                        }
                    },
                    scales: {
                        x: {
                            title: {
                                display: true,
                                text: 'Month',
                                font: {
                                    family: 'Poppins',
                                    size: 14,
                                    weight: '600'
                                }
                            },
                            ticks: {
                                autoSkip: true,
                                maxTicksLimit: 20,
                                font: {
                                    family: 'Poppins',
                                }
                            },
                            grid: {
                                display: false
                            }
                        },
                        y: {
                            title: {
                                display: true,
                                text: 'Amount ($)',
                                font: {
                                    family: 'Poppins',
                                    size: 14,
                                    weight: '600'
                                }
                            },
                            ticks: {
                                beginAtZero: true,
                                font: {
                                    family: 'Poppins',
                                },
                                callback: function(value) {
                                    return '$' + parseFloat(value).toLocaleString();
                                }
                            },
                            grid: {
                                color: '#e9ecef'
                            }
                        }
                    }
                }
            });

            // Profit Over Time Chart
            const ctx2 = document.getElementById('profitChart').getContext('2d');
            const profitChart = new Chart(ctx2, {
                type: 'bar',
                data: {
                    labels: <?php echo json_encode($chart_months); ?>,
                    datasets: [
                        {
                            label: 'Profit',
                            data: <?php echo json_encode($chart_profits); ?>,
                            backgroundColor: function(context) {
                                var value = context.dataset.data[context.dataIndex];
                                return value >= 0 ? 'rgba(75, 192, 192, 0.6)' : 'rgba(220, 53, 69, 0.6)';
                            },
                            borderColor: function(context) {
                                var value = context.dataset.data[context.dataIndex];
                                return value >= 0 ? 'rgba(75, 192, 192, 1)' : 'rgba(220, 53, 69, 1)';
                            },
                            borderWidth: 1,
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false,
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    let label = context.dataset.label || '';
                                    if (label) {
                                        label += ': ';
                                    }
                                    if (context.parsed.y !== null) {
                                        label += '$' + parseFloat(context.parsed.y).toLocaleString();
                                    }
                                    return label;
                                }
                            }
                        },
                    },
                    scales: {
                        x: {
                            title: {
                                display: true,
                                text: 'Month',
                                font: {
                                    family: 'Poppins',
                                    size: 14,
                                    weight: '600'
                                }
                            },
                            ticks: {
                                font: {
                                    family: 'Poppins',
                                }
                            },
                            grid: {
                                display: false
                            }
                        },
                        y: {
                            title: {
                                display: true,
                                text: 'Profit ($)',
                                font: {
                                    family: 'Poppins',
                                    size: 14,
                                    weight: '600'
                                }
                            },
                            ticks: {
                                beginAtZero: true,
                                font: {
                                    family: 'Poppins',
                                },
                                callback: function(value) {
                                    return '$' + parseFloat(value).toLocaleString();
                                }
                            },
                            grid: {
                                color: '#e9ecef'
                            }
                        }
                    }
                }
            });
        })();
    </script>

    <!-- Dark Mode Toggle Script -->
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const darkModeToggle = document.getElementById('toggleDarkMode');

            // Toggle dark mode on button click
            darkModeToggle.addEventListener('click', function() {
                document.body.classList.toggle('dark-mode');
                // Save preference in localStorage
                if(document.body.classList.contains('dark-mode')) {
                    localStorage.setItem('theme', 'dark');
                    this.innerText = 'Light Mode';
                } else {
                    localStorage.setItem('theme', 'light');
                    this.innerText = 'Dark Mode';
                }
            });

            // Load theme preference on page load
            const savedTheme = localStorage.getItem('theme');
            if(savedTheme === 'dark') {
                document.body.classList.add('dark-mode');
                darkModeToggle.innerText = 'Light Mode';
            } else {
                darkModeToggle.innerText = 'Dark Mode';
            }
        });
    </script>
</body>
</html>)