in this codes (<?php
// accountant/manage_salaries.php

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

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

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

// Generate CSRF token if not set
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Initialize feedback messages
$success = isset($_SESSION['success']) ? $_SESSION['success'] : '';
$error = isset($_SESSION['error']) ? $_SESSION['error'] : '';
unset($_SESSION['success'], $_SESSION['error']);

// Fetch filter parameters from GET request
$start_date = isset($_GET['start_date']) && !empty($_GET['start_date']) ? $_GET['start_date'] : '';
$end_date = isset($_GET['end_date']) && !empty($_GET['end_date']) ? $_GET['end_date'] : '';
$status_filter = isset($_GET['status_filter']) && !empty($_GET['status_filter']) ? $_GET['status_filter'] : '';

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

if (($start_date && !validate_date($start_date)) || ($end_date && !validate_date($end_date))) {
    $_SESSION['error'] = "Invalid date format for filters.";
    header("Location: manage_salaries.php");
    exit();
}

// Fetch all statuses for filtering
$statusOptions = ['Pending', 'Paid'];

// Build the SQL query with filters
$sql = "
    SELECT salaries.*, employees.name AS employee_name
    FROM salaries
    JOIN employees ON salaries.employee_id = employees.id
";

$conditions = [];
$params = [];

// Apply filters if set
if ($start_date) {
    $conditions[] = "salaries.payment_date >= :start_date";
    $params[':start_date'] = $start_date;
}

if ($end_date) {
    $conditions[] = "salaries.payment_date <= :end_date";
    $params[':end_date'] = $end_date;
}

if ($status_filter && in_array($status_filter, $statusOptions)) {
    $conditions[] = "salaries.status = :status_filter";
    $params[':status_filter'] = $status_filter;
}

if (count($conditions) > 0) {
    $sql .= " WHERE " . implode(" AND ", $conditions);
}

$sql .= " ORDER BY salaries.payment_date DESC";

try {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $salaries = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    // Log error for debugging
    error_log($e->getMessage(), 3, '../logs/error.log');
    die("An error occurred while fetching salaries. Please try again later.");
}

// Fetch all active employees for the 'Add Salary' form
try {
    $empStmt = $pdo->prepare("SELECT id, name FROM employees WHERE status = 'active' ORDER BY name ASC");
    $empStmt->execute();
    $employees = $empStmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    // Log error for debugging
    error_log($e->getMessage(), 3, '../logs/error.log');
    die("An error occurred while fetching employees. Please try again later.");
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Manage Salaries - Longevacare</title>
    <!-- Meta tags for responsiveness -->
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- 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;
        }

        /* Reset and Base Styles */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            background-color: var(--background-color);
            font-family: var(--font-family);
            color: var(--text-color);
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

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

        .dashboard-header h1 {
            font-weight: 700;
            font-size: 2.5em;
        }

        .dashboard-header p {
            margin-top: 10px;
            font-size: 1em;
        }

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

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

        /* Container */
        .container {
            flex: 1;
        }

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

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

        .card .card-title {
            color: var(--primary-color);
            font-weight: 600;
            margin-bottom: 15px;
        }

        .card .card-text {
            font-size: 1.2em;
            font-weight: 500;
        }

        /* Buttons */
        .btn-custom {
            background-color: var(--secondary-color);
            border-color: var(--secondary-color);
            color: var(--primary-color);
            font-weight: 600;
            padding: 10px 20px;
            border-radius: 10px;
            transition: all 0.3s ease;
            cursor: pointer;
        }

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

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

        /* Modal Styles */
        .modal-header {
            background-color: var(--primary-color);
            color: #fff;
        }

        .modal-footer .btn-custom {
            width: auto;
        }

        /* DataTables Custom Styles */
        table.dataTable thead th, table.dataTable tfoot th {
            background-color: var(--primary-color);
            color: #fff;
            font-weight: 600;
        }

        table.dataTable tbody tr:nth-child(even) {
            background-color: #f2f2f2;
        }

        body.dark-mode table.dataTable tbody tr:nth-child(even) {
            background-color: #2c2c2c;
        }

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

        body.dark-mode .dashboard-header {
            background-color: #1f1f1f;
            color: #e0e0e0;
        }

        body.dark-mode .card {
            background-color: #1f1f1f;
            box-shadow: 0 6px 10px rgba(255, 255, 255, 0.05);
        }

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

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

        body.dark-mode .filters {
            background-color: #1f1f1f;
            box-shadow: 0 6px 10px rgba(255, 255, 255, 0.05);
        }

        body.dark-mode .card-title {
            color: #d1c287;
        }

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

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

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

            .filters {
                padding: 20px;
            }

            .btn-custom {
                padding: 8px 16px;
                font-size: 0.9em;
            }
        }
    </style>
    <!-- External Libraries -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.13.5/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <!-- SweetAlert2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.3/dist/sweetalert2.min.css" rel="stylesheet">
</head>
<body class="light-mode">
    <!-- Dashboard Header -->
    <header class="dashboard-header">
        <h1>Longevacare Salary Management Dashboard</h1>
        <p>
            <a href="dashboard.php">Dashboard</a> |
            <a href="accountant_profile.php">Profile</a> |
            <a href="logout.php">Logout</a>
            <!-- Dark Mode Toggle -->
            <button class="btn-custom ms-3" id="toggleDarkMode" title="Toggle Dark Mode"><i class="fas fa-moon"></i></button>
        </p>
    </header>

    <!-- Main Container -->
    <div class="container my-4">
        <!-- Feedback Messages -->
        <?php if (!empty($success)): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?php echo sanitize_output($success); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <?php if (!empty($error)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?php echo sanitize_output($error); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <!-- Filters -->
        <div class="filters card">
            <form id="filterForm" method="GET" action="manage_salaries.php">
                <div class="row g-3">
                    <!-- Start Date Filter -->
                    <div class="col-md-4">
                        <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); ?>">
                    </div>
                    <!-- End Date Filter -->
                    <div class="col-md-4">
                        <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); ?>">
                    </div>
                    <!-- Status Filter -->
                    <div class="col-md-4">
                        <label for="status_filter" class="form-label">Status:</label>
                        <select id="status_filter" name="status_filter" class="form-select">
                            <option value="">All</option>
                            <?php foreach ($statusOptions as $status): ?>
                                <option value="<?php echo sanitize_output($status); ?>" <?php echo ($status_filter === $status) ? 'selected' : ''; ?>>
                                    <?php echo sanitize_output($status); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="row mt-3">
                    <div class="col-md-12 text-end">
                        <button type="submit" class="btn btn-custom">Apply Filters</button>
                        <a href="manage_salaries.php" class="btn btn-secondary">Reset Filters</a>
                    </div>
                </div>
            </form>
        </div>

        <!-- Action Buttons -->
        <div class="d-flex justify-content-between mb-3">
            <button type="button" class="btn btn-custom" data-bs-toggle="modal" data-bs-target="#addSalaryModal">
                <i class="fas fa-plus"></i> Add Salary
            </button>
            <!-- Export Buttons -->
            <div>
                <button id="export_csv" class="btn btn-secondary me-2"><i class="fas fa-file-csv"></i> Export CSV</button>
                <button id="export_pdf" class="btn btn-secondary"><i class="fas fa-file-pdf"></i> Export PDF</button>
            </div>
        </div>

        <!-- Salaries Table -->
        <div class="table-responsive">
            <table class="table table-striped table-hover" id="salariesTable">
                <thead>
                    <tr>
                        <th><input type="checkbox" id="select_all"></th>
                        <th>Salary ID</th>
                        <th>Employee Name</th>
                        <th>Basic Salary ($)</th>
                        <th>Bonuses ($)</th>
                        <th>Deductions ($)</th>
                        <th>Overtime (Hours)</th>
                        <th>Overtime Rate ($/hr)</th>
                        <th>Tax ($)</th>
                        <th>Net Salary ($)</th>
                        <th>Payment Date</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($salaries) > 0): ?>
                        <?php foreach ($salaries as $salary): ?>
                            <tr>
                                <td><input type="checkbox" class="salary_checkbox" value="<?php echo sanitize_output($salary['id']); ?>"></td>
                                <td><?php echo sanitize_output($salary['id']); ?></td>
                                <td><?php echo sanitize_output($salary['employee_name']); ?></td>
                                <td><?php echo number_format($salary['basic_salary'], 2); ?></td>
                                <td><?php echo number_format($salary['bonuses'], 2); ?></td>
                                <td><?php echo number_format($salary['deductions'], 2); ?></td>
                                <td><?php echo sanitize_output($salary['overtime_hours']); ?></td>
                                <td><?php echo number_format($salary['overtime_rate'], 2); ?></td>
                                <td><?php echo number_format($salary['tax'], 2); ?></td>
                                <td><?php echo number_format($salary['net_salary'], 2); ?></td>
                                <td><?php echo sanitize_output($salary['payment_date']); ?></td>
                                <td>
                                    <?php if ($salary['status'] === 'Paid'): ?>
                                        <span class="badge bg-success">Paid</span>
                                    <?php else: ?>
                                        <span class="badge bg-warning text-dark">Pending</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <a href="edit_salary.php?id=<?php echo urlencode($salary['id']); ?>" class="btn btn-sm btn-primary" title="Edit">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <button type="button" class="btn btn-sm btn-danger delete_salary_btn" data-id="<?php echo sanitize_output($salary['id']); ?>" title="Delete">
                                        <i class="fas fa-trash-alt"></i>
                                    </button>
                                    <?php if ($salary['status'] === 'Pending'): ?>
                                        <button type="button" class="btn btn-sm btn-success mark_paid_btn" data-id="<?php echo sanitize_output($salary['id']); ?>" title="Mark as Paid">
                                            <i class="fas fa-dollar-sign"></i>
                                        </button>
                                    <?php endif; ?>
                                    <a href="generate_payslip.php?id=<?php echo urlencode($salary['id']); ?>" class="btn btn-sm btn-info" title="Generate Payslip" target="_blank">
                                        <i class="fas fa-file-pdf"></i>
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="13" class="text-center">No salary records found.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <!-- Bulk Actions -->
        <div class="mb-4">
            <button id="bulk_delete" class="btn btn-danger me-2" disabled><i class="fas fa-trash-alt"></i> Delete Selected</button>
            <button id="bulk_mark_paid" class="btn btn-success" disabled><i class="fas fa-dollar-sign"></i> Mark Selected as Paid</button>
        </div>

        <!-- Add Salary Modal -->
        <div class="modal fade" id="addSalaryModal" tabindex="-1" aria-labelledby="addSalaryModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <form action="add_salary.php" method="POST" id="addSalaryForm">
                        <div class="modal-header">
                            <h5 class="modal-title" id="addSalaryModalLabel">Add New Salary</h5>
                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <!-- CSRF Token -->
                            <input type="hidden" name="csrf_token" value="<?php echo sanitize_output($_SESSION['csrf_token']); ?>">

                            <div class="row g-3">
                                <!-- Employee Selection -->
                                <div class="col-md-6">
                                    <label for="employee_id" class="form-label">Employee <span class="text-danger">*</span></label>
                                    <select class="form-select" id="employee_id" name="employee_id" required>
                                        <option value="" selected disabled>Select an employee</option>
                                        <?php foreach ($employees as $employee): ?>
                                            <option value="<?php echo sanitize_output($employee['id']); ?>">
                                                <?php echo sanitize_output($employee['name']); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <div class="invalid-feedback">
                                        Please select an employee.
                                    </div>
                                </div>
                                <!-- Payment Date -->
                                <div class="col-md-6">
                                    <label for="payment_date" class="form-label">Payment Date <span class="text-danger">*</span></label>
                                    <input type="date" class="form-control" id="payment_date" name="payment_date" required>
                                    <div class="invalid-feedback">
                                        Please select a payment date.
                                    </div>
                                </div>
                                <!-- Basic Salary -->
                                <div class="col-md-4">
                                    <label for="basic_salary" class="form-label">Basic Salary ($) <span class="text-danger">*</span></label>
                                    <input type="number" step="0.01" class="form-control" id="basic_salary" name="basic_salary" placeholder="Enter basic salary" required>
                                    <div class="invalid-feedback">
                                        Please enter a valid basic salary.
                                    </div>
                                </div>
                                <!-- Bonuses -->
                                <div class="col-md-4">
                                    <label for="bonuses" class="form-label">Bonuses ($)</label>
                                    <input type="number" step="0.01" class="form-control" id="bonuses" name="bonuses" placeholder="Enter bonuses" value="0">
                                </div>
                                <!-- Deductions -->
                                <div class="col-md-4">
                                    <label for="deductions" class="form-label">Deductions ($)</label>
                                    <input type="number" step="0.01" class="form-control" id="deductions" name="deductions" placeholder="Enter deductions" value="0">
                                </div>
                                <!-- Overtime Hours -->
                                <div class="col-md-4">
                                    <label for="overtime_hours" class="form-label">Overtime Hours</label>
                                    <input type="number" class="form-control" id="overtime_hours" name="overtime_hours" placeholder="Enter overtime hours" value="0">
                                </div>
                                <!-- Overtime Rate -->
                                <div class="col-md-4">
                                    <label for="overtime_rate" class="form-label">Overtime Rate ($/hr)</label>
                                    <input type="number" step="0.01" class="form-control" id="overtime_rate" name="overtime_rate" placeholder="Enter overtime rate" value="0">
                                </div>
                                <!-- Tax -->
                                <div class="col-md-4">
                                    <label for="tax" class="form-label">Tax ($) <span class="text-danger">*</span></label>
                                    <input type="number" step="0.01" class="form-control" id="tax" name="tax" placeholder="Enter tax deductions" value="0" required>
                                    <div class="invalid-feedback">
                                        Please enter a valid tax amount.
                                    </div>
                                </div>
                                <!-- Net Salary (Read-only) -->
                                <div class="col-md-6">
                                    <label for="net_salary" class="form-label">Net Salary ($)</label>
                                    <input type="text" class="form-control" id="net_salary" name="net_salary" readonly>
                                </div>
                                <!-- Notes -->
                                <div class="col-md-6">
                                    <label for="notes" class="form-label">Notes</label>
                                    <textarea class="form-control" id="notes" name="notes" rows="3" placeholder="Enter any additional notes"></textarea>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                            <button type="submit" name="add_salary" class="btn btn-custom">Add Salary</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Edit Salary Modal (Loaded via AJAX) -->
        <div class="modal fade" id="editSalaryModal" tabindex="-1" aria-labelledby="editSalaryModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <!-- Content will be loaded dynamically -->
                </div>
            </div>
        </div>
    </div>

    <!-- External Libraries -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.7/dist/umd/popper.min.js" integrity="sha384-..." crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.5/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.5/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/js/all.min.js"></script>
    <!-- SweetAlert2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.3/dist/sweetalert2.all.min.js"></script>
    <!-- jsPDF for PDF export -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.25/jspdf.plugin.autotable.min.js"></script>
    <!-- Custom Scripts -->
    <script>
        $(document).ready(function() {
            // Initialize DataTable
            var table = $('#salariesTable').DataTable({
                "order": [[ 9, "desc" ]], // Order by Payment Date descending
                "columnDefs": [
                    { "orderable": false, "targets": [0, 12] } // Disable ordering on checkbox and actions
                ],
                "pageLength": 10,
                "lengthMenu": [5, 10, 25, 50, 100],
                "language": {
                    "search": "Search Salaries:",
                    "lengthMenu": "Show _MENU_ entries",
                    "zeroRecords": "No matching records found",
                    "info": "Showing _START_ to _END_ of _TOTAL_ salaries",
                    "infoEmpty": "Showing 0 to 0 of 0 salaries",
                    "infoFiltered": "(filtered from _MAX_ total salaries)"
                }
            });

            // Handle Select All checkbox
            $('#select_all').on('click', function(){
                var rows = table.rows({ 'search': 'applied' }).nodes();
                $('input[type="checkbox"]', rows).prop('checked', this.checked);
                toggleBulkButtons();
            });

            // Handle individual checkbox click
            $('#salariesTable tbody').on('change', 'input.salary_checkbox', function(){
                if(!this.checked){
                    var el = $('#select_all').get(0);
                    if(el && el.checked && ('indeterminate' in el)){
                        el.indeterminate = true;
                    }
                }
                toggleBulkButtons();
            });

            // Toggle Bulk Action Buttons
            function toggleBulkButtons(){
                var selected = $('input.salary_checkbox:checked').length;
                if(selected > 0){
                    $('#bulk_delete, #bulk_mark_paid').prop('disabled', false);
                } else {
                    $('#bulk_delete, #bulk_mark_paid').prop('disabled', true);
                }
            }

            // Bulk Delete Salaries
            $('#bulk_delete').on('click', function(){
                var selected_ids = [];
                $('input.salary_checkbox:checked').each(function(){
                    selected_ids.push($(this).val());
                });

                Swal.fire({
                    title: 'Are you sure?',
                    text: `You are about to delete ${selected_ids.length} salary record(s). This action cannot be undone.`,
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#dc3545',
                    cancelButtonColor: '#6c757d',
                    confirmButtonText: 'Yes, delete them!'
                }).then((result) => {
                    if (result.isConfirmed) {
                        // Submit form via AJAX
                        $.ajax({
                            url: 'bulk_actions.php',
                            type: 'POST',
                            data: {
                                action: 'delete',
                                salary_ids: selected_ids,
                                csrf_token: '<?php echo sanitize_output($_SESSION['csrf_token']); ?>'
                            },
                            success: function(response){
                                var res = JSON.parse(response);
                                if(res.status === 'success'){
                                    Swal.fire(
                                        'Deleted!',
                                        res.message,
                                        'success'
                                    ).then(() => {
                                        location.reload();
                                    });
                                } else {
                                    Swal.fire(
                                        'Error!',
                                        res.message,
                                        'error'
                                    );
                                }
                            },
                            error: function(){
                                Swal.fire(
                                    'Error!',
                                    'An error occurred while processing your request.',
                                    'error'
                                );
                            }
                        });
                    }
                });
            });

            // Bulk Mark as Paid
            $('#bulk_mark_paid').on('click', function(){
                var selected_ids = [];
                $('input.salary_checkbox:checked').each(function(){
                    if($(this).closest('tr').find('span.badge').text() === 'Pending'){
                        selected_ids.push($(this).val());
                    }
                });

                if(selected_ids.length === 0){
                    Swal.fire(
                        'No Pending Salaries',
                        'Selected salaries are already marked as paid.',
                        'info'
                    );
                    return;
                }

                Swal.fire({
                    title: 'Mark as Paid?',
                    text: `You are about to mark ${selected_ids.length} salary record(s) as Paid.`,
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonColor: '#28a745',
                    cancelButtonColor: '#6c757d',
                    confirmButtonText: 'Yes, mark them!'
                }).then((result) => {
                    if (result.isConfirmed) {
                        // Submit form via AJAX
                        $.ajax({
                            url: 'bulk_actions.php',
                            type: 'POST',
                            data: {
                                action: 'mark_paid',
                                salary_ids: selected_ids,
                                csrf_token: '<?php echo sanitize_output($_SESSION['csrf_token']); ?>'
                            },
                            success: function(response){
                                var res = JSON.parse(response);
                                if(res.status === 'success'){
                                    Swal.fire(
                                        'Success!',
                                        res.message,
                                        'success'
                                    ).then(() => {
                                        location.reload();
                                    });
                                } else {
                                    Swal.fire(
                                        'Error!',
                                        res.message,
                                        'error'
                                    );
                                }
                            },
                            error: function(){
                                Swal.fire(
                                    'Error!',
                                    'An error occurred while processing your request.',
                                    'error'
                                );
                            }
                        });
                    }
                });
            });

            // Delete Salary (Single)
            $('.delete_salary_btn').on('click', function(){
                var salary_id = $(this).data('id');
                Swal.fire({
                    title: 'Are you sure?',
                    text: "You are about to delete this salary record.",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#dc3545',
                    cancelButtonColor: '#6c757d',
                    confirmButtonText: 'Yes, delete it!'
                }).then((result) => {
                    if (result.isConfirmed) {
                        // Submit delete via AJAX
                        $.ajax({
                            url: 'delete_salary.php',
                            type: 'POST',
                            data: {
                                salary_id: salary_id,
                                csrf_token: '<?php echo sanitize_output($_SESSION['csrf_token']); ?>'
                            },
                            success: function(response){
                                var res = JSON.parse(response);
                                if(res.status === 'success'){
                                    Swal.fire(
                                        'Deleted!',
                                        res.message,
                                        'success'
                                    ).then(() => {
                                        location.reload();
                                    });
                                } else {
                                    Swal.fire(
                                        'Error!',
                                        res.message,
                                        'error'
                                    );
                                }
                            },
                            error: function(){
                                Swal.fire(
                                    'Error!',
                                    'An error occurred while processing your request.',
                                    'error'
                                );
                            }
                        });
                    }
                });
            });

            // Mark as Paid (Single)
            $('.mark_paid_btn').on('click', function(){
                var salary_id = $(this).data('id');
                Swal.fire({
                    title: 'Mark as Paid?',
                    text: "You are about to mark this salary as Paid.",
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonColor: '#28a745',
                    cancelButtonColor: '#6c757d',
                    confirmButtonText: 'Yes, mark it!'
                }).then((result) => {
                    if (result.isConfirmed) {
                        // Submit mark as paid via AJAX
                        $.ajax({
                            url: 'mark_paid.php',
                            type: 'POST',
                            data: {
                                salary_id: salary_id,
                                csrf_token: '<?php echo sanitize_output($_SESSION['csrf_token']); ?>'
                            },
                            success: function(response){
                                var res = JSON.parse(response);
                                if(res.status === 'success'){
                                    Swal.fire(
                                        'Marked!',
                                        res.message,
                                        'success'
                                    ).then(() => {
                                        location.reload();
                                    });
                                } else {
                                    Swal.fire(
                                        'Error!',
                                        res.message,
                                        'error'
                                    );
                                }
                            },
                            error: function(){
                                Swal.fire(
                                    'Error!',
                                    'An error occurred while processing your request.',
                                    'error'
                                );
                            }
                        });
                    }
                });
            });

            // Calculate Net Salary on Input Change
            $('#addSalaryModal').on('input', '#basic_salary, #bonuses, #deductions, #overtime_hours, #overtime_rate, #tax', function(){
                var basic = parseFloat($('#basic_salary').val()) || 0;
                var bonuses = parseFloat($('#bonuses').val()) || 0;
                var deductions = parseFloat($('#deductions').val()) || 0;
                var overtime_hours = parseFloat($('#overtime_hours').val()) || 0;
                var overtime_rate = parseFloat($('#overtime_rate').val()) || 0;
                var tax = parseFloat($('#tax').val()) || 0;

                var net_salary = (basic + bonuses + (overtime_hours * overtime_rate)) - (deductions + tax);
                $('#net_salary').val(net_salary.toFixed(2));
            });

            // Export to CSV
            $('#export_csv').on('click', function(){
                var csv_data = [];
                var headers = [];
                $('#salariesTable thead tr th').each(function(index){
                    if(index !== 0 && index !== 12){ // Exclude checkbox and actions
                        headers.push('"' + $(this).text().trim().replace(/"/g, '""') + '"');
                    }
                });
                csv_data.push(headers.join(','));

                table.rows({ search: 'applied' }).every(function(){
                    var data = this.data();
                    var row = [];
                    for(var i = 1; i < data.length - 1; i++){ // Exclude checkbox and actions
                        // Remove HTML tags from data[i]
                        var temp = $('<div>').html(data[i]).text();
                        row.push('"' + temp.replace(/"/g, '""') + '"');
                    }
                    csv_data.push(row.join(','));
                });

                var csv_string = csv_data.join('\n');
                var a = document.createElement('a');
                a.href = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv_string);
                a.download = 'salaries.csv';
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            });

            // Export to PDF using jsPDF and AutoTable
            $('#export_pdf').on('click', function(){
                const { jsPDF } = window.jspdf;
                var doc = new jsPDF();
                doc.setFont("Poppins", "normal");
                doc.setFontSize(18);
                doc.text("Salaries Report", 14, 22);
                var columns = [];
                $('#salariesTable thead tr th').each(function(index){
                    if(index !== 0 && index !== 12){ // Exclude checkbox and actions
                        columns.push($(this).text().trim());
                    }
                });
                var rows = [];
                table.rows({ search: 'applied' }).every(function(){
                    var data = this.data();
                    var row = [];
                    for(var i = 1; i < data.length - 1; i++){ // Exclude checkbox and actions
                        // Remove HTML tags from data[i]
                        var temp = $('<div>').html(data[i]).text();
                        row.push(temp);
                    }
                    rows.push(row);
                });
                doc.autoTable({
                    head: [columns],
                    body: rows,
                    startY: 30,
                    styles: { font: "Poppins", fontSize: 10 },
                    theme: 'striped'
                });
                doc.save('salaries.pdf');
            });

            // Load Edit Salary Modal via AJAX
            $('#salariesTable').on('click', '.edit_salary_btn', function(){
                var salary_id = $(this).data('id');
                $.ajax({
                    url: 'edit_salary_form.php',
                    type: 'GET',
                    data: { id: salary_id },
                    success: function(response){
                        $('#editSalaryModal .modal-content').html(response);
                        $('#editSalaryModal').modal('show');
                    },
                    error: function(){
                        Swal.fire(
                            'Error!',
                            'Failed to load the edit form.',
                            'error'
                        );
                    }
                });
            });

            // Dark Mode Toggle
            document.getElementById('toggleDarkMode').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.innerHTML = '<i class="fas fa-sun"></i>';
                } else {
                    localStorage.setItem('theme', 'light');
                    this.innerHTML = '<i class="fas fa-moon"></i>';
                }
            });

            // Load theme preference on page load
            document.addEventListener('DOMContentLoaded', function() {
                const theme = localStorage.getItem('theme');
                if(theme === 'dark') {
                    document.body.classList.add('dark-mode');
                    document.getElementById('toggleDarkMode').innerHTML = '<i class="fas fa-sun"></i>';
                }
            });

            // Form Validation for Add Salary
            (function () {
                'use strict'

                var forms = document.querySelectorAll('#addSalaryForm')

                Array.prototype.slice.call(forms)
                    .forEach(function (form) {
                        form.addEventListener('submit', function (event) {
                            if (!form.checkValidity()) {
                                event.preventDefault()
                                event.stopPropagation()
                            }

                            form.classList.add('was-validated')
                        }, false)
                    })
            })()
        </script>
</body>
</html>) make it cool and add more feauters and remove toggle dark mode and add button (add_salary.php) and this info database (===Database u406552082_info

== Table structure for table admins

|------
|Column|Type|Null|Default
|------
|//**id**//|int(11)|No|
|**username**|varchar(50)|No|
|password|varchar(255)|No|
|email|varchar(100)|No|
== Dumping data for table admins

|1|mmtawfik|$2y$10$V9jnPR/dZN0uoiHPQa038uBXCS1NC7xV.uVJxnlE6lmICqAwpSr1O|mmtawfik@example.com
|<PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>
== Table structure for table budgets

|------
|Column|Type|Null|Default
|------
|//**id**//|int(11)|No|
|month|varchar(7)|Yes|NULL
|budgeted_revenue|decimal(10,2)|Yes|NULL
|budgeted_expenses|decimal(10,2)|Yes|NULL
|notes|text|Yes|NULL
== Dumping data for table budgets

|1|2024-09|20000.00|1000.00| 
== Table structure for table comments

|------
|Column|Type|Null|Default
|------
|//**id**//|int(11)|No|
|patient_id|int(11)|No|
|sender|enum('patient', 'doctor', 'admin')|No|
|message|text|No|
|timestamp|datetime|Yes|current_timestamp()
|parent_id|int(11)|Yes|NULL
== Dumping data for table comments

|44|16|patient|Good|2024-10-03 03:28:46|NULL
|45|16|admin|Thanks|2024-10-03 03:29:02|44
== Table structure for table doctors

|------
|Column|Type|Null|Default
|------
|//**id**//|int(11)|No|
|employee_id|int(11)|No|
|name|varchar(255)|No|
|**username**|varchar(100)|No|
|password|varchar(255)|No|
|**email**|varchar(255)|No|
|specialization|varchar(255)|Yes|NULL
|phone|varchar(20)|Yes|NULL
|registration_date|date|Yes|curdate()
|profile_picture|varchar(255)|Yes|NULL
|department|varchar(100)|Yes|NULL
|date_of_joining|date|Yes|NULL
|status|enum('active', 'inactive')|Yes|active
== Dumping data for table doctors

|12|18|Dr. Engy Shahbander|drengy|$2y$10$Tx74blqFrEdOB2tOZy/Qye7ndsmS9aBMUo23mOG0a9zgfHPoNBnI2|engy.shahbander@gmail.com|CEO - Longevacare|0151315489|2024-10-03|NULL|NULL|NULL|active
== Table structure for table doctor_patient

|------
|Column|Type|Null|Default
|------
|//**id**//|int(11)|No|
|**doctor_id**|int(11)|No|
|**patient_id**|int(11)|No|
== Dumping data for table doctor_patient

|14|3|13
|31|12|13
|30|12|16
== Table structure for table employees

|------
|Column|Type|Null|Default
|------
|//**id**//|int(11)|No|
|name|varchar(255)|No|
|role|enum('admin', 'doctor', 'staff', 'accountant')|No|
|**email**|varchar(255)|No|
|phone|varchar(20)|Yes|NULL
|department|varchar(100)|Yes|NULL
|date_of_joining|date|Yes|NULL
|status|enum('active', 'inactive')|Yes|active
|**username**|varchar(100)|No|
|password|varchar(255)|No|
|created_at|timestamp|Yes|current_timestamp()
|updated_at|timestamp|Yes|current_timestamp()
|profile_picture|varchar(255)|Yes|NULL
|specialization|varchar(255)|Yes|NULL
== Dumping data for table employees

|<PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>|0105131548|Nursing|2024-10-15|active|doaa123|$2y$10$jezEFBAuvB.2J56DTgGeZ.PbpKBaHGZARBNjy5mvnR21lImE9aala|2024-10-03 01:38:20|2024-10-03 01:38:20|doaa123_1727919500.jpg|Nurse
|18|Dr. Engy <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>|0151315489|Administration|2024-10-03|active|drengy|$2y$10$Tx74blqFrEdOB2tOZy/Qye7ndsmS9aBMUo23mOG0a9zgfHPoNBnI2|2024-10-03 01:51:32|2024-10-03 03:34:49|drengy_18.jpg|CEO - Longevacare
|19|Mahmoud <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>|01119235049|Administration|2024-10-03|active|mahmoudtawfik|$2y$10$qciyhqx0IHsZMviAa9YceOuw8JZ2RaK2CR2b2Ny.nOT1bogVRSKoy|2024-10-03 01:54:51|2024-10-03 03:35:14|mahmoudtawfik_19.png|Developer
|20|Mohamed <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>|0105134856|Accounting|2024-10-01|active|mohamed_5049|$2y$10$/RZk3a7dRiM4zSssCWK8ae7QidsQooQ5Y0U6k9KrE7d5XwN5h5IUC|2024-10-03 04:15:27|2024-10-03 04:15:40|default_profile.png|Accountant
== Table structure for table health_records

|------
|Column|Type|Null|Default
|------
|//**id**//|int(11)|No|
|patient_id|int(11)|No|
|blood_pressure|varchar(20)|Yes|NULL
|weight|decimal(5,2)|Yes|NULL
|bmi|decimal(4,2)|Yes|NULL
|cholesterol|decimal(5,2)|Yes|NULL
|prescription|text|Yes|NULL
|treatment_progress|text|Yes|NULL
|record_date|date|No|
== Dumping data for table health_records

|36|12|80|80.00|80.00|5.00|STR - 32|Isn't good for this patient|2024-10-02
|37|16|80|80.00|99.99|169.00|This new precept|Hi|2024-10-03
== Table structure for table insurance_claims

|------
|Column|Type|Null|Default
|------
|//**id**//|int(11)|No|
|patient_id|int(11)|Yes|NULL
|invoice_id|int(11)|Yes|NULL
|claim_amount|decimal(10,2)|Yes|NULL
|status|enum('Pending', 'Approved', 'Rejected')|Yes|NULL
|submission_date|date|Yes|NULL
|processing_date|date|Yes|NULL
|notes|text|Yes|NULL
== Dumping data for table insurance_claims

|1|16|31|1000.00|Rejected|2024-10-05|2024-10-05| 
== Table structure for table invoices

|------
|Column|Type|Null|Default
|------
|//**id**//|int(11)|No|
|patient_id|int(11)|No|
|service_name|varchar(255)|No|
|service_description|text|Yes|NULL
|cost|decimal(10,2)|No|
|tax_rate|decimal(5,2)|Yes|0.00
|discount|decimal(5,2)|Yes|0.00
|total_amount|decimal(10,2)|No|
|invoice_date|date|Yes|curdate()
|notes|text|Yes|NULL
|tax|decimal(5,2)|Yes|0.00
== Dumping data for table invoices

|19|13| |NULL|0.00|0.00|300.00|1284.00|2024-09-29| |7.00
|28|15| |NULL|0.00|0.00|150.00|720.00|2024-09-30| |20.00
|31|16| | |750.00|5.00|100.00|650.00|2024-10-03| |0.00
== Table structure for table invoice_services

|------
|Column|Type|Null|Default
|------
|//**id**//|int(11)|No|
|invoice_id|int(11)|No|
|service_id|int(11)|No|
|service_name|varchar(255)|No|
|cost|decimal(10,2)|No|
== Dumping data for table invoice_services

|13|19|10|Stress|750.00
|14|19|9|Depression|750.00
|36|28|10|Stress|750.00
|39|31|9|Depression|750.00
== Table structure for table patients

|------
|Column|Type|Null|Default
|------
|//**id**//|int(11)|No|
|name|varchar(100)|No|
|age|int(11)|No|
|gender|enum('Male', 'Female', 'Other')|No|
|phone|varchar(20)|Yes|NULL
|email|varchar(100)|Yes|NULL
|medical_history|text|Yes|NULL
|created_at|timestamp|Yes|current_timestamp()
|updated_at|timestamp|Yes|current_timestamp()
|date_of_birth|date|Yes|NULL
|registration_datetime|datetime|Yes|current_timestamp()
|registration_date|date|Yes|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')|Yes|Initial Consultation
|doctor_id|int(11)|Yes|NULL
== Dumping data for table patients

|<PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>|DEP - XRA 12Mg|2024-09-28 23:15:43|2024-09-29 02:53:36|1999-09-28|2024-09-28 23:15:43|2024-09-28|Discontinued|NULL
|<PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>|Sr - Dep - 323Mg/d|2024-09-28 23:17:04|2024-09-29 02:53:27|1963-09-28|2024-09-28 23:17:04|2024-09-28|Awaiting Test Results|NULL
|13|Ahmed <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>|Has Bad Medical History|2024-09-29 01:14:56|2024-09-29 21:59:09|1988-09-29|2024-09-29 01:14:56|2024-09-29|Relapsed|NULL
|15|Ali <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>|.|2024-09-29 23:23:06|2024-09-29 23:24:12|1998-09-29|2024-09-29 23:23:06|2024-09-29|Paused|NULL
|16|Soha <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>|Doesn't have Medical History 1|2024-10-03 02:28:58|2024-10-03 02:29:52|2001-10-03|2024-10-03 02:28:58|2024-10-03|Paused|NULL
== Table structure for table patient_logins

|------
|Column|Type|Null|Default
|------
|//**id**//|int(11)|No|
|**patient_id**|int(11)|No|
|**username**|varchar(50)|No|
|password|varchar(255)|No|
== Dumping data for table patient_logins

|24|11|mahmoud_507|$2y$10$aWr138nBYi1CPnOp6Zd2geqUfpAO6zhAGWh0EUtiEMNcUIEIBw4RS
|25|12|mona_630|$2y$10$YMU9RdPOpW1MIELx8W6NBel0fl7NmzGl3GiRitSCQadQYx8Ux4U8e
|26|13|ahmed_697|$2y$10$PVsNfLKdc5gVD0TxjIil8u968rEq3ixyeOKImGLJZXvT8jiOjHNwa
|28|15|ali_127|$2y$10$sNDe.Ka5.Ne9z409SKVew.Diqw6P5cFurRyU1P1pBrTZRV6.LeJFy
|29|16|soha_554|$2y$10$dZEFXbXdX8oe2CWRBFxcOek1DD7O4iiOuvxB3A3cMgdKu7GutJ39K
== Table structure for table payments

|------
|Column|Type|Null|Default
|------
|//**id**//|int(11)|No|
|patient_id|int(11)|No|
|invoice_id|int(11)|No|
|amount_paid|decimal(10,2)|No|
|payment_date|date|No|
|payment_method|varchar(50)|Yes|NULL
|notes|text|Yes|NULL
== Dumping data for table payments

== Table structure for table salaries

|------
|Column|Type|Null|Default
|------
|//**id**//|int(11)|No|
|employee_id|int(11)|No|
|basic_salary|decimal(10,2)|No|
|bonuses|decimal(10,2)|Yes|0.00
|deductions|decimal(10,2)|Yes|0.00
|overtime_hours|int(11)|Yes|0
|overtime_rate|decimal(10,2)|Yes|0.00
|tax|decimal(10,2)|Yes|0.00
|payment_date|date|No|
|net_salary|decimal(10,2)|No|
|status|enum('Pending', 'Paid')|Yes|Pending
|notes|text|Yes|NULL
|payslip_path|varchar(255)|Yes|NULL
== Dumping data for table salaries

== Table structure for table services

|------
|Column|Type|Null|Default
|------
|//**service_id**//|int(11)|No|
|service_name|varchar(255)|No|
|service_price|decimal(10,2)|No|
|service_description|text|Yes|NULL
|created_at|timestamp|Yes|current_timestamp()
|updated_at|timestamp|Yes|current_timestamp()
== Dumping data for table services

|9|Depression|750.00|New Service Depression - longevacare|2024-09-28 23:19:56|2024-09-28 23:19:56
|10|Stress|750.00|New Service Stress - Longevacare|2024-09-29 10:24:07|2024-09-29 10:24:07) and type full codes