<?php

session_name('super_admin_session');

if (!is_dir(dirname(__DIR__) . '/session_data/super')) {
    mkdir(dirname(__DIR__) . '/session_data/super', 0700, true);
}
session_save_path(dirname(__DIR__) . '/session_data/super');

session_set_cookie_params(['path' => '/', 'httponly' => true, 'samesite' => 'Strict']);

session_start();

error_reporting();

include('includes/dbconnection.php');
include('includes/flash.php');
require_once 'includes/session_term_helper.php';
$stResult = resolveCurrentSessionTerm($con);
$currentSessionName = $stResult['session_name'];
$currentTermName = $stResult['term_name'];



if (!isset($_SESSION['sid']) || strlen((string) $_SESSION['sid']) == 0) {

    header('location:logout.php');

    exit;

}



// Check if 'del' parameter exists in the URL

if (isset($_GET['del'])) {

    $id = intval($_GET['id']); // Securely get the ID from the URL



    // Backup student details with a prepared statement

    $backupQuery = "INSERT INTO fees_backup SELECT *, NOW() AS deleted_at FROM fees WHERE id = ?";

    if ($stmt = mysqli_prepare($con, $backupQuery)) {

        mysqli_stmt_bind_param($stmt, "i", $id);

        if (mysqli_stmt_execute($stmt)) {

            // Proceed to delete the record after backup with a prepared statement

            $deleteQuery = "DELETE FROM fees WHERE id = ?";

            if ($stmtDelete = mysqli_prepare($con, $deleteQuery)) {

                mysqli_stmt_bind_param($stmtDelete, "i", $id);

                if (mysqli_stmt_execute($stmtDelete)) {

                    flash_alert('Record deleted and backed up successfully.');

                    header('Location: feelist.php');
                    exit;

                } else {

                    flash_alert('Error deleting record from the database.');

                    echo "MySQL Error: " . mysqli_error($con); // Debugging

                }

                mysqli_stmt_close($stmtDelete);

            } else {

                flash_alert('Error preparing delete query.');

            }

        } else {

            flash_alert('Error backing up record details.');

            echo "MySQL Error: " . mysqli_error($con); // Debugging

        }

        mysqli_stmt_close($stmt);

    } else {

        flash_alert('Error preparing backup query.');

    }

}

?>



<!DOCTYPE html>

<html>

<?php @include("includes/head.php"); ?>

<body class="hold-transition sidebar-mini layout-fixed">

    <div class="wrapper">

        <!-- Navbar -->

        <?php @include("includes/header.php"); ?>



        <!-- Main Sidebar Container -->

        <?php @include("includes/sidebar.php"); ?>



        <!-- Content Wrapper. Contains page content -->

        <div class="content-wrapper">

            <!-- Content Header -->

            <section class="content-header premium-header">

                <div class="container-fluid">

                    <div class="header-glass-card">

                        <div class="row align-items-center">

                            <div class="col-md-8">

                                <div class="title-section">

                                    <div class="icon-box bg-primary-gradient shadow-sm">

                                        <i class="fas fa-wallet"></i>

                                    </div>

                                    <div>

                                        <h1 class="premium-title text-primary">

                                            Fees Management

                                            <span class="premium-subtitle text-secondary">Manage Fees</span>

                                        </h1>

                                    <div class="mt-1">
                                      <?php if ($currentSessionName): ?>
                                            <span class="badge badge-primary mr-1">
                                              <i class="fas fa-calendar-alt"></i>
                                              <?= htmlspecialchars($currentSessionName) ?>
                                            </span>
                                      <?php endif; ?>
                                      <?php if ($currentTermName): ?>
                                            <span class="badge badge-success">
                                              <i class="fas fa-bookmark"></i>
                                              <?= htmlspecialchars($currentTermName) ?>
                                            </span>
                                      <?php else: ?>
                                            <span class="badge badge-warning">
                                              <i class="fas fa-exclamation-triangle"></i> No active term
                                            </span>
                                      <?php endif; ?>
                                    </div>

                                    </div>

                                </div>

                            </div>

                            <div class="col-md-4">

                                <nav aria-label="breadcrumb">

                                    <ol class="breadcrumb premium-breadcrumb">

                                        <li class="breadcrumb-item"><a href="dashboard.php"
                                                class="text-primary">Home</a></li>

                                        <li class="breadcrumb-item active" aria-current="page">Fees List</li>

                                    </ol>

                                </nav>

                            </div>

                        </div>

                    </div>

                </div>

            </section>

            <!-- Main content -->

            <section class="content">

                <div class="container-fluid">

                    <div class="row">

                        <div class="col-12">

                            <div class="card card-primary">

                                <div class="card-header">

                                    <h5 class="card-title font-weight-bold"><i class="fas fa-money-bill-wave"></i>
                                        Manage Fees</h5>

                                    <div class="card-tools">

                                        <a href="restore_fees.php">

                                            <button type="button" class="btn btn-sm btn-primary">

                                                <span style="color: #fff;"><i class="fas fa-undo"></i> Restore
                                                    Fees</span>

                                            </button>

                                        </a>

                                        <a href="addfees.php">

                                            <button type="button" class="btn btn-sm btn-primary">

                                                <span><i class="ion ion-person-add"></i> Add New Fees</span>

                                            </button>

                                        </a>

                                    </div>

                                </div>



                                <!-- /.card-header -->

                                <div id="editData" class="modal fade">

                                    <div class="modal-dialog modal-xl">

                                        <div class="modal-content">

                                            <div class="modal-header">

                                                <h5 class="modal-title">Fees Details</h5>

                                                <button type="button" class="close" data-dismiss="modal"
                                                    aria-label="Close">

                                                    <span aria-hidden="true">&times;</span>

                                                </button>

                                            </div>

                                            <div class="modal-body" id="info_update">
                                                <!-- loaded via AJAX -->
                                            </div>

                                            <div class="modal-footer ">

                                                <button type="button" class="btn btn-default"
                                                    data-dismiss="modal">Cancel</button>

                                            </div>

                                            <!-- /.modal-content -->

                                        </div>

                                        <!-- /.modal-dialog -->

                                    </div>

                                    <!-- /.modal -->

                                </div>

                                <!--   end modal -->



                                <!-- Card Body -->

                                <div class="card-body mt-2">

                                    <table id="example1" class="table table-bordered table-hover">

                                        <thead>

                                            <tr>

                                                <th>#</th>

                                                <th>Fees Name</th>

                                                <th>Class</th>

                                                <th>School Type</th>

                                                <th>Amount</th>

                                                <th>Action</th>

                                            </tr>

                                        </thead>

                                        <tbody>

                                            <?php

                                            $query = mysqli_query($con, "SELECT * FROM fees ORDER BY name ASC");

                                            $cnt = 1;

                                            while ($row = mysqli_fetch_array($query)) {

                                                ?>

                                                <tr>

                                                    <td><?php echo htmlentities($cnt); ?></td>

                                                    <td><?php echo htmlentities($row['name']); ?></td>

                                                    <td><?php echo htmlentities($row['class']); ?></td>

                                                    <td><?php echo htmlentities($row['stream']); ?></td>

                                                    <td><?php echo htmlentities($row['amount']); ?></td>

                                                    <td>

                                                        <button class="btn btn-primary btn-xs edit_data"
                                                            id="<?php echo $row['id']; ?>" title="Edit">

                                                            <i class="fa fa-edit"></i>

                                                        </button>

                                                        <a href="feelist.php?id=<?php echo $row['id']; ?>&del=1"
                                                            onClick="return confirm('Are you sure you want to delete?')"
                                                            class="btn btn-danger btn-xs">

                                                            <i class="fa fa-trash"></i>

                                                        </a>

                                                    </td>

                                                </tr>

                                                <?php

                                                $cnt++;

                                            }

                                            ?>

                                        </tbody>

                                    </table>

                                </div>

                                <!-- /.card-body -->

                            </div>

                            <!-- /.card -->

                        </div>

                        <!-- /.col -->

                    </div>

                    <!-- /.row -->

                </div>

                <!-- /.container-fluid -->

            </section>

            <!-- /.content -->

        </div>

        <!-- /.content-wrapper -->

        <?php @include("includes/footer.php"); ?>



        <!-- Control Sidebar -->

        <aside class="control-sidebar control-sidebar-dark">

            <!-- Control sidebar content goes here -->

        </aside>

    </div>



    <!-- ./wrapper -->

    <?php @include("includes/foot.php"); ?>



    <!-- Scripts -->

    <script type="text/javascript">

        $(document).ready(function () {

            $(document).on('click', '.edit_data', function () {

                var edit_id = $(this).attr('id');

                $.ajax({

                    url: "editfees.php",

                    type: "post",

                    data: { edit_id: edit_id },

                    success: function (data) {

                        $("#info_update").html(data);

                        $("#editData").data('ajax-src', 'editfees.php').modal('show');
                        $("#editData").find('form:not([action])').attr('data-ajax-action', 'editfees.php');

                        if (typeof window.initEditFeesModal === 'function') {

                            window.initEditFeesModal();

                        }

                    }

                });

            });

            window.initEditFeesModal = function () {

                var raw = $('#efc_terms_json').val();

                if (!raw) {

                    return;

                }

                var termsBySession = {};

                try {

                    termsBySession = JSON.parse(raw);

                } catch (e) {

                    return;

                }

                var prefTerm = $('#efc_pref_term').val() || '';

                var $modal = $('#editData');

                var select2ModalOpts = {

                    width: '100%',

                    dropdownParent: $modal

                };

                function destroySelect2IfAny($el) {

                    if ($el.length && $el.hasClass('select2-hidden-accessible')) {

                        $el.select2('destroy');

                    }

                }

                function rebuildEditFeeTerms() {

                    destroySelect2IfAny($('#edit_fee_term'));

                    var $session = $('#edit_fee_session');

                    var sid = parseInt($session.find('option:selected').data('session-id'), 10) || 0;

                    var $t = $('#edit_fee_term');

                    $t.empty().append($('<option>', { value: '', text: '-- Select term --' }));

                    if (sid && termsBySession[sid]) {

                        termsBySession[sid].forEach(function (name) {

                            var opt = $('<option>').val(name).text(name);

                            if (prefTerm && name === prefTerm) {

                                opt.prop('selected', true);

                            }

                            $t.append(opt);

                        });

                    }

                    $t.trigger('change');

                    if ($.fn.select2) {

                        $t.select2(select2ModalOpts);

                    }

                }

                destroySelect2IfAny($('#edit_fee_session'));

                destroySelect2IfAny($('#edit_fee_term'));

                $('#edit_fee_session').off('change.editfees').on('change.editfees', rebuildEditFeeTerms);

                rebuildEditFeeTerms();

                if ($.fn.select2) {

                    $('#edit_fee_session').select2(select2ModalOpts);

                }

            };

        });

    </script>

</body>

</html>