Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

ok, i want to use this styles ( <style> /* Import Google Fonts / @import…

  1. User

    ok, i want to use this styles ( /* 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);
        }
    
        /* Header */
        .dashboard-header {
            background-color: var(--primary-color);
            color: #fff;
            padding: 30px;
            text-align: center;
            border-radius: 0 0 25px 25px;
            margin-bottom: 40px;
        }
    
        .dashboard-header h1 {
            font-weight: 700;
        }
    
        .dashboard-header p a {
            color: #fff;
            margin: 0 10px;
        }
    
        .dashboard-header p a:hover {
            text-decoration: underline;
        }
    
        /* 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: 2em;
            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: 15px;
            border-radius: 10px;
            transition: all 0.3s ease;
        }
    
        .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;
        }
    
        /* Charts */
        .chart-container {
            position: relative;
            height: 400px;
        }
    
        /* Responsive Adjustments */
        @media (max-width: 768px) {
            .dashboard-header h1 {
                font-size: 24px;
            }
    
            .btn-custom {
                margin-bottom: 15px;
            }
        }
    
        @media (max-width: 576px) {
            .dashboard-header h1 {
                font-size: 20px;
            }
    
            .card .card-body {
                padding: 20px;
            }
    
            .card .card-text {
                font-size: 1.5em;
            }
    
            .filters {
                padding: 20px;
            }
        }
    
        /* 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;
        }
    </style>
    

    )for manage_salaries.php (<?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(success = isset(_SESSION['success']) ? SESSION[′success′]:′′;_SESSION['success'] : ''; error = isset(SESSION[′error′])?_SESSION['error']) ? _SESSION['error'] : ''; unset(SESSION[′success′],_SESSION['success'], _SESSION['error']);

    // Fetch all salaries with employee details try { stmt=stmt = pdo->prepare(" SELECT salaries.*, employees.name AS employee_name FROM salaries JOIN employees ON salaries.employee_id = employees.id ORDER BY payment_date DESC "); stmt−>execute();stmt->execute(); 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=empStmt = pdo->prepare("SELECT id, name FROM employees WHERE status = 'active' ORDER BY name ASC"); empStmt−>execute();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."); }

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

    <!-- 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="card mb-4">
            <div class="card-body">
                <form id="filterForm" class="row g-3">
                    <!-- Date Range 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($_GET['start_date'] ?? ''); ?>">
                    </div>
                    <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($_GET['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 (isset($_GET['status_filter']) && $_GET['status_filter'] === $status) ? 'selected' : ''; ?>>
                                    <?php echo sanitize_output($status); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </form>
            </div>
        </div>
    
        <!-- Add Salary Button -->
        <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">
                        <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>
    
        <!-- Bootstrap JS, DataTables JS, Font Awesome, SweetAlert2 JS, jsPDF, and Custom JS -->
        <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>
        <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 src="../assets/js/scripts.js"></script>
        <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'
                                        );
                                    }
                                }
                            });
                        }
                    });
                });
    
                // 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'
                                        );
                                    }
                                }
                            });
                        }
                    });
                });
    
                // 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'
                                        );
                                    }
                                }
                            });
                        }
                    });
                });
    
                // 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'
                                        );
                                    }
                                }
                            });
                        }
                    });
                });
    
                // 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(){
                        headers.push($(this).text().trim());
                    });
                    csv_data.push(headers.join(','));
    
                    table.rows({ search: 'applied' }).every(function(){
                        var data = this.data();
                        var row = [];
                        for(var i=0; i< data.length; i++){
                            row.push('"' + data[i].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(){
                    var { jsPDF } = window.jspdf;
                    var doc = new jsPDF();
                    doc.text("Salaries Report", 14, 16);
                    var columns = [];
                    $('#salariesTable thead tr th').each(function(){
                        columns.push($(this).text().trim());
                    });
                    var rows = [];
                    table.rows({ search: 'applied' }).every(function(){
                        var data = this.data();
                        var row = data.map(item => item.toString());
                        rows.push(row);
                    });
                    doc.autoTable({
                        head: [columns],
                        body: rows,
                        startY: 20,
                        styles: { font: "Poppins" }
                    });
                    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');
                        }
                    });
                });
            });
    
            // 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>';
                }
            });
        </script>
    </body>
    

    session_start(); require_once '../db_connect.php'; require_once '../assets/libraries/tcpdf/tcpdf.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(); }

    // Check if salary ID is provided if (!isset(_GET['id'])) { _SESSION['error'] = "No salary record selected."; header("Location: manage_salaries.php"); exit(); }

    salaryid=(int)salary_id = (int)_GET['id'];

    if (salary_id <= 0) { _SESSION['error'] = "Invalid Salary ID."; header("Location: manage_salaries.php"); exit(); }

    try { // Fetch the salary record along with employee details stmt=stmt = pdo->prepare(" SELECT salaries.*, employees.name, employees.role, employees.email, employees.department FROM salaries JOIN employees ON salaries.employee_id = employees.id WHERE salaries.id = :id "); stmt−>execute([′:id′=>stmt->execute([':id' => salary_id]); salary=salary = stmt->fetch();

    if (!$salary) {
        $_SESSION['error'] = "Salary record not found.";
        header("Location: manage_salaries.php");
        exit();
    }
    
    // Initialize TCPDF
    $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
    
    // Set Document Information
    $pdf->SetCreator('Salary Management System');
    $pdf->SetAuthor('Your Company Name');
    $pdf->SetTitle('Salary Payslip');
    $pdf->SetSubject('Payslip for ' . $salary['name']);
    
    // Remove default header/footer
    $pdf->setPrintHeader(false);
    $pdf->setPrintFooter(false);
    
    // Set margins
    $pdf->SetMargins(15, 15, 15, true);
    
    // Add a page
    $pdf->AddPage();
    
    // Styles
    $style = '<style>
                body { font-family: DejaVu Sans, sans-serif; }
                .header { text-align: center; }
                .header h2 { margin-bottom: -10px; }
                .header p { margin-top: 0; }
                table { width: 100%; border-collapse: collapse; margin-top: 20px; }
                table, th, td { border: 1px solid #000; }
                th, td { padding: 8px 12px; }
                .total { font-weight: bold; }
                .notes { margin-top: 20px; }
              </style>';
    
    // Header Content
    $header = '
        <div class="header">
            <h2>Your Company Name</h2>
            <p>1234 Street Address, City, Country</p>
            <h4>Payslip</h4>
        </div>';
    
    // Employee and Salary Details
    $details = '
        <table>
            <tr>
                <td><strong>Employee Name:</strong> ' . sanitize_output($salary['name']) . '</td>
                <td><strong>Role:</strong> ' . sanitize_output($salary['role']) . '</td>
            </tr>
            <tr>
                <td><strong>Department:</strong> ' . sanitize_output($salary['department']) . '</td>
                <td><strong>Email:</strong> ' . sanitize_output($salary['email']) . '</td>
            </tr>
            <tr>
                <td><strong>Payment Date:</strong> ' . sanitize_output($salary['payment_date']) . '</td>
                <td><strong>Status:</strong> ' . sanitize_output($salary['status']) . '</td>
            </tr>
        </table>';
    
    // Salary Breakdown
    $breakdown = '
        <table>
            <thead>
                <tr>
                    <th>Description</th>
                    <th>Amount ($)</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Basic Salary</td>
                    <td>' . number_format($salary['basic_salary'], 2) . '</td>
                </tr>
                <tr>
                    <td>Bonuses</td>
                    <td>' . number_format($salary['bonuses'], 2) . '</td>
                </tr>
                <tr>
                    <td>Overtime (' . $salary['overtime_hours'] . ' hrs)</td>
                    <td>' . number_format($salary['overtime_hours'] * $salary['overtime_rate'], 2) . '</td>
                </tr>
                <tr>
                    <td>Deductions</td>
                    <td>' . number_format($salary['deductions'], 2) . '</td>
                </tr>
                <tr>
                    <td>Tax</td>
                    <td>' . number_format($salary['tax'], 2) . '</td>
                </tr>
                <tr class="total">
                    <td>Net Salary</td>
                    <td>' . number_format($salary['net_salary'], 2) . '</td>
                </tr>
            </tbody>
        </table>';
    
    // Notes
    $notes = '
        <div class="notes">
            <strong>Notes:</strong>
            <p>' . nl2br(sanitize_output($salary['notes'])) . '</p>
        </div>';
    
    // Assemble the PDF content
    $html = $style . $header . $details . $breakdown . $notes;
    
    // Output the HTML content
    $pdf->writeHTML($html, true, false, true, false, '');
    
    // Define the file name
    $pdf_file = '../accountant/upload/payslips/payslip_' . $salary['id'] . '.pdf';
    
    // Create directory if not exists
    if (!is_dir('../accountant/upload/payslips/')) {
        mkdir('../accountant/upload/payslips/', 0777, true);
    }
    
    // Save the PDF to the server
    $pdf->Output($pdf_file, 'F');
    
    // Update the payslip_path in the database
    $updateStmt = $pdo->prepare("UPDATE salaries SET payslip_path = :path WHERE id = :id");
    $updateStmt->execute([
        ':path' => $pdf_file,
        ':id' => $salary_id,
    ]);
    
    // Force download the PDF
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="payslip_' . $salary['id'] . '.pdf"');
    readfile($pdf_file);
    exit();
    

    } else { // Invalid request $_SESSION['error'] = "Invalid request."; header("Location: manage_salaries.php"); exit(); } ?>) and type full codes and this info database (Updated Database Structure The database for the admin dashboard and patient management system consists of the following tables: a. Patients id (INT, AUTO_INCREMENT, PRIMARY KEY): Unique identifier for each patient. name (VARCHAR): Full name of the patient. age (INT): Age of the patient. gender (ENUM('Male', 'Female', 'Other')): Gender of the patient. phone (VARCHAR): Phone number of the patient. email (VARCHAR): Email address of the patient. medical_history (TEXT): Medical history of the patient. date_of_birth (DATE): Date of birth of the patient. registration_date (DATE): Date when the patient was registered. registration_datetime (DATETIME): Date and time when the patient was registered. status (ENUM): Current status of the patient (e.g., 'Initial Consultation', 'Treatment in Progress'). b. Health Records id (INT, AUTO_INCREMENT, PRIMARY KEY): Unique identifier for each health record. patient_id (INT, FOREIGN KEY REFERENCES patients(id)): ID of the patient associated with this health record. blood_pressure (VARCHAR): Blood pressure reading. weight (DECIMAL): Weight of the patient. bmi (DECIMAL): Body Mass Index of the patient. cholesterol (DECIMAL): Cholesterol level of the patient. prescription (TEXT): Prescriptions given to the patient. treatment_progress (TEXT): Notes on the treatment progress. record_date (DATE): Date of the health record. c. Admins id (INT, AUTO_INCREMENT, PRIMARY KEY): Unique identifier for each admin. username (VARCHAR): Admin's username. password (VARCHAR): Hashed password for the admin. email (VARCHAR): Email address of the admin. d. Patient Logins id (INT, AUTO_INCREMENT, PRIMARY KEY): Unique identifier for each patient login. patient_id (INT, FOREIGN KEY REFERENCES patients(id)): ID of the patient associated with this login. username (VARCHAR): Username for patient login. password (VARCHAR): Hashed password for patient login. e. Invoices id (INT, AUTO_INCREMENT, PRIMARY KEY): Unique identifier for each invoice. patient_id (INT NOT NULL, FOREIGN KEY REFERENCES patients(id)): ID of the patient associated with this invoice. service_name (VARCHAR(255) NOT NULL): Name of the service rendered. service_description (TEXT): Description of the service. cost (DECIMAL(10, 2) NOT NULL): Cost of the service. tax_rate (DECIMAL(5, 2) DEFAULT 0): Tax rate applied to the service. discount (DECIMAL(5, 2) DEFAULT 0): Discount applied to the service. total_amount (DECIMAL(10, 2) NOT NULL): Total amount due after tax and discount. invoice_date (DATE DEFAULT CURRENT_DATE): Date of the invoice. notes (TEXT): Additional notes for the invoice. f. Services service_id (INT, AUTO_INCREMENT, PRIMARY KEY): Unique identifier for each service. service_name (VARCHAR(255) NOT NULL): Name of the service. service_price (DECIMAL(10, 2) NOT NULL): Price of the service. service_description (TEXT): Description of the service. created_at (TIMESTAMP DEFAULT CURRENT_TIMESTAMP): Timestamp when the service was created. updated_at (TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP): Timestamp when the service was last updated. g. Invoice Services id (INT, AUTO_INCREMENT, PRIMARY KEY): Unique identifier for each entry in the invoice services table. invoice_id (INT NOT NULL, FOREIGN KEY REFERENCES invoices(id)): ID of the associated invoice. service_id (INT NOT NULL, FOREIGN KEY REFERENCES services(service_id)): ID of the associated service. service_name (VARCHAR(255) NOT NULL): Name of the service rendered. cost (DECIMAL(10, 2) NOT NULL): Cost of the service rendered. h. Comments id (INT, AUTO_INCREMENT, PRIMARY KEY): Unique identifier for each comment. patient_id (INT NOT NULL, FOREIGN KEY REFERENCES patients(id)): ID of the patient associated with the comment. sender (ENUM('patient', 'doctor', 'admin') NOT NULL): Sender of the comment, which can be 'patient', 'doctor', or 'admin'. message (TEXT NOT NULL): The message or comment content. timestamp (DATETIME DEFAULT CURRENT_TIMESTAMP): Date and time the comment was made. parent_id (INT NULL DEFAULT NULL): ID of the parent comment (for threaded conversations), if applicable. i. Doctor-Patient id (INT, AUTO_INCREMENT, PRIMARY KEY): Unique identifier for each doctor-patient relationship. doctor_id (INT NOT NULL, FOREIGN KEY REFERENCES doctors(id)): ID of the associated doctor. patient_id (INT NOT NULL, FOREIGN KEY REFERENCES patients(id)): ID of the associated patient. UNIQUE (doctor_id, patient_id): Ensures a unique doctor-patient pair. j. Employees id (INT, AUTO_INCREMENT, PRIMARY KEY): Unique identifier for each employee. name (VARCHAR(255) NOT NULL): Full name of the employee. role (ENUM('admin', 'doctor', 'staff') NOT NULL): Role of the employee, which can be 'admin', 'doctor', or 'staff'. email (VARCHAR(255) NOT NULL UNIQUE): Email address of the employee, ensuring it is unique. phone (VARCHAR(20)): Phone number of the employee. department (VARCHAR(100)): Department where the employee works. date_of_joining (DATE): The date when the employee joined the organization. status (ENUM('active', 'inactive') DEFAULT 'active'): Employment status, either 'active' or 'inactive', with 'active' as the default. username (VARCHAR(100) NOT NULL UNIQUE): Username for employee login, ensuring it is unique. password (VARCHAR(255) NOT NULL): Hashed password for the employee. created_at (TIMESTAMP DEFAULT CURRENT_TIMESTAMP): Timestamp when the employee record was created. updated_at (TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP): Timestamp when the employee record was last updated. profile_picture (VARCHAR(255) DEFAULT 'default_profile.png'): Profile picture of the employee. specialization (VARCHAR(255) DEFAULT NULL): Specialization of the employee. k. Doctors id (INT, AUTO_INCREMENT, PRIMARY KEY): Unique identifier for each doctor. employee_id (INT NOT NULL, FOREIGN KEY REFERENCES employees(id)): ID of the associated employee record. department (VARCHAR(100) DEFAULT NULL): Department where the doctor works. date_of_joining (DATE DEFAULT NULL): The date when the doctor joined the organization. status (ENUM('active', 'inactive') DEFAULT 'active'): Employment status of the doctor. profile_picture (VARCHAR(255) DEFAULT 'default_profile.png'): Profile picture of the doctor. l. Payments id (INT AUTO_INCREMENT, PRIMARY KEY): Unique identifier for each payment. patient_id (INT NOT NULL, FOREIGN KEY REFERENCES patients(id)): ID of the patient associated with this payment. invoice_id (INT NOT NULL, FOREIGN KEY REFERENCES invoices(id)): ID of the invoice associated with this payment. amount_paid (DECIMAL(10,2) NOT NULL): Amount paid by the patient. payment_date (DATE NOT NULL): Date of the payment. payment_method (VARCHAR(50)): Method of payment (e.g., cash, card, insurance). notes (TEXT): Additional notes regarding the payment. m. Salaries id (INT AUTO_INCREMENT, PRIMARY KEY): Unique identifier for each salary record. employee_id (INT NOT NULL, FOREIGN KEY REFERENCES employees(id)): ID of the employee receiving the salary. basic_salary (DECIMAL(10,2) NOT NULL): Basic salary of the employee. bonuses (DECIMAL(10,2) DEFAULT 0): Bonuses added to the salary. deductions (DECIMAL(10,2) DEFAULT 0): Deductions from the salary. overtime_hours (INT DEFAULT 0): Number of overtime hours worked by the employee. overtime_rate (DECIMAL(10,2) DEFAULT 0): Rate per overtime hour. tax (DECIMAL(10,2) DEFAULT 0): Tax applied to the salary. payment_date (DATE NOT NULL): Date of the salary payment. net_salary (DECIMAL(10,2) NOT NULL): Net salary after adjustments. status (ENUM('Pending', 'Paid') DEFAULT 'Pending'): Status of the salary payment. notes (TEXT): Additional notes for the salary record.

    SQL Updates for Doctors Table The SQL statement ALTER TABLE doctors ADD COLUMN date_of_joining DATE DEFAULT NULL; adds a date_of_joining column to the doctors table, allowing the storage of the date when a doctor joined the organization. The SQL statement ALTER TABLE doctors ADD COLUMN department VARCHAR(100) DEFAULT NULL; adds a department column to the doctors table, enabling the specification of the department where the doctor works. )

  2. Assistant

    Certainly! Below, you'll find the complete updated code for manage_salaries.php and generate_payslip.php, incorporating your provided CSS styles for a modern and "cool" design. Additionally, I've ensured that deleting a payment refreshes the page gracefully with a smooth user experience using SweetAlert2. I'll also provide auxiliary PHP scripts necessary for handling deletion, marking salaries as paid, and bulk actions to ensure the entire functionality works seamlessly.


    1. Updated manage_salaries.php

    This updated version integrates your custom CSS styles, refines the design for a modern look, and ensures that when a salary record is deleted or updated, the page refreshes smoothly with appropriate feedback.

    File Structure:

    accountant/
    │
    ├── manage_salaries.php
    ├── add_salary.php
    ├── edit_salary.php
    ├── delete_salary.php
    ├── mark_paid.php
    ├── bulk_actions.php
    ├── generate_payslip.php
    │
    ├── db_connect.php
    ├── auth/
    │   ├── login.php
    │   └── logout.php
    │
    ├── assets/
    │   ├── css/
    │   │   └── styles.css
    │   └── js/
    │       └── scripts.js
    │
    └── logs/
        └── error.log
    

    manage_salaries.php

    <?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 all salaries with employee details
    try {
        $stmt = $pdo->prepare("
            SELECT salaries.*, employees.name AS employee_name
            FROM salaries
            JOIN employees ON salaries.employee_id = employees.id
            ORDER BY payment_date DESC
        ");
        $stmt->execute();
        $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.");
    }
    
    // Fetch all statuses for filtering
    $statusOptions = ['Pending', 'Paid'];
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Manage Salaries</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: 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 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;
            }
    
            .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;
            }
    
            /* 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;
                }
            }
    
            @media (max-width: 576px) {
                .dashboard-header h1 {
                    font-size: 1.5em;
                }
    
                .card .card-body {
                    padding: 20px;
                }
    
                .filters {
                    padding: 20px;
                }
            }
    
            /* 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 Toggle Button */
            #toggleDarkMode {
                background-color: transparent;
                border: none;
                color: #fff;
                font-size: 1.2em;
            }
    
            #toggleDarkMode:focus {
                outline: none;
            }
        </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>Salary Management Dashboard</h1>
            <p>
                <a href="manage_salaries.php">Manage Salaries</a>
                <a href="../auth/logout.php">Logout</a>
                <!-- Dark Mode Toggle -->
                <button class="btn" 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" class="row g-3">
                    <!-- Date Range Filter -->
                    <div class="col-md-3">
                        <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($_GET['start_date'] ?? ''); ?>">
                    </div>
                    <div class="col-md-3">
                        <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($_GET['end_date'] ?? ''); ?>">
                    </div>
                    <!-- Status Filter -->
                    <div class="col-md-3">
                        <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 (isset($_GET['status_filter']) && $_GET['status_filter'] === $status) ? 'selected' : ''; ?>>
                                    <?php echo sanitize_output($status); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <!-- Filter Button -->
                    <div class="col-md-3 d-flex align-items-end">
                        <button type="submit" class="btn btn-custom">Apply Filters</button>
                    </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(){
                        headers.push('"' + $(this).text().trim().replace(/"/g, '""') + '"');
                    });
                    csv_data.push(headers.join(','));
    
                    table.rows({ search: 'applied' }).every(function(){
                        var data = this.data();
                        var row = [];
                        // Exclude the first checkbox and last actions columns
                        for(var i = 1; i < data.length - 1; i++){
                            // 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");
                    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" },
                        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>
    

    Explanation of Key Enhancements:

    1. Custom CSS Integration:

      • The provided <style> block has been integrated directly into the <head> section of manage_salaries.php. This ensures that all styles are applied correctly without relying on external CSS files.
      • Variables (:root) are used for colors and fonts, making it easier to manage and maintain the design.
    2. Dark Mode Functionality:

      • A toggle button is provided in the header allowing users to switch between light and dark modes.
      • The user's preference is stored in localStorage to persist the theme across sessions.
    3. Responsive Design:

      • Media queries ensure that the dashboard is responsive and looks good on various screen sizes.
    4. Enhanced DataTables Integration:

      • DataTables are styled to match the custom CSS, with alternating row colors and headers matching the primary color.
    5. User Feedback:

      • SweetAlert2 is used extensively for confirmation dialogs and feedback messages, enhancing user interaction and experience.
    6. Form Validation:

      • Bootstrap's built-in form validation has been utilized to ensure that all required fields are filled out correctly when adding a new salary.
    7. Smooth Page Refresh on Actions:

      • After actions like delete or mark as paid, the page refreshes smoothly with a success message, providing immediate feedback to the user.

    2. Updated generate_payslip.php

    This script generates a PDF payslip for a specific salary record, styled to match the overall design aesthetics.

    generate_payslip.php

    <?php
    // accountant/generate_payslip.php
    
    session_start();
    require_once '../db_connect.php';
    require_once '../assets/libraries/tcpdf/tcpdf.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();
    }
    
    // Check if salary ID is provided
    if (!isset($_GET['id'])) {
        $_SESSION['error'] = "No salary record selected.";
        header("Location: manage_salaries.php");
        exit();
    }
    
    $salary_id = (int)$_GET['id'];
    
    if ($salary_id <= 0) {
        $_SESSION['error'] = "Invalid Salary ID.";
        header("Location: manage_salaries.php");
        exit();
    }
    
    try {
        // Fetch the salary record along with employee details
        $stmt = $pdo->prepare("
            SELECT salaries.*, employees.name, employees.role, employees.email, employees.department
            FROM salaries
            JOIN employees ON salaries.employee_id = employees.id
            WHERE salaries.id = :id
        ");
        $stmt->execute([':id' => $salary_id]);
        $salary = $stmt->fetch();
    
        if (!$salary) {
            $_SESSION['error'] = "Salary record not found.";
            header("Location: manage_salaries.php");
            exit();
        }
    
        // Initialize TCPDF
        $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
    
        // Set Document Information
        $pdf->SetCreator('Salary Management System');
        $pdf->SetAuthor('Your Company Name');
        $pdf->SetTitle('Salary Payslip');
        $pdf->SetSubject('Payslip for ' . $salary['name']);
    
        // Remove default header/footer
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);
    
        // Set margins
        $pdf->SetMargins(15, 15, 15, true);
    
        // Add a page
        $pdf->AddPage();
    
        // Styles
        $style = '<style>
                    body { font-family: "Poppins", sans-serif; color: #333; }
                    .header { text-align: center; }
                    .header h2 { margin-bottom: -10px; color: var(--primary-color); }
                    .header p { margin-top: 0; }
                    table { width: 100%; border-collapse: collapse; margin-top: 20px; }
                    table, th, td { border: 1px solid #000; }
                    th, td { padding: 8px 12px; }
                    .total { font-weight: bold; }
                    .notes { margin-top: 20px; }
                  </style>';
    
        // Header Content
        $header = '
            <div class="header">
                <h2>Your Company Name</h2>
                <p>1234 Street Address, City, Country</p>
                <h4>Payslip</h4>
            </div>';
    
        // Employee and Salary Details
        $details = '
            <table>
                <tr>
                    <td><strong>Employee Name:</strong> ' . sanitize_output($salary['name']) . '</td>
                    <td><strong>Role:</strong> ' . sanitize_output($salary['role']) . '</td>
                </tr>
                <tr>
                    <td><strong>Department:</strong> ' . sanitize_output($salary['department']) . '</td>
                    <td><strong>Email:</strong> ' . sanitize_output($salary['email']) . '</td>
                </tr>
                <tr>
                    <td><strong>Payment Date:</strong> ' . sanitize_output($salary['payment_date']) . '</td>
                    <td><strong>Status:</strong> ' . sanitize_output($salary['status']) . '</td>
                </tr>
            </table>';
    
        // Salary Breakdown
        $breakdown = '
            <table>
                <thead>
                    <tr>
                        <th>Description</th>
                        <th>Amount ($)</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>Basic Salary</td>
                        <td>' . number_format($salary['basic_salary'], 2) . '</td>
                    </tr>
                    <tr>
                        <td>Bonuses</td>
                        <td>' . number_format($salary['bonuses'], 2) . '</td>
                    </tr>
                    <tr>
                        <td>Overtime (' . $salary['overtime_hours'] . ' hrs)</td>
                        <td>' . number_format($salary['overtime_hours'] * $salary['overtime_rate'], 2) . '</td>
                    </tr>
                    <tr>
                        <td>Deductions</td>
                        <td>' . number_format($salary['deductions'], 2) . '</td>
                    </tr>
                    <tr>
                        <td>Tax</td>
                        <td>' . number_format($salary['tax'], 2) . '</td>
                    </tr>
                    <tr class="total">
                        <td>Net Salary</td>
                        <td>' . number_format($salary['net_salary'], 2) . '</td>
                    </tr>
                </tbody>
            </table>';
    
        // Notes
        $notes = '
            <div class="notes">
                <strong>Notes:</strong>
                <p>' . nl2br(sanitize_output($salary['notes'])) . '</p>
            </div>';
    
        // Assemble the PDF content
        $html = $style . $header . $details . $breakdown . $notes;
    
        // Output the HTML content
        $pdf->writeHTML($html, true, false, true, false, '');
    
        // Define the file name
        $pdf_file = '../accountant/upload/payslips/payslip_' . $salary['id'] . '.pdf';
    
        // Create directory if not exists
        if (!is_dir('../upload/payslips/')) {
            mkdir('../upload/payslips/', 0777, true);
        }
    
        // Save the PDF to the server
        $pdf->Output($pdf_file, 'F');
    
        // Update the payslip_path in the database
        $updateStmt = $pdo->prepare("UPDATE salaries SET payslip_path = :path WHERE id = :id");
        $updateStmt->execute([
            ':path' => $pdf_file,
            ':id' => $salary_id,
        ]);
    
        // Force download the PDF
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="payslip_' . $salary['id'] . '.pdf"');
        readfile($pdf_file);
        exit();
    } catch (PDOException $e) {
        // Log error for debugging
        error_log($e->getMessage(), 3, '../logs/error.log');
        $_SESSION['error'] = "An error occurred while generating the payslip.";
        header("Location: manage_salaries.php");
        exit();
    } catch (Exception $e) {
        // Handle TCPDF errors
        error_log($e->getMessage(), 3, '../logs/error.log');
        $_SESSION['error'] = "An unexpected error occurred.";
        header("Location: manage_salaries.php");
        exit();
    }
    ?>
    

    Explanation of Key Enhancements:

    1. Styling Consistency:

      • The CSS styles used in the HTML part of manage_salaries.php are mirrored in the PDF to ensure consistency in branding and design.
    2. Responsive Layout:

      • The PDF layout is clean and structured, making it easy to read and professional.
    3. Error Handling:

      • Comprehensive error handling ensures that any issues during PDF generation are logged, and the user receives appropriate feedback.
    4. Directory Structure:

      • The script checks and creates the upload/payslips/ directory if it doesn't exist, ensuring that payslips are stored correctly.

    3. Auxiliary PHP Scripts

    For the complete functionality to work, you need the following auxiliary scripts to handle actions like deleting a salary, marking as paid, and bulk actions. Below are the complete codes for these scripts.

    3.1. delete_salary.php

    <?php
    // accountant/delete_salary.php
    
    session_start();
    require_once '../db_connect.php';
    
    // Function to sanitize output
    function sanitize_output($data) {
        return htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
    }
    
    // Only accept POST requests
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        echo json_encode(['status' => 'error', 'message' => 'Invalid request method.']);
        exit();
    }
    
    // Check CSRF token
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid CSRF token.']);
        exit();
    }
    
    // Check if salary_id is set
    if (!isset($_POST['salary_id']) || empty($_POST['salary_id'])) {
        echo json_encode(['status' => 'error', 'message' => 'Salary ID not provided.']);
        exit();
    }
    
    $salary_id = (int)$_POST['salary_id'];
    
    if ($salary_id <= 0) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid Salary ID.']);
        exit();
    }
    
    try {
        // Check if the salary exists
        $stmt = $pdo->prepare("SELECT * FROM salaries WHERE id = :id");
        $stmt->execute([':id' => $salary_id]);
        $salary = $stmt->fetch();
    
        if (!$salary) {
            echo json_encode(['status' => 'error', 'message' => 'Salary record not found.']);
            exit();
        }
    
        // Delete the salary record
        $deleteStmt = $pdo->prepare("DELETE FROM salaries WHERE id = :id");
        $deleteStmt->execute([':id' => $salary_id]);
    
        // Optionally, delete the payslip file if exists
        if (!empty($salary['payslip_path']) && file_exists($salary['payslip_path'])) {
            unlink($salary['payslip_path']);
        }
    
        echo json_encode(['status' => 'success', 'message' => 'Salary record deleted successfully.']);
        exit();
    } catch (PDOException $e) {
        // Log error
        error_log($e->getMessage(), 3, '../logs/error.log');
        echo json_encode(['status' => 'error', 'message' => 'An error occurred while deleting the salary record.']);
        exit();
    }
    ?>
    

    3.2. mark_paid.php

    <?php
    // accountant/mark_paid.php
    
    session_start();
    require_once '../db_connect.php';
    
    // Function to sanitize output
    function sanitize_output($data) {
        return htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
    }
    
    // Only accept POST requests
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        echo json_encode(['status' => 'error', 'message' => 'Invalid request method.']);
        exit();
    }
    
    // Check CSRF token
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid CSRF token.']);
        exit();
    }
    
    // Check if salary_id is set
    if (!isset($_POST['salary_id']) || empty($_POST['salary_id'])) {
        echo json_encode(['status' => 'error', 'message' => 'Salary ID not provided.']);
        exit();
    }
    
    $salary_id = (int)$_POST['salary_id'];
    
    if ($salary_id <= 0) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid Salary ID.']);
        exit();
    }
    
    try {
        // Check if the salary exists and is pending
        $stmt = $pdo->prepare("SELECT * FROM salaries WHERE id = :id AND status = 'Pending'");
        $stmt->execute([':id' => $salary_id]);
        $salary = $stmt->fetch();
    
        if (!$salary) {
            echo json_encode(['status' => 'error', 'message' => 'Salary record not found or already marked as Paid.']);
            exit();
        }
    
        // Update the status to Paid
        $updateStmt = $pdo->prepare("UPDATE salaries SET status = 'Paid' WHERE id = :id");
        $updateStmt->execute([':id' => $salary_id]);
    
        echo json_encode(['status' => 'success', 'message' => 'Salary marked as Paid successfully.']);
        exit();
    } catch (PDOException $e) {
        // Log error
        error_log($e->getMessage(), 3, '../logs/error.log');
        echo json_encode(['status' => 'error', 'message' => 'An error occurred while updating the salary status.']);
        exit();
    }
    ?>
    

    3.3. bulk_actions.php

    <?php
    // accountant/bulk_actions.php
    
    session_start();
    require_once '../db_connect.php';
    
    // Function to sanitize output
    function sanitize_output($data) {
        return htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
    }
    
    // Only accept POST requests
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        echo json_encode(['status' => 'error', 'message' => 'Invalid request method.']);
        exit();
    }
    
    // Check CSRF token
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid CSRF token.']);
        exit();
    }
    
    // Check if action is set
    if (!isset($_POST['action']) || empty($_POST['action'])) {
        echo json_encode(['status' => 'error', 'message' => 'Action not specified.']);
        exit();
    }
    
    $action = $_POST['action'];
    
    // Check if salary_ids are set and is an array
    if (!isset($_POST['salary_ids']) || !is_array($_POST['salary_ids']) || empty($_POST['salary_ids'])) {
        echo json_encode(['status' => 'error', 'message' => 'No salary records selected.']);
        exit();
    }
    
    $salary_ids = array_map('intval', $_POST['salary_ids']);
    $salary_ids = array_filter($salary_ids, function($id) { return $id > 0; });
    
    if (empty($salary_ids)) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid Salary IDs provided.']);
        exit();
    }
    
    try {
        if ($action === 'delete') {
            // Fetch salaries to delete and get payslip paths
            $placeholders = implode(',', array_fill(0, count($salary_ids), '?'));
            $stmt = $pdo->prepare("SELECT payslip_path FROM salaries WHERE id IN ($placeholders)");
            $stmt->execute($salary_ids);
            $salaries = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
            // Delete the salary records
            $deleteStmt = $pdo->prepare("DELETE FROM salaries WHERE id IN ($placeholders)");
            $deleteStmt->execute($salary_ids);
    
            // Delete associated payslip files
            foreach ($salaries as $salary) {
                if (!empty($salary['payslip_path']) && file_exists($salary['payslip_path'])) {
                    unlink($salary['payslip_path']);
                }
            }
    
            echo json_encode(['status' => 'success', 'message' => 'Selected salary records have been deleted successfully.']);
            exit();
        } elseif ($action === 'mark_paid') {
            // Update status to Paid for selected salaries
            $placeholders = implode(',', array_fill(0, count($salary_ids), '?'));
            $updateStmt = $pdo->prepare("UPDATE salaries SET status = 'Paid' WHERE id IN ($placeholders) AND status = 'Pending'");
            $updateStmt->execute($salary_ids);
    
            $affected = $updateStmt->rowCount();
    
            if ($affected > 0) {
                echo json_encode(['status' => 'success', 'message' => "$affected salary record(s) marked as Paid successfully."]);
                exit();
            } else {
                echo json_encode(['status' => 'error', 'message' => 'No pending salary records were found for the selected IDs.']);
                exit();
            }
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Invalid action specified.']);
            exit();
        }
    } catch (PDOException $e) {
        // Log error
        error_log($e->getMessage(), 3, '../logs/error.log');
        echo json_encode(['status' => 'error', 'message' => 'An error occurred while processing your request.']);
        exit();
    }
    ?>
    

    3.4. add_salary.php

    <?php
    // accountant/add_salary.php
    
    session_start();
    require_once '../db_connect.php';
    
    // Function to sanitize output
    function sanitize_input($data) {
        return trim(htmlspecialchars($data, ENT_QUOTES, 'UTF-8'));
    }
    
    // Only accept POST requests
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        $_SESSION['error'] = "Invalid request method.";
        header("Location: manage_salaries.php");
        exit();
    }
    
    // Check CSRF token
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $_SESSION['error'] = "Invalid CSRF token.";
        header("Location: manage_salaries.php");
        exit();
    }
    
    // Retrieve and sanitize form inputs
    $employee_id = isset($_POST['employee_id']) ? (int)$_POST['employee_id'] : 0;
    $payment_date = isset($_POST['payment_date']) ? sanitize_input($_POST['payment_date']) : '';
    $basic_salary = isset($_POST['basic_salary']) ? (float)$_POST['basic_salary'] : 0.00;
    $bonuses = isset($_POST['bonuses']) ? (float)$_POST['bonuses'] : 0.00;
    $deductions = isset($_POST['deductions']) ? (float)$_POST['deductions'] : 0.00;
    $overtime_hours = isset($_POST['overtime_hours']) ? (int)$_POST['overtime_hours'] : 0;
    $overtime_rate = isset($_POST['overtime_rate']) ? (float)$_POST['overtime_rate'] : 0.00;
    $tax = isset($_POST['tax']) ? (float)$_POST['tax'] : 0.00;
    $notes = isset($_POST['notes']) ? sanitize_input($_POST['notes']) : '';
    
    // Validate required fields
    if ($employee_id <= 0 || empty($payment_date) || $basic_salary <= 0 || $tax < 0) {
        $_SESSION['error'] = "Please fill out all required fields correctly.";
        header("Location: manage_salaries.php");
        exit();
    }
    
    // Calculate net salary
    $net_salary = ($basic_salary + $bonuses + ($overtime_hours * $overtime_rate)) - ($deductions + $tax);
    
    try {
        // Insert the salary record
        $stmt = $pdo->prepare("
            INSERT INTO salaries (employee_id, basic_salary, bonuses, deductions, overtime_hours, overtime_rate, tax, payment_date, net_salary, status, notes)
            VALUES (:employee_id, :basic_salary, :bonuses, :deductions, :overtime_hours, :overtime_rate, :tax, :payment_date, :net_salary, 'Pending', :notes)
        ");
        $stmt->execute([
            ':employee_id' => $employee_id,
            ':basic_salary' => $basic_salary,
            ':bonuses' => $bonuses,
            ':deductions' => $deductions,
            ':overtime_hours' => $overtime_hours,
            ':overtime_rate' => $overtime_rate,
            ':tax' => $tax,
            ':payment_date' => $payment_date,
            ':net_salary' => $net_salary,
            ':notes' => $notes
        ]);
    
        $_SESSION['success'] = "Salary record added successfully.";
        header("Location: manage_salaries.php");
        exit();
    } catch (PDOException $e) {
        // Log error
        error_log($e->getMessage(), 3, '../logs/error.log');
        $_SESSION['error'] = "An error occurred while adding the salary record.";
        header("Location: manage_salaries.php");
        exit();
    }
    ?>
    

    3.5. edit_salary.php & edit_salary_form.php

    Note: To keep things modular, edit_salary_form.php will handle fetching the existing salary details and rendering the edit form inside the modal. edit_salary.php will process the form submission.

    edit_salary_form.php

    <?php
    // accountant/edit_salary_form.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 salary ID is provided
    if (!isset($_GET['id'])) {
        echo "Invalid request.";
        exit();
    }
    
    $salary_id = (int)$_GET['id'];
    
    if ($salary_id <= 0) {
        echo "Invalid Salary ID.";
        exit();
    }
    
    try {
        // Fetch the salary record
        $stmt = $pdo->prepare("SELECT * FROM salaries WHERE id = :id");
        $stmt->execute([':id' => $salary_id]);
        $salary = $stmt->fetch();
    
        if (!$salary) {
            echo "Salary record not found.";
            exit();
        }
    
        // Fetch all active employees for the 'Edit Salary' form
        $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) {
        echo "An error occurred while fetching the salary record.";
        exit();
    }
    ?>
    <div class="modal-header">
        <h5 class="modal-title" id="editSalaryModalLabel">Edit Salary</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
    </div>
    <div class="modal-body">
        <form action="edit_salary.php" method="POST" id="editSalaryForm">
            <!-- CSRF Token -->
            <input type="hidden" name="csrf_token" value="<?php echo sanitize_output($_SESSION['csrf_token']); ?>">
            <!-- Salary ID -->
            <input type="hidden" name="salary_id" value="<?php echo sanitize_output($salary['id']); ?>">
    
            <div class="row g-3">
                <!-- Employee Selection -->
                <div class="col-md-6">
                    <label for="employee_id_edit" class="form-label">Employee <span class="text-danger">*</span></label>
                    <select class="form-select" id="employee_id_edit" name="employee_id" required>
                        <option value="" disabled>Select an employee</option>
                        <?php foreach ($employees as $employee): ?>
                            <option value="<?php echo sanitize_output($employee['id']); ?>" <?php echo ($salary['employee_id'] == $employee['id']) ? 'selected' : ''; ?>>
                                <?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_edit" class="form-label">Payment Date <span class="text-danger">*</span></label>
                    <input type="date" class="form-control" id="payment_date_edit" name="payment_date" value="<?php echo sanitize_output($salary['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_edit" class="form-label">Basic Salary ($) <span class="text-danger">*</span></label>
                    <input type="number" step="0.01" class="form-control" id="basic_salary_edit" name="basic_salary" value="<?php echo sanitize_output($salary['basic_salary']); ?>" required>
                    <div class="invalid-feedback">
                        Please enter a valid basic salary.
                    </div>
                </div>
                <!-- Bonuses -->
                <div class="col-md-4">
                    <label for="bonuses_edit" class="form-label">Bonuses ($)</label>
                    <input type="number" step="0.01" class="form-control" id="bonuses_edit" name="bonuses" value="<?php echo sanitize_output($salary['bonuses']); ?>">
                </div>
                <!-- Deductions -->
                <div class="col-md-4">
                    <label for="deductions_edit" class="form-label">Deductions ($)</label>
                    <input type="number" step="0.01" class="form-control" id="deductions_edit" name="deductions" value="<?php echo sanitize_output($salary['deductions']); ?>">
                </div>
                <!-- Overtime Hours -->
                <div class="col-md-4">
                    <label for="overtime_hours_edit" class="form-label">Overtime Hours</label>
                    <input type="number" class="form-control" id="overtime_hours_edit" name="overtime_hours" value="<?php echo sanitize_output($salary['overtime_hours']); ?>">
                </div>
                <!-- Overtime Rate -->
                <div class="col-md-4">
                    <label for="overtime_rate_edit" class="form-label">Overtime Rate ($/hr)</label>
                    <input type="number" step="0.01" class="form-control" id="overtime_rate_edit" name="overtime_rate" value="<?php echo sanitize_output($salary['overtime_rate']); ?>">
                </div>
                <!-- Tax -->
                <div class="col-md-4">
                    <label for="tax_edit" class="form-label">Tax ($) <span class="text-danger">*</span></label>
                    <input type="number" step="0.01" class="form-control" id="tax_edit" name="tax" value="<?php echo sanitize_output($salary['tax']); ?>" 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_edit" class="form-label">Net Salary ($)</label>
                    <input type="text" class="form-control" id="net_salary_edit" name="net_salary" readonly>
                </div>
                <!-- Notes -->
                <div class="col-md-6">
                    <label for="notes_edit" class="form-label">Notes</label>
                    <textarea class="form-control" id="notes_edit" name="notes" rows="3"><?php echo sanitize_output($salary['notes']); ?></textarea>
                </div>
            </div>
        </form>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button type="submit" form="editSalaryForm" name="edit_salary" class="btn btn-custom">Save Changes</button>
    </div>
    <script>
        // Calculate Net Salary on Input Change
        $('#editSalaryForm').on('input', '#basic_salary_edit, #bonuses_edit, #deductions_edit, #overtime_hours_edit, #overtime_rate_edit, #tax_edit', function(){
            var basic = parseFloat($('#basic_salary_edit').val()) || 0;
            var bonuses = parseFloat($('#bonuses_edit').val()) || 0;
            var deductions = parseFloat($('#deductions_edit').val()) || 0;
            var overtime_hours = parseFloat($('#overtime_hours_edit').val()) || 0;
            var overtime_rate = parseFloat($('#overtime_rate_edit').val()) || 0;
            var tax = parseFloat($('#tax_edit').val()) || 0;
    
            var net_salary = (basic + bonuses + (overtime_hours * overtime_rate)) - (deductions + tax);
            $('#net_salary_edit').val(net_salary.toFixed(2));
        });
    
        // Form Validation for Edit Salary
        (function () {
            'use strict'
    
            var form = document.getElementById('editSalaryForm')
    
            form.addEventListener('submit', function (event) {
                if (!form.checkValidity()) {
                    event.preventDefault()
                    event.stopPropagation()
                }
    
                form.classList.add('was-validated')
            }, false)
        })()
    </script>
    

    edit_salary.php

    <?php
    // accountant/edit_salary.php
    
    session_start();
    require_once '../db_connect.php';
    
    // Function to sanitize output
    function sanitize_input($data) {
        return trim(htmlspecialchars($data, ENT_QUOTES, 'UTF-8'));
    }
    
    // Only accept POST requests
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        $_SESSION['error'] = "Invalid request method.";
        header("Location: manage_salaries.php");
        exit();
    }
    
    // Check CSRF token
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $_SESSION['error'] = "Invalid CSRF token.";
        header("Location: manage_salaries.php");
        exit();
    }
    
    // Retrieve and sanitize form inputs
    $salary_id = isset($_POST['salary_id']) ? (int)$_POST['salary_id'] : 0;
    $employee_id = isset($_POST['employee_id']) ? (int)$_POST['employee_id'] : 0;
    $payment_date = isset($_POST['payment_date']) ? sanitize_input($_POST['payment_date']) : '';
    $basic_salary = isset($_POST['basic_salary']) ? (float)$_POST['basic_salary'] : 0.00;
    $bonuses = isset($_POST['bonuses']) ? (float)$_POST['bonuses'] : 0.00;
    $deductions = isset($_POST['deductions']) ? (float)$_POST['deductions'] : 0.00;
    $overtime_hours = isset($_POST['overtime_hours']) ? (int)$_POST['overtime_hours'] : 0;
    $overtime_rate = isset($_POST['overtime_rate']) ? (float)$_POST['overtime_rate'] : 0.00;
    $tax = isset($_POST['tax']) ? (float)$_POST['tax'] : 0.00;
    $notes = isset($_POST['notes']) ? sanitize_input($_POST['notes']) : '';
    
    // Validate required fields
    if ($salary_id <= 0 || $employee_id <= 0 || empty($payment_date) || $basic_salary <= 0 || $tax < 0) {
        $_SESSION['error'] = "Please fill out all required fields correctly.";
        header("Location: manage_salaries.php");
        exit();
    }
    
    // Calculate net salary
    $net_salary = ($basic_salary + $bonuses + ($overtime_hours * $overtime_rate)) - ($deductions + $tax);
    
    try {
        // Update the salary record
        $stmt = $pdo->prepare("
            UPDATE salaries
            SET employee_id = :employee_id,
                basic_salary = :basic_salary,
                bonuses = :bonuses,
                deductions = :deductions,
                overtime_hours = :overtime_hours,
                overtime_rate = :overtime_rate,
                tax = :tax,
                payment_date = :payment_date,
                net_salary = :net_salary,
                notes = :notes
            WHERE id = :id
        ");
        $stmt->execute([
            ':employee_id' => $employee_id,
            ':basic_salary' => $basic_salary,
            ':bonuses' => $bonuses,
            ':deductions' => $deductions,
            ':overtime_hours' => $overtime_hours,
            ':overtime_rate' => $overtime_rate,
            ':tax' => $tax,
            ':payment_date' => $payment_date,
            ':net_salary' => $net_salary,
            ':notes' => $notes,
            ':id' => $salary_id
        ]);
    
        $_SESSION['success'] = "Salary record updated successfully.";
        header("Location: manage_salaries.php");
        exit();
    } catch (PDOException $e) {
        // Log error
        error_log($e->getMessage(), 3, '../logs/error.log');
        $_SESSION['error'] = "An error occurred while updating the salary record.";
        header("Location: manage_salaries.php");
        exit();
    }
    ?>
    

    4. Database Structure Alignment

    Based on your provided database structure, ensure that the salaries and employees tables are correctly set up in your MySQL database. Here's a brief SQL overview for these tables:

    4.1. employees Table

    CREATE TABLE `employees` (
        `id` INT AUTO_INCREMENT PRIMARY KEY,
        `name` VARCHAR(255) NOT NULL,
        `role` ENUM('admin', 'doctor', 'staff') NOT NULL,
        `email` VARCHAR(255) NOT NULL UNIQUE,
        `phone` VARCHAR(20),
        `department` VARCHAR(100),
        `date_of_joining` DATE,
        `status` ENUM('active', 'inactive') DEFAULT 'active',
        `username` VARCHAR(100) NOT NULL UNIQUE,
        `password` VARCHAR(255) NOT NULL,
        `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        `profile_picture` VARCHAR(255) DEFAULT 'default_profile.png',
        `specialization` VARCHAR(255) DEFAULT NULL
    );
    

    4.2. salaries Table

    CREATE TABLE `salaries` (
        `id` INT AUTO_INCREMENT PRIMARY KEY,
        `employee_id` INT NOT NULL,
        `basic_salary` DECIMAL(10,2) NOT NULL,
        `bonuses` DECIMAL(10,2) DEFAULT 0,
        `deductions` DECIMAL(10,2) DEFAULT 0,
        `overtime_hours` INT DEFAULT 0,
        `overtime_rate` DECIMAL(10,2) DEFAULT 0,
        `tax` DECIMAL(10,2) DEFAULT 0,
        `payment_date` DATE NOT NULL,
        `net_salary` DECIMAL(10,2) NOT NULL,
        `status` ENUM('Pending', 'Paid') DEFAULT 'Pending',
        `notes` TEXT,
        `payslip_path` VARCHAR(255),
        FOREIGN KEY (`employee_id`) REFERENCES `employees`(`id`) ON DELETE CASCADE
    );
    

    Note: The payslip_path column is added to store the path of the generated payslip PDF.


    5. Additional Recommendations

    1. Security Enhancements:

      • Password Hashing: Ensure that passwords for both admins and employees are securely hashed using algorithms like bcrypt before storing them in the database.
      • Prepared Statements: Continue using prepared statements to prevent SQL injection, as demonstrated in the provided scripts.
      • CSRF Protection: CSRF tokens are implemented to protect against Cross-Site Request Forgery attacks.
    2. Error Logging:

      • Ensure that the logs/error.log file is writable by the server and is stored securely, preferably outside the web root to prevent unauthorized access.
    3. Directory Permissions:

      • The upload/payslips/ directory should have appropriate permissions (e.g., 0755) to allow PHP to write files while preventing unauthorized access.
    4. Responsive Design Testing:

      • Test the dashboard on various devices to ensure that the design remains consistent and user-friendly across different screen sizes.
    5. Accessibility:

      • Ensure that the dashboard is accessible to users with disabilities by following WCAG guidelines.
    6. Code Maintenance:

      • Consider organizing your JavaScript and CSS into separate files (scripts.js and styles.css) for better maintainability, especially as the project grows.

    By integrating the provided CSS styles and enhancing the PHP scripts, your Salary Management Dashboard should now have a modern, responsive, and user-friendly interface. The use of SweetAlert2 ensures that user interactions are smooth and intuitive, providing immediate feedback on actions like deletions and updates. The structure also aligns perfectly with your updated database schema, ensuring data integrity and seamless functionality.

    Feel free to further customize the styles and functionalities as per your specific requirements!