<?php session_start();?>
<?php include'includes/header.php'; ?>
<?php include'includes/sidebar.php';?>
<?php include'includes/functions.php';?>
<?php include'includes/navbar.php'; ?>

<!-- This page unique styles -->
<style>
/*Core setup styles*/
.sideNav{
    height: 100%;
    /*width: 220px;*/
    position: fixed;
    z-index: 9;
}
.navbar{
    top: 0;
    position: fixed;
    z-index: 9999;
}
.the-links{
    padding-top: 10px;
}
/*.nav-links{
    height: 100%;
    overflow-y: auto;
}*/
.insider{
    margin-top: 10px;
    position: relative;
}
.card{
    height: auto;
}
.cat-pag{
    position: relative;
}
.cat-page-header{
    position: sticky;
    width: 100%;
    height: 50px;
    background:#F7F9FB; 
    top: 60px;
    right: 60px;
    z-index: 1;
}
@media(max-width: 992px){
    .insider{
        margin-top: 10px;
        padding-left: 10px;
        padding-right: 10px;
    }
    .text-sm{
        font-size: 12px;
    }
    input[type='checkbox']{
    width: 12px;
    height: 12px;
    }         
}
.card-header h5{
    font-size: 14px;
}
.cat-page-header h5{
    font-size: 14px;
}

</style>
<?php $totalSub = $pdo->query("SELECT COUNT(DISTINCT(subName)) FROM subject")->fetchColumn();?>

<div id="notification-containers" class="notification-containers"></div>
<div class="insider">
    <div class="container">
        <div class="cat-pag">
            <div class="cat-page-header d-flex justify-content-between align-items-center">
                <h5> Subject Page</h5>
                <div>
                    <button class="btn btn-sm info text-white" onclick="openModal('modal-add')">
                        <i class="fa fa-plus-circle"></i> Add New 
                    </button>

                    <button class="btn btn-sm danger text-white" onclick="handleDelete()">
                        <i class="fa fa-trash"></i> Remove 
                    </button>
                </div>
            </div>

            <div class="card mt-3">
                <div class="card-header text-left d-flex justify-content-between align-items-center">
                    <h5>All Subjects</h5>
                    <span class="badge bg-primary me-2">Total: <?= $totalSub ?></span>
                </div>
                <div class="card-body">
                    <form action="" method="POST" id="mainForm">
                        <!-- Delete Confirmation Modal -->
                        <div id="modal-delete" class="modal">
                            <div class="modal-content" style="margin-top:150px;">
                                <div class="modal-header">Delete Confirmation</div>
                                <div class="modal-body">Are you sure you want to delete the Subject(s) ?</div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" onclick="closeModal('modal-delete')">No, Cancel
                                    </button>

                                    <button type="submit" name="DeleteBtn" class="btn btn-danger">Yes, Delete</button>
                                </div>
                            </div>  
                        </div>

                        <div class="table-responsive">
                            <table id="example" class="display table table-striped table-bordered">
                                <thead>
                                    <tr>
                                        <th><input type="checkbox" id="SelectAllBoxes"></th>
                                        
                                        <th class="text-sm">Subjects</th>
                                        <th class="text-sm">Class</th>
                                        <th class="text-sm">Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $fetch = "SELECT DISTINCT(subName) FROM subject order by subjectId DESC";
                                    $stmt = $pdo->prepare($fetch);
                                    $stmt->execute();
                                    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                        
                                        $subject      = $row['subName'];

                                        $selects = "SELECT inClass, subjectId FROM subject 
                                                    WHERE subName = ?";
                                        $secePdo = $pdo->prepare($selects);
                                        $secePdo->execute([$subject]);

                                        $classList = [];
                                        while ($dataClass = $secePdo->fetch(PDO::FETCH_ASSOC)) {
                                            $classList[] = $dataClass['inClass'];
                                            $subjectId    = $dataClass['subjectId'];
                                        }
                                        $classString = implode(', ', $classList);?>
                                        <tr>
                                            <td>
                                                <input type="checkbox" name="checkBoxArray[]" 
                                                value="<?=$subjectId ?>" class='checkBoxes'>
                                            </td>
                                            <td class="text-sm"><?=$subject?></td>
                                            <td class="text-sm"><?=$classString?></td>
                                            <td class="text-center">
                                                <button type="button" class="btn btn-sm btn-primary" onclick="openModal('Edit_modal-<?= $subjectId ?>')">
                                                    <i class="fa fa-edit"></i> Edit
                                                </button>

                                            </td>
                                            <?php include'includes/edit_subj.php';?>
                                        </tr>
                                    <?php }  ?>
                                </tbody>
                            </table>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Add Modal -->
        <div id="modal-add" class="modal">
            <div class="modal-content" style="margin-top:50px;">
                <div class="modal-header text-success">Add New Subject <i class="fa fa-plus-circle"></i></div>
                <div class="modal-body">
                    <form action="" method="POST">
                        <label>Select Subject</label>
                        <div class="my-input">
                            <input type="text" name="new_sub" placeholder="Enter New Subject">
                        </div>
                        <h6 class="mt-4 mb-3">Select Class</h6>
                        <div class="box-overall">
                            <div class="class-box">
                                <?php
                                $fetchClass = "SELECT * FROM classes";
                                $classStmt = $pdo->prepare($fetchClass);
                                $classStmt->execute();
                                while ($classRow = $classStmt->fetch(PDO::FETCH_ASSOC)) {
                                    $allClass = $classRow['className'];
                                ?>
                                <label class="class-item">
                                    <input type="checkbox" name="class[]" value="<?=$allClass?>">
                                    <span><?=$allClass?></span>
                                </label>

                                <?php } ?>
                            </div>
                        </div>

                        <div class="modal-footer mt-4">
                            <button type="button" class="btn btn-sm btn-danger" onclick="closeModal('modal-add')">Cancel <i class="fa fa-cancel"></i> &times;</button>
                            <!-- Add button -->
                            <button name="add-subject" class="btn btn-sm btn-success">
                                <i class="fa fa-plus"></i> Add </button>
                        </div>
                        
                    </form>
                </div>
                
            </div>
        </div>
   
    </div>
</div>

<?php
if (isset($_POST['edit-btn'])) {
    $subj_name = $_POST['subj_name'];
    $sub_box = $_POST['subj_box'];

    // Delete first
    $sql = "DELETE FROM subject WHERE subName = ?";
    $query = $pdo->prepare($sql);
    $query->execute([$subj_name]);

    // Then Insert new items
    $sub_sql = "INSERT INTO subject(subName, inClass)VALUES(?,?)";
    $sub_query = $pdo->prepare($sub_sql);

    foreach ($sub_box as $key_sub) {
        $sub_query->execute([$subj_name, $key_sub]);
    }
    $_SESSION['message'] = "Updated Successfully";
    $_SESSION['type'] = 'success';

    ?>
    <script type="text/javascript">
      setTimeout("location.href='subject.php';", 2000);
    </script>
    <?php
}

?>

<?php
if (isset($_POST['add-subject'])) {
    $subject = $_POST['new_sub'];
    $class    = $_POST['class'];

    foreach ($class as $new_class) {
        // check if the subject exist for the class
        $checko = "SELECT * FROM subject WHERE subName = ? AND inClass = ?";
        $checksPdo = $pdo->prepare($checko);
        $checksPdo->execute([$subject, $new_class]);
        $validate = $checksPdo->rowCount();
        if ($validate == TRUE) {
            $_SESSION['message'] = 'Data Already Exist.';
            $_SESSION['type'] = 'error';
        }else{
            $saveSub = "INSERT INTO subject (subName, inClass) VALUES(?, ?)";
            $stmt = $pdo->prepare($saveSub);
            $stmt->execute([$subject, $new_class]);

            $_SESSION['message'] = 'Subject Added Successfully.';
            $_SESSION['type'] = 'success';

            ?>
            <script type="text/javascript">
              setTimeout("location.href='subject.php';", 2000);
            </script>
            <?php
        }
        
    }
}


// Handle Delete Slider
if (isset($_POST['DeleteBtn'])) {
    
    if (!empty($_POST['checkBoxArray'])) {
        foreach ($_POST['checkBoxArray'] as $subjectId) {

            // Delete from the products table
            $delete = "DELETE FROM subject WHERE subjectId = ?";
            $delStmt = $pdo->prepare($delete);
            $delStmt->execute([$subjectId]);

            $_SESSION['message'] = "Subject(s) deleted Successfully";
            $_SESSION['type'] = "success";?>
            <script type="text/javascript">
              setTimeout("location.href='subject.php';", 2000);
            </script>
        <?php }
    }
}
?>
<style type="text/css">
.class-box {
    display: flex;
    gap: 15px;
    overflow-x: auto;
    padding: 10px 0;
    scrollbar-width: thin;
}

.class-item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 6px;
    white-space: nowrap;
    background-color: #f9f9f9;
    cursor: pointer;
    transition: all 0.2s ease;
}

.class-item:hover {
    background-color: #eef5ff;
    border-color: #5a9bff;
}

.class-item input[type="checkbox"] {
    accent-color: #007bff;
}
.box-overall{
    width: 100%;
    height: auto;
}
</style>



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



<!-- DataTables & jQuery -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>


<script>
    $(document).ready(function () {
        $('#example').DataTable();
        $('#SelectAllBoxes').click(function () {
            $('.checkBoxes').prop('checked', this.checked);
        });
    });

    language: {
      emptyTable: "No Subject Added Yet. Click 'Add New' to add subject."
    }

    function openModal(id) {
        document.getElementById(id).style.display = "block";
    }

    function closeModal(id) {
        document.getElementById(id).style.display = "none";
    }

    function handleDelete() {
        const checked = document.querySelectorAll("input[name='checkBoxArray[]']:checked");
        if (checked.length === 0) {
            alert("No subject selected!");
            return;
        }
        openModal('modal-delete');
    }
   
</script>


<!-- Modal Styling -->
<style>
    .modal {
        display: none;
        position: fixed;
        z-index: 99999;
        left: 0; top: 0;
        width: 100%; height: 100%;
        overflow: auto;
        background-color: rgba(0,0,0,0.5);

    }

    .modal-content {
        background-color: #fff;
        margin: auto;
        padding: 20px;
        border-radius: 8px;
        width: 80%;
        max-width: 500px;
        animation: fadeIn 0.3s;
    }
    @media(max-width: 992px){
        .modal-content{
            width: 90%;
        }
    }

    .modal-header, .modal-footer {
        font-weight: bold;
    }

    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(-20px); }
        to { opacity: 1; transform: translateY(0); }
    }

    .single-input{
        margin-top: 10px;
    }
    .single-input label{
        font-size: 15px;
        margin-left: 20px;
        font-family: sans-serif;
    }
    .my-input input{
        width: 100%;
        border:2px solid #ccc;
        outline: none;
        font-size: 16px;
        color: 888;
        height: 50px;
        border-radius: 10px;
        padding: 15px;
        text-align: left;
       /* height: 20px;*/
    }
    .my-input select{
        width: 100%;
        border:2px solid #ccc;
        outline: none;
        font-size: 16px;
        color: 888;
        height: 50px;
        border-radius: 10px;
        padding: 10px;
       /* height: 20px;*/
    }
</style>

<!-- Notifications alert -->
<?php include'includes/notification-alert-js.php';?>

