<?php
include('session_validator.php');
include('includes/db.php');

// Handle delete action
if (isset($_GET['delete_id'])) {
    $delete_id = intval($_GET['delete_id']);
    
    $stmt = $conn->prepare("DELETE FROM exam_subject_marks WHERE id = ?");
    $stmt->bind_param("i", $delete_id);
    
    if ($stmt->execute()) {
        $alert = "delete_success";
    } else {
        $alert = "delete_error";
    }
    $stmt->close();
}

// Handle bulk delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_delete'])) {
    if (isset($_POST['selected_ids']) && is_array($_POST['selected_ids'])) {
        $selected_ids = array_map('intval', $_POST['selected_ids']);
        $placeholders = implode(',', array_fill(0, count($selected_ids), '?'));
        
        $stmt = $conn->prepare("DELETE FROM exam_subject_marks WHERE id IN ($placeholders)");
        $types = str_repeat('i', count($selected_ids));
        $stmt->bind_param($types, ...$selected_ids);
        
        if ($stmt->execute()) {
            $alert = "bulk_delete_success";
        } else {
            $alert = "bulk_delete_error";
        }
        $stmt->close();
    }
}

// Fetch filter options
$exams = $conn->query("SELECT id, exm_year, exm_year_ad, exam_type FROM examination_type ORDER BY id DESC")->fetch_all(MYSQLI_ASSOC);
$classes = $conn->query("SELECT class_id, class FROM classes WHERE status = '1' ORDER BY class_numeric")->fetch_all(MYSQLI_ASSOC);
$sections = $conn->query("SELECT section_id, section_name FROM sections WHERE status = '1' ORDER BY section_id")->fetch_all(MYSQLI_ASSOC);
$sessions = $conn->query("SELECT year_id, ay_bs, ay_ad, status FROM academic_years ORDER BY year_id DESC")->fetch_all(MYSQLI_ASSOC);

// Build WHERE clause based on filters
$where_conditions = [];
$params = [];
$types = '';

// Get filter values from URL
$filter_session = isset($_GET['session_id']) ? intval($_GET['session_id']) : '';
$filter_exam = isset($_GET['exam_id']) ? intval($_GET['exam_id']) : '';
$filter_class = isset($_GET['class_id']) ? intval($_GET['class_id']) : '';
$filter_section = isset($_GET['section_id']) ? intval($_GET['section_id']) : '';

if (!empty($filter_session)) {
    $where_conditions[] = "esm.session_id = ?";
    $params[] = $filter_session;
    $types .= 'i';
}

if (!empty($filter_exam)) {
    $where_conditions[] = "esm.exam_id = ?";
    $params[] = $filter_exam;
    $types .= 'i';
}

if (!empty($filter_class)) {
    $where_conditions[] = "esm.class_id = ?";
    $params[] = $filter_class;
    $types .= 'i';
}

if (!empty($filter_section)) {
    $where_conditions[] = "esm.section_id = ?";
    $params[] = $filter_section;
    $types .= 'i';
}

// Build query - FIXED: Using subjects.id instead of subjects.subject_id
$query = "SELECT 
            esm.*,
            ay.ay_bs as session_name,
            ay.ay_ad as session_year_ad,
            et.exam_type,
            et.exm_year,
            et.exm_year_ad,
            c.class,
            s.section_name,
            sub.subject_code,
            sub.subject_name,
            sub.type as subject_type
          FROM exam_subject_marks esm
          LEFT JOIN academic_years ay ON esm.session_id = ay.year_id
          LEFT JOIN examination_type et ON esm.exam_id = et.id
          LEFT JOIN classes c ON esm.class_id = c.class_id
          LEFT JOIN sections s ON esm.section_id = s.section_id
          LEFT JOIN subjects sub ON esm.subject_id = sub.id  -- FIXED: Changed sub.subject_id to sub.id
        ";

if (!empty($where_conditions)) {
    $query .= " WHERE " . implode(" AND ", $where_conditions);
}

$query .= " ORDER BY esm.session_id DESC, esm.exam_id DESC, esm.class_id, esm.section_id, sub.subject_name";

// Prepare and execute query
$stmt = $conn->prepare($query);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();
$records = $result->fetch_all(MYSQLI_ASSOC);
$total_records = $result->num_rows;

$stmt->close();

// Calculate totals
$total_theory_marks = 0;
$total_internal_marks = 0;
$total_theory_credits = 0;
$total_internal_credits = 0;

foreach ($records as $record) {
    $total_theory_marks += floatval($record['full_marks_theory']);
    $total_internal_marks += floatval($record['full_marks_internal']);
    $total_theory_credits += floatval($record['theory_credit_hour']);
    $total_internal_credits += floatval($record['internal_credit_hour']);
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>View Exam Subject Marks</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/font-awesome.min.css">
    <link rel="stylesheet" href="css/animate-css/animate.min.css">
    <link rel="stylesheet" href="css/lobipanel/lobipanel.min.css">
    <link rel="stylesheet" href="css/datatables/datatables.min.css">
    <link rel="stylesheet" href="css/main.css">
    <style>
        /* ... (keep all the CSS styles from previous version) ... */
        .custom-button {
            color: white;
            background-color: #28a745;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: all 0.3s;
            font-weight: 600;
            text-decoration: none;
            display: inline-block;
        }

        .custom-button:hover {
            color: white;
            background-color: #218838;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            text-decoration: none;
        }
        
        .btn-edit {
            background-color: #ffc107;
            color: #212529;
            border: none;
        }
        
        .btn-edit:hover {
            background-color: #e0a800;
            color: #212529;
        }
        
        .btn-delete {
            background-color: #dc3545;
            color: white;
            border: none;
        }
        
        .btn-delete:hover {
            background-color: #c82333;
            color: white;
        }
        
        .badge-type {
            font-size: 0.75rem;
            padding: 3px 8px;
            border-radius: 12px;
        }
        
        .type-compulsory {
            background-color: #d4edda;
            color: #155724;
        }
        
        .type-optional {
            background-color: #fff3cd;
            color: #856404;
        }
        
        .type-elective {
            background-color: #d1ecf1;
            color: #0c5460;
        }
        
        .summary-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .summary-card h5 {
            font-weight: 600;
            margin-bottom: 15px;
            color: white;
        }
        
        .summary-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 0;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }
        
        .summary-item:last-child {
            border-bottom: none;
        }
        
        .summary-label {
            font-size: 0.9rem;
            opacity: 0.9;
        }
        
        .summary-value {
            font-weight: bold;
            font-size: 1.1rem;
        }
        
        .filter-card {
            background-color: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            border: 1px solid #e9ecef;
        }
        
        .select2-container--default .select2-selection--single {
            height: 38px;
            padding: 5px;
        }
        
        .action-buttons {
            white-space: nowrap;
        }
        
        .checkbox-column {
            width: 40px;
            text-align: center;
        }
        
        .table th {
            background-color: #f1f3f4;
            font-weight: 600;
            border-bottom: 2px solid #dee2e6;
        }
        
        .table td {
            vertical-align: middle;
        }
        
        .marks-cell {
            font-weight: 600;
            text-align: center;
        }
        
        .credit-cell {
            text-align: center;
            font-weight: 500;
        }
        
        .no-records {
            text-align: center;
            padding: 50px;
            color: #6c757d;
        }
        
        .no-records i {
            font-size: 48px;
            margin-bottom: 20px;
            color: #dee2e6;
        }
        
        .bulk-actions {
            background-color: #fff3cd;
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 15px;
            border: 1px solid #ffeaa7;
        }
    </style>
</head>

<body class="top-navbar-fixed">
    <div class="main-wrapper">
        <?php include('includes/topbar.php'); ?>
        <div class="content-wrapper">
            <div class="content-container">
                <?php include('includes/leftbar.php'); ?>
               
                <div class="main-page">
                    <div class="container-fluid">
                        <div class="row page-title-div">
                            <div class="col-md-6">
                                <h2 class="title"><i class="fa fa-list-alt"></i> View Exam Subject Marks</h2>
                            </div>
                            <div class="col-md-6 text-right">
                                <a href="assign_full_marks.php" class="custom-button">
                                    <i class="fa fa-plus-circle"></i> Assign New Marks
                                </a>
                            </div>
                        </div>

                        <div class="row breadcrumb-div">
                            <div class="col-md-12">
                                <ul class="breadcrumb">
                                    <li><a href="dashboard.php"><i class="fa fa-home"></i> Home</a></li>
                                    <li>Exam Management</li>
                                    <li class="active">View Subject Marks</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    
                    <div class="container-fluid">
                        <!-- Summary Cards -->
                        <div class="row">
                            <div class="col-md-3">
                                <div class="summary-card">
                                    <h5><i class="fa fa-file-text"></i> Total Records</h5>
                                    <div class="summary-item">
                                        <span class="summary-label">Subjects Marks</span>
                                        <span class="summary-value"><?= number_format($total_records) ?></span>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="summary-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                                    <h5><i class="fa fa-calculator"></i> Theory Marks</h5>
                                    <div class="summary-item">
                                        <span class="summary-label">Total Theory</span>
                                        <span class="summary-value"><?= number_format($total_theory_marks, 2) ?></span>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="summary-card" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
                                    <h5><i class="fa fa-calculator"></i> Internal Marks</h5>
                                    <div class="summary-item">
                                        <span class="summary-label">Total Internal</span>
                                        <span class="summary-value"><?= number_format($total_internal_marks, 2) ?></span>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="summary-card" style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);">
                                    <h5><i class="fa fa-clock-o"></i> Credit Hours</h5>
                                    <div class="summary-item">
                                        <span class="summary-label">Theory/Internal</span>
                                        <span class="summary-value"><?= number_format($total_theory_credits, 2) ?>/<?= number_format($total_internal_credits, 2) ?></span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Filter Form -->
                        <div class="filter-card">
                            <h5><i class="fa fa-filter"></i> Filter Records</h5>
                            <form method="GET" id="filterForm">
                                <div class="row">
                                    <div class="form-group col-md-3">
                                        <label>Session</label>
                                        <select name="session_id" class="form-control select2">
                                            <option value="">All Sessions</option>
                                            <?php foreach ($sessions as $s): ?>
                                                <option value="<?= $s['year_id'] ?>" <?= $filter_session == $s['year_id'] ? 'selected' : '' ?>>
                                                    <?= htmlspecialchars($s['ay_bs']) ?> - <?= htmlspecialchars($s['ay_ad']) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="form-group col-md-3">
                                        <label>Exam</label>
                                        <select name="exam_id" class="form-control select2">
                                            <option value="">All Exams</option>
                                            <?php foreach ($exams as $ex): ?>
                                                <option value="<?= $ex['id'] ?>" <?= $filter_exam == $ex['id'] ? 'selected' : '' ?>>
                                                    <?= htmlspecialchars($ex['exam_type']) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="form-group col-md-3">
                                        <label>Class</label>
                                        <select name="class_id" class="form-control select2">
                                            <option value="">All Classes</option>
                                            <?php foreach ($classes as $cl): ?>
                                                <option value="<?= $cl['class_id'] ?>" <?= $filter_class == $cl['class_id'] ? 'selected' : '' ?>>
                                                    <?= htmlspecialchars($cl['class']) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="form-group col-md-3">
                                        <label>Section</label>
                                        <select name="section_id" class="form-control select2">
                                            <option value="">All Sections</option>
                                            <?php foreach ($sections as $sec): ?>
                                                <option value="<?= $sec['section_id'] ?>" <?= $filter_section == $sec['section_id'] ? 'selected' : '' ?>>
                                                    <?= htmlspecialchars($sec['section_name']) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                                <div class="text-right mt-3">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fa fa-search"></i> Apply Filters
                                    </button>
                                    <a href="view_exam_subject_marks.php" class="btn btn-secondary">
                                        <i class="fa fa-refresh"></i> Reset
                                    </a>
                                </div>
                            </form>
                        </div>
                        
                        <!-- Records Table -->
                        <div class="panel">
                            <div class="panel-heading">
                                <div class="panel-title">
                                    <h5><i class="fa fa-table"></i> Subject Marks Records</h5>
                                </div>
                            </div>
                            <div class="panel-body">
                                <?php if ($total_records > 0): ?>
                                    <!-- Bulk Actions -->
                                    <form method="POST" id="bulkForm" onsubmit="return confirmBulkDelete()">
                                        <div class="bulk-actions">
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <div class="form-check">
                                                        <input type="checkbox" class="form-check-input" id="selectAll">
                                                        <label class="form-check-label" for="selectAll">
                                                            <strong>Select All</strong>
                                                        </label>
                                                    </div>
                                                </div>
                                                <div class="col-md-6 text-right">
                                                    <button type="submit" name="bulk_delete" class="btn btn-danger btn-sm">
                                                        <i class="fa fa-trash"></i> Delete Selected
                                                    </button>
                                                    <button type="button" class="btn btn-success btn-sm" onclick="exportToExcel()">
                                                        <i class="fa fa-download"></i> Export to Excel
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="table-responsive">
                                            <table class="table table-bordered table-hover" id="recordsTable">
                                                <thead>
                                                    <tr>
                                                        <th class="checkbox-column">
                                                            <input type="checkbox" id="selectAllCheckbox">
                                                        </th>
                                                        <th>#</th>
                                                        <th>Session</th>
                                                        <th>Exam</th>
                                                        <th>Class-Section</th>
                                                        <th>Subject</th>
                                                        <th>Theory Marks</th>
                                                        <th>Internal Marks</th>
                                                        <th>Theory Credit</th>
                                                        <th>Internal Credit</th>
                                                        <th>Remarks</th>
                                                        <th>Entered By</th>
                                                        <th>Updated By</th>
                                                        <th>Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php $counter = 0; ?>
                                                    <?php foreach ($records as $record): ?>
                                                        <?php 
                                                        $counter++;
                                                        $subject_type_class = '';
                                                        switch(strtolower($record['subject_type'])) {
                                                            case 'compulsory': $subject_type_class = 'type-compulsory'; break;
                                                            case 'optional': $subject_type_class = 'type-optional'; break;
                                                            case 'elective': $subject_type_class = 'type-elective'; break;
                                                            default: $subject_type_class = 'type-compulsory';
                                                        }
                                                        ?>
                                                        <tr>
                                                            <td class="checkbox-column">
                                                                <input type="checkbox" class="record-checkbox" name="selected_ids[]" value="<?= $record['id'] ?>">
                                                            </td>
                                                            <td><?= $counter ?></td>
                                                            <td>
                                                                <?= htmlspecialchars($record['session_name']) ?><br>
                                                                <small class="text-muted"><?= htmlspecialchars($record['session_year_ad']) ?></small>
                                                            </td>
                                                            <td>
                                                                <?= htmlspecialchars($record['exam_type']) ?><br>
                                                                <small class="text-muted">
                                                                    <?= htmlspecialchars($record['exm_year']) ?> [<?= htmlspecialchars($record['exm_year_ad']) ?>]
                                                                </small>
                                                            </td>
                                                            <td>
                                                                <?= htmlspecialchars($record['class']) ?> - <?= htmlspecialchars($record['section_name']) ?>
                                                            </td>
                                                            <td>
                                                                <strong><?= htmlspecialchars($record['subject_name']) ?></strong><br>
                                                                <small class="text-muted">Code: <?= htmlspecialchars($record['subject_code']) ?></small><br>
                                                                <span class="badge-type <?= $subject_type_class ?>">
                                                                    <?= ucfirst(htmlspecialchars($record['subject_type'])) ?>
                                                                </span>
                                                            </td>
                                                            <td class="marks-cell">
                                                                <?= number_format($record['full_marks_theory'], 2) ?>
                                                            </td>
                                                            <td class="marks-cell">
                                                                <?= number_format($record['full_marks_internal'], 2) ?>
                                                            </td>
                                                            <td class="credit-cell">
                                                                <?= number_format($record['theory_credit_hour'], 2) ?>
                                                            </td>
                                                            <td class="credit-cell">
                                                                <?= number_format($record['internal_credit_hour'], 2) ?>
                                                            </td>
                                                            <td>
                                                                <?= !empty($record['remarks']) ? htmlspecialchars($record['remarks']) : '<span class="text-muted">N/A</span>' ?>
                                                            </td>
                                                            <td>
                                                                <?= !empty($record['entered_by_name']) ? htmlspecialchars($record['entered_by_name']) : 'System' ?><br>
                                                                <small class="text-muted">
                                                                    <?= !empty($record['created_at']) ? date('d-M-Y H:i', strtotime($record['created_at'])) : 'N/A' ?>
                                                                </small>
                                                            </td>
                                                            <td>
                                                                <?php if (!empty($record['updated_by_name'])): ?>
                                                                    <?= htmlspecialchars($record['updated_by_name']) ?><br>
                                                                    <small class="text-muted">
                                                                        <?= !empty($record['updated_at']) ? date('d-M-Y H:i', strtotime($record['updated_at'])) : 'N/A' ?>
                                                                    </small>
                                                                <?php else: ?>
                                                                    <span class="text-muted">Not updated</span>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td class="action-buttons">
                                                                <a href="edit_exam_subject_marks.php?id=<?= $record['id'] ?>" 
                                                                   class="btn btn-edit btn-sm" 
                                                                   title="Edit">
                                                                    <i class="fa fa-edit"></i>
                                                                </a>
                                                                <button type="button" 
                                                                        class="btn btn-delete btn-sm" 
                                                                        onclick="confirmDelete(<?= $record['id'] ?>)" 
                                                                        title="Delete">
                                                                    <i class="fa fa-trash"></i>
                                                                </button>
                                                            </td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                </tbody>
                                                <tfoot>
                                                    <tr class="total-row">
                                                        <td colspan="6" class="text-right"><strong>TOTALS:</strong></td>
                                                        <td class="marks-cell"><?= number_format($total_theory_marks, 2) ?></td>
                                                        <td class="marks-cell"><?= number_format($total_internal_marks, 2) ?></td>
                                                        <td class="credit-cell"><?= number_format($total_theory_credits, 2) ?></td>
                                                        <td class="credit-cell"><?= number_format($total_internal_credits, 2) ?></td>
                                                        <td colspan="4"></td>
                                                    </tr>
                                                </tfoot>
                                            </table>
                                        </div>
                                    </form>
                                    
                                    <!-- Pagination Info -->
                                    <div class="row mt-3">
                                        <div class="col-md-6">
                                            <p class="text-muted">
                                                Showing <?= $counter ?> record(s) out of <?= $total_records ?>
                                            </p>
                                        </div>
                                    </div>
                                    
                                <?php else: ?>
                                    <div class="no-records">
                                        <i class="fa fa-inbox"></i>
                                        <h4>No records found</h4>
                                        <p>No subject marks records found for the selected filters.</p>
                                        <a href="assign_full_marks.php" class="btn btn-primary mt-3">
                                            <i class="fa fa-plus-circle"></i> Add New Marks
                                        </a>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="js/jquery/jquery-2.2.4.min.js"></script>
    <script src="js/bootstrap/bootstrap.min.js"></script>
    <script src="js/pace/pace.min.js"></script>
    <script src="js/lobipanel/lobipanel.min.js"></script>
    <script src="js/select2/select2.min.js"></script>
    <script src="js/datatables/datatables.min.js"></script>
    <script src="js/main.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>

    <script>
        $(document).ready(function() {
            // Initialize select2
            $('.select2').select2({
                theme: 'bootstrap'
            });
            
            // Initialize DataTable
            $('#recordsTable').DataTable({
                "pageLength": 25,
                "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
                "order": [[1, 'desc']],
                "columnDefs": [
                    { "orderable": false, "targets": [0, 13] },
                    { "searchable": false, "targets": [0, 13] }
                ],
                "language": {
                    "emptyTable": "No records available",
                    "info": "Showing _START_ to _END_ of _TOTAL_ records",
                    "infoEmpty": "Showing 0 to 0 of 0 records",
                    "infoFiltered": "(filtered from _MAX_ total records)",
                    "lengthMenu": "Show _MENU_ records",
                    "search": "Search:",
                    "zeroRecords": "No matching records found",
                    "paginate": {
                        "first": "First",
                        "last": "Last",
                        "next": "Next",
                        "previous": "Previous"
                    }
                }
            });
            
            // Select all checkboxes
            $('#selectAllCheckbox').click(function() {
                $('.record-checkbox').prop('checked', this.checked);
            });
            
            $('#selectAll').click(function() {
                $('.record-checkbox').prop('checked', this.checked);
                $('#selectAllCheckbox').prop('checked', this.checked);
            });
            
            // Uncheck "select all" if any checkbox is unchecked
            $('.record-checkbox').click(function() {
                if (!$(this).prop('checked')) {
                    $('#selectAllCheckbox').prop('checked', false);
                    $('#selectAll').prop('checked', false);
                }
            });
        });
        
        // Confirm delete function
        function confirmDelete(id) {
            Swal.fire({
                title: 'Are you sure?',
                text: "You won't be able to revert this!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, delete it!',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = 'view_exam_subject_marks.php?delete_id=' + id;
                }
            });
        }
        
        // Confirm bulk delete
        function confirmBulkDelete() {
            const selectedCount = $('.record-checkbox:checked').length;
            
            if (selectedCount === 0) {
                Swal.fire({
                    icon: 'warning',
                    title: 'No Selection',
                    text: 'Please select at least one record to delete.',
                    confirmButtonText: 'OK'
                });
                return false;
            }
            
            return Swal.fire({
                title: 'Delete Selected Records?',
                html: `You are about to delete <strong>${selectedCount}</strong> record(s).<br>This action cannot be undone.`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, delete them!',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                return result.isConfirmed;
            });
        }
        
        // Export to Excel function
        function exportToExcel() {
            const table = document.getElementById('recordsTable');
            const workbook = XLSX.utils.table_to_book(table, {sheet: "Subject Marks"});
            
            const sessionFilter = $('select[name="session_id"]').val();
            const examFilter = $('select[name="exam_id"]').val();
            const classFilter = $('select[name="class_id"]').val();
            const sectionFilter = $('select[name="section_id"]').val();
            
            let fileName = 'Subject_Marks';
            if (sessionFilter) {
                const sessionText = $('select[name="session_id"] option:selected').text();
                fileName += '_' + sessionText.replace(/[^a-z0-9]/gi, '_');
            }
            if (examFilter) {
                const examText = $('select[name="exam_id"] option:selected').text();
                fileName += '_' + examText.replace(/[^a-z0-9]/gi, '_');
            }
            fileName += '_' + new Date().toISOString().slice(0,10) + '.xlsx';
            
            XLSX.writeFile(workbook, fileName);
        }

        <?php if ($alert === "delete_success"): ?>
            Swal.fire({
                icon: 'success',
                title: 'Deleted!',
                text: 'Record has been deleted successfully.',
                timer: 3000,
                showConfirmButton: false
            });
        <?php elseif ($alert === "delete_error"): ?>
            Swal.fire({
                icon: 'error',
                title: 'Error!',
                text: 'Failed to delete the record. Please try again.',
                timer: 3000,
                showConfirmButton: true
            });
        <?php elseif ($alert === "bulk_delete_success"): ?>
            Swal.fire({
                icon: 'success',
                title: 'Success!',
                text: 'Selected records have been deleted successfully.',
                timer: 3000,
                showConfirmButton: false
            });
        <?php elseif ($alert === "bulk_delete_error"): ?>
            Swal.fire({
                icon: 'error',
                title: 'Error!',
                text: 'Failed to delete some records. Please try again.',
                timer: 3000,
                showConfirmButton: true
            });
        <?php endif; ?>
    </script>

</body>

</html>