<?php
session_start();
error_reporting(0);
include('includes/config.php');

// Check login
if (strlen($_SESSION['alogin']) == 0) {
    header('location:index.php');
    exit;
}

//  Delete Degree
if (isset($_GET['del'])) {
    $id = intval($_GET['del']);

    // Step 1: Check if this degree is used in tblbooks
    $checkSql = "SELECT COUNT(*) FROM tblbooks WHERE degree_id = :id";
    $checkQuery = $dbh->prepare($checkSql);
    $checkQuery->bindParam(':id', $id, PDO::PARAM_INT);
    $checkQuery->execute();
    $count = $checkQuery->fetchColumn();

    if ($count > 0) {
        // Step 2: Soft delete
        $sql = "UPDATE tbldegree SET is_deleted = 1 WHERE degree_id = :id";
        $query = $dbh->prepare($sql);
        $query->bindParam(':id', $id, PDO::PARAM_INT);
        $query->execute();
        $_SESSION['delmsg'] = "Degree deleted successfully";
    } else {
        // Step 3: Hard delete
        $sql = "DELETE FROM tbldegree WHERE degree_id = :id";
        $query = $dbh->prepare($sql);
        $query->bindParam(':id', $id, PDO::PARAM_INT);
        $query->execute();
        $_SESSION['delmsg'] = "Degree deleted successfully";
    }

    header('location:manage-degrees.php');
    exit;
}

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

<head>
    <meta charset="UTF-8">
    <title>Manage Degrees | Library System</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="../<?php echo $_SESSION['logo']; ?>">

    <!-- ✅ Bootstrap 5 -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- ✅ DataTables Bootstrap 5 -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">

    <style>
        .square-card {
            width: 100%;
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
            border-radius: 5px;
        }

        .flash-message {
            max-width: 600px;
            margin: 0 auto 15px;
        }

        .table-wrapper {
            overflow-x: auto;
            padding: 10px;
        }

        .col-md-12 h5 {
            color:   #0d6efd;
            font-size: 20px;
        }

        .btn+.btn {
            margin-left: 5px;
        }
    </style>
</head>

<body>
    <div class="d-flex flex-column min-vh-100">
        <?php include('includes/header.php'); ?>

        <div class="main-content flex-grow-1">
            <div class="row pad-botm mb-4">
                <div class="col-md-12">
                    <h5 class="header-line" style="color:#0d6efd;">MANAGE DEGREES</h5>
                </div>
            </div>

            <!-- Flash Messages -->
            <div class="row justify-content-center">
                <div class="col-md-8" id="flash-container">
                    <?php
                    foreach (['error', 'msg', 'updatemsg', 'delmsg'] as $type):
                        if (!empty($_SESSION[$type])): ?>
                            <div class="alert alert-<?php echo ($type == 'error') ? 'danger' : 'success'; ?> flash-message">
                                <strong><?php echo ucfirst($type); ?> :</strong> <?php echo htmlentities($_SESSION[$type]); ?>
                            </div>
                            <?php $_SESSION[$type] = ""; ?>
                            <?php
                        endif;
                    endforeach;
                    ?>
                </div>
            </div>

            <!-- Degrees Table -->
            <div class="card square-card mb-5">
                <div class="card-header bg-secondary text-white d-flex justify-content-between align-items-center">
                    <span><i class="fa fa-graduation-cap mr-2"></i> Degrees List</span>
                    <button class="btn btn-light btn-sm text-dark shadow-sm rounded-pill px-3"
                        onclick="openDegreeModal()">
                        <i class="fa fa-plus-circle"></i><b> ADD</b>
                    </button>
                </div>

                <div class="card-body table-wrapper">
                    <table id="degreesTable" class="table table-bordered table-hover table-sm text-dark">
                        <thead class="table-theme-header">
                            <tr>
                                <th>#</th>
                                <th>Degree Name</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $sql = "SELECT * FROM tbldegree WHERE is_deleted=0 ORDER BY degree_id DESC";
                            $query = $dbh->prepare($sql);
                            $query->execute();
                            $results = $query->fetchAll(PDO::FETCH_OBJ);
                            $cnt = 1;
                            // if ($query->rowCount() > 0) {
                            foreach ($results as $result) {
                                ?>
                                <tr>
                                    <td><?= htmlentities($cnt++) ?></td>
                                    <td><?= htmlentities($result->degree_name) ?></td>
                                    <td>
                                        <button class="btn btn-sm btn-info"
                                            onclick="editDegree(<?= $result->degree_id ?>,'<?= htmlentities($result->degree_name) ?>')">
                                            <i class="fa fa-edit"></i> Edit
                                        </button>
                                        <!-- <a href="manage-degrees.php?del=<?= $result->degree_id ?>"
                                            onclick="return confirm('Are you sure you want to delete this degree?');"
                                            class="btn btn-sm btn-danger">
                                            <i class="fa fa-trash"></i> Delete
                                        </a> -->
                                    </td>
                                </tr>
                                <?php
                                //     }
                                // } else {
                                //     echo "<tr><td colspan='3' class='text-center text-muted'>No degrees found</td></tr>";
                            }
                            ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Degree Modal -->
            <div class="modal fade" id="degreeModal" tabindex="-1" role="dialog">
                <div class="modal-dialog modal-dialog-centered modal-md">
                    <div class="modal-content">
                        <div class="modal-header bg-primary text-white">
                            <h5 class="modal-title" id="degreeModalTitle">Add Degree</h5>
                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"
                                aria-label="Close"></button>
                        </div>
                        <form id="degreeForm">
                            <div class="modal-body">
                                <input type="hidden" id="degreeId" name="degreeId">
                                <div class="form-group mb-3">
                                    <label>Degree Name</label>
                                    <input type="text" id="degreeName" name="degreeName" class="form-control" required>
                                </div>
                            </div>
                            <div class="modal-footer justify-content-center py-2">
                                <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">
                                    <i class="fa fa-times"></i> Cancel
                                </button>
                                <button type="submit" id="saveBtn" class="btn btn-success btn-sm">
                                    <i class="fa fa-save"></i> Save
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

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

    <!-- ✅ Scripts -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

    <script>
        $(document).ready(function () {
            $('#degreesTable').DataTable({
                pageLength: 10,
                responsive: true,
                language: { search: "🔍 Search degrees:" }
            });
        });

        // ✅ Open Add Modal
        function openDegreeModal() {
            $("#degreeModalTitle").text("Add Degree");
            $("#degreeForm")[0].reset();
            $("#degreeId").val("");
            const modal = new bootstrap.Modal(document.getElementById("degreeModal"));
            modal.show();
        }

        // ✅ Open Edit Modal
        function editDegree(id, degreeName) {
            $("#degreeModalTitle").text("Edit Degree");
            $("#degreeId").val(id);
            $("#degreeName").val(degreeName);
            const modal = new bootstrap.Modal(document.getElementById("degreeModal"));
            modal.show();
        }

        // ✅ AJAX Save/Update Degree
        $("#degreeForm").on("submit", function (e) {
            e.preventDefault();

            $.ajax({
                url: "save-degree.php",
                type: "POST",
                data: $(this).serialize(),
                dataType: "json",
                success: function (response) {
                    // Remove any existing flash message
                    $("#flash-container .flash-message").remove();

                    // Determine alert type
                    const alertType = response.status === "success" ? "success" : "danger";

                    // Add flash message dynamically
                    $("#flash-container").prepend(`
                <div class="alert alert-${alertType} flash-message text-center">
                    <strong>${response.status === "success" ? "Success!" : "Error!"}</strong> ${response.message}
                </div>
            `);

                    // Auto fade
                    setTimeout(() => $(".flash-message").fadeOut(), 3000);

                    // If success → close modal and reload
                    if (response.status === "success") {
                        $("#degreeModal").modal("hide");
                        setTimeout(() => location.reload(), 1500);
                    }
                },
                error: function () {
                    $("#flash-container .flash-message").remove();
                    $("#flash-container").prepend(`
                <div class="alert alert-danger flash-message text-center">
                    ⚠️ Something went wrong! Please try again.
                </div>
            `);
                    setTimeout(() => $(".flash-message").fadeOut(), 3000);
                }
            });
        });
    </script>

</body>

</html>