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

$alert = "";

/* ---------- ADD CLASS ---------- */
if (isset($_POST['add_class'])) {
    $class = $conn->real_escape_string(trim($_POST['class']));
    $num   = (int)$_POST['class_numeric'];
    
    // Check if class already exists
    $check = $conn->query("SELECT * FROM classes WHERE class = '$class' OR class_numeric = $num");
    
    if ($check->num_rows > 0) {
        $alert = "<div class='alert alert-warning'>Class or numeric value already exists</div>";
    } else {
        if ($conn->query("INSERT INTO classes (class, class_numeric, status) VALUES ('$class', $num, 1)")) {
            $alert = "<div class='alert alert-success'>Class added successfully</div>";
        } else {
            $alert = "<div class='alert alert-danger'>Failed to add class</div>";
        }
    }
}

/* ---------- ADD SECTION ---------- */
if (isset($_POST['add_section'])) {
    $section = $conn->real_escape_string(trim($_POST['section']));
    
    // Check if section already exists
    $check = $conn->query("SELECT * FROM sections WHERE section_name = '$section'");
    
    if ($check->num_rows > 0) {
        $alert = "<div class='alert alert-warning'>Section already exists</div>";
    } else {
        if ($conn->query("INSERT INTO sections (section_name, status) VALUES ('$section', 1)")) {
            $alert = "<div class='alert alert-success'>Section added successfully</div>";
        } else {
            $alert = "<div class='alert alert-danger'>Failed to add section</div>";
        }
    }
}

/* ---------- MAP CLASS SECTION ---------- */
if (isset($_POST['map_cs'])) {
    $cid = (int)$_POST['class_id'];
    
    if (isset($_POST['section_ids']) && is_array($_POST['section_ids'])) {
        $successCount = 0;
        $errorCount = 0;
        
        // First, disable all existing mappings for this class
        $conn->query("UPDATE class_section SET status = 0 WHERE class_id = $cid");
        
        foreach ($_POST['section_ids'] as $section_id) {
            $sid = (int)$section_id;
            
            $checkQuery = $conn->query("SELECT * FROM class_section WHERE class_id = $cid AND section_id = $sid");
            if ($checkQuery->num_rows > 0) {
                // Update existing mapping
                $update = $conn->query("UPDATE class_section SET status = 1 WHERE class_id = $cid AND section_id = $sid");
                if ($update) {
                    $successCount++;
                } else {
                    $errorCount++;
                }
            } else {
                // Insert new mapping
                $insert = $conn->query("INSERT INTO class_section (class_id, section_id, status) VALUES ($cid, $sid, 1)");
                if ($insert) {
                    $successCount++;
                } else {
                    $errorCount++;
                }
            }
        }
        
        if ($errorCount == 0) {
            $alert = "<div class='alert alert-success'>Successfully mapped $successCount section(s) to class</div>";
        } else {
            $alert = "<div class='alert alert-warning'>Mapped $successCount section(s), $errorCount failed</div>";
        }
    } else {
        // If no sections selected, disable all mappings for this class
        $conn->query("UPDATE class_section SET status = 0 WHERE class_id = $cid");
        $alert = "<div class='alert alert-info'>All sections removed from class</div>";
    }
}

/* ---------- EDIT CLASS ---------- */
if (isset($_POST['edit_class'])) {
    $id = (int)$_POST['class_id'];
    $class = $conn->real_escape_string(trim($_POST['edit_class_name']));
    $num = (int)$_POST['edit_class_numeric'];
    
    $check = $conn->query("SELECT * FROM classes WHERE (class = '$class' OR class_numeric = $num) AND class_id != $id");
    
    if ($check->num_rows > 0) {
        $alert = "<div class='alert alert-warning'>Class or numeric value already exists</div>";
    } else {
        if ($conn->query("UPDATE classes SET class = '$class', class_numeric = $num WHERE class_id = $id")) {
            $alert = "<div class='alert alert-success'>Class updated successfully</div>";
        } else {
            $alert = "<div class='alert alert-danger'>Failed to update class</div>";
        }
    }
}

/* ---------- EDIT SECTION ---------- */
if (isset($_POST['edit_section'])) {
    $id = (int)$_POST['section_id'];
    $section = $conn->real_escape_string(trim($_POST['edit_section_name']));
    
    $check = $conn->query("SELECT * FROM sections WHERE section_name = '$section' AND section_id != $id");
    
    if ($check->num_rows > 0) {
        $alert = "<div class='alert alert-warning'>Section already exists</div>";
    } else {
        if ($conn->query("UPDATE sections SET section_name = '$section' WHERE section_id = $id")) {
            $alert = "<div class='alert alert-success'>Section updated successfully</div>";
        } else {
            $alert = "<div class='alert alert-danger'>Failed to update section</div>";
        }
    }
}

/* ---------- DELETE CLASS ---------- */
if (isset($_GET['delete_class'])) {
    $id = (int)$_GET['delete_class'];
    
    // Check if class has any mappings
    $check = $conn->query("SELECT * FROM class_section WHERE class_id = $id AND status = 1");
    if ($check->num_rows > 0) {
        $alert = "<div class='alert alert-warning'>Cannot delete class. Remove all section mappings first.</div>";
    } else {
        if ($conn->query("DELETE FROM classes WHERE class_id = $id")) {
            $alert = "<div class='alert alert-success'>Class deleted successfully</div>";
        } else {
            $alert = "<div class='alert alert-danger'>Failed to delete class</div>";
        }
    }
}

/* ---------- DELETE SECTION ---------- */
if (isset($_GET['delete_section'])) {
    $id = (int)$_GET['delete_section'];
    
    // Check if section has any mappings
    $check = $conn->query("SELECT * FROM class_section WHERE section_id = $id AND status = 1");
    if ($check->num_rows > 0) {
        $alert = "<div class='alert alert-warning'>Cannot delete section. Remove all class mappings first.</div>";
    } else {
        if ($conn->query("DELETE FROM sections WHERE section_id = $id")) {
            $alert = "<div class='alert alert-success'>Section deleted successfully</div>";
        } else {
            $alert = "<div class='alert alert-danger'>Failed to delete section</div>";
        }
    }
}

/* ---------- UPDATE STATUS ---------- */
if (isset($_GET['toggle']) && isset($_GET['type'])) {
    $id   = (int)$_GET['id'];
    $val  = (int)$_GET['toggle'];
    $type = $_GET['type'];

    $tables = [
        'class'   => 'classes',
        'section' => 'sections',
        'map'     => 'class_section'
    ];

    if (isset($tables[$type])) {
        $pk = ($type == 'map') ? 'id' : $type . '_id';
        if ($conn->query("UPDATE {$tables[$type]} SET status=$val WHERE $pk=$id")) {
            $alert = "<div class='alert alert-info'>Status updated</div>";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Manage Classes & Sections</title>
<link rel="stylesheet" href="css/bootstrap.min.css" media="screen" >
<link rel="stylesheet" href="css/font-awesome.min.css" media="screen" >
<link rel="stylesheet" href="css/animate-css/animate.min.css" media="screen" >
<link rel="stylesheet" href="css/lobipanel/lobipanel.min.css" media="screen" >
<link rel="stylesheet" href="css/prism/prism.css" media="screen" >
<link rel="stylesheet" href="css/select2/select2.min.css" >
<link rel="stylesheet" href="css/main.css" media="screen" >
<script src="js/modernizr/modernizr.min.js"></script>
<style>
    .multi-select {
        min-height: 100px;
    }
    .section-badge {
        display: inline-block;
        background: #e9ecef;
        padding: 3px 10px;
        margin: 2px;
        border-radius: 20px;
        font-size: 0.85em;
        color: #495057;
    }
    .section-badge.active {
        background: #28a745;
        color: white;
    }
    .action-buttons .btn {
        margin: 2px;
    }
    .modal-lg {
        max-width: 600px;
    }
    .mapped-count {
        display: inline-block;
        background: #17a2b8;
        color: white;
        border-radius: 50%;
        width: 20px;
        height: 20px;
        line-height: 20px;
        text-align: center;
        font-size: 0.8em;
        margin-left: 5px;
    }
</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">

<?= $alert; ?>

<!-- ================= ADD FORMS ================= -->
<div class="row">
    <div class="col-md-6">
        <div class="panel">
            <div class="panel-heading">
                <h5>Add New Class</h5>
            </div>
            <div class="panel-body">
                <form method="POST" class="row">
                    <div class="col-md-6">
                        <input name="class" class="form-control" placeholder="Class Name (e.g., Class 10)" required>
                    </div>
                    <div class="col-md-4">
                        <input name="class_numeric" type="number" min="1" max="12" class="form-control" placeholder="Numeric (1-12)" required>
                    </div>
                    <div class="col-md-2">
                        <button name="add_class" class="btn btn-primary btn-block">Add</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <div class="col-md-6">
        <div class="panel">
            <div class="panel-heading">
                <h5>Add New Section</h5>
            </div>
            <div class="panel-body">
                <form method="POST" class="row">
                    <div class="col-md-8">
                        <input name="section" class="form-control" placeholder="Section Name (e.g., A, B, Science)" required>
                    </div>
                    <div class="col-md-4">
                        <button name="add_section" class="btn btn-success btn-block">Add</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- ================= MAP CLASS & SECTION ================= -->
<div class="panel">
    <div class="panel-heading">
        <h5>Map Class & Sections</h5>
    </div>
    <div class="panel-body">
        <form method="POST" class="row">
            <div class="col-md-4">
                <select name="class_id" class="form-control" required id="classSelect">
                    <option value="">Select Class</option>
                    <?php
                    $r = $conn->query("SELECT * FROM classes WHERE status=1 ORDER BY class_numeric");
                    while ($c = $r->fetch_assoc()):
                        // Get count of active sections for this class
                        $sectionCount = $conn->query("SELECT COUNT(*) FROM class_section WHERE class_id = {$c['class_id']} AND status = 1")->fetch_row()[0];
                    ?>
                    <option value="<?= $c['class_id'] ?>" data-sections="<?= $sectionCount ?>">
                        <?= htmlspecialchars($c['class']) ?> (<?= $c['class_numeric'] ?>)
                        <?php if($sectionCount > 0): ?><span class="mapped-count"><?= $sectionCount ?></span><?php endif; ?>
                    </option>
                    <?php endwhile; ?>
                </select>
            </div>

            <div class="col-md-6">
                <select name="section_ids[]" class="form-control multi-select" multiple="multiple" id="sectionSelect">
                    <?php
                    $r = $conn->query("SELECT * FROM sections WHERE status=1 ORDER BY section_name");
                    while ($s = $r->fetch_assoc()):
                    ?>
                    <option value="<?= $s['section_id'] ?>"><?= htmlspecialchars($s['section_name']) ?></option>
                    <?php endwhile; ?>
                </select>
                <small class="text-muted">Hold Ctrl/Cmd to select multiple sections</small>
            </div>

            <div class="col-md-2">
                <button name="map_cs" class="btn btn-info btn-block">Update Mapping</button>
            </div>
        </form>
    </div>
</div>

<!-- ================= CLASSES TABLE ================= -->
<div class="panel">
    <div class="panel-heading">
        <h5>Manage Classes 
            <span class="badge badge-primary"><?= $conn->query("SELECT COUNT(*) FROM classes")->fetch_row()[0] ?></span>
            <small class="pull-right text-muted">Total: <?= $conn->query("SELECT COUNT(*) FROM classes")->fetch_row()[0] ?> classes</small>
        </h5>
    </div>
    <div class="panel-body">
        <div class="table-responsive">
            <table class="table table-bordered table-striped table-hover">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Class Name</th>
                        <th>Numeric</th>
                        <th>Sections</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                <?php
                $q = $conn->query("
                    SELECT c.*, 
                           GROUP_CONCAT(DISTINCT s.section_name ORDER BY s.section_name SEPARATOR ', ') as sections,
                           COUNT(DISTINCT cs.section_id) as section_count
                    FROM classes c
                    LEFT JOIN class_section cs ON c.class_id = cs.class_id AND cs.status = 1
                    LEFT JOIN sections s ON cs.section_id = s.section_id AND s.status = 1
                    GROUP BY c.class_id
                    ORDER BY c.class_numeric
                ");
                
                while ($row = $q->fetch_assoc()):
                ?>
                <tr>
                    <td><?= $row['class_id'] ?></td>
                    <td><?= htmlspecialchars($row['class']) ?></td>
                    <td><?= $row['class_numeric'] ?></td>
                    <td>
                        <?php if ($row['sections']): ?>
                            <div>
                                <?php
                                $sections = explode(', ', $row['sections']);
                                foreach ($sections as $section):
                                    if (!empty(trim($section))):
                                ?>
                                <span class="section-badge"><?= htmlspecialchars($section) ?></span>
                                <?php
                                    endif;
                                endforeach;
                                ?>
                            </div>
                            <small class="text-muted"><?= $row['section_count'] ?> section(s)</small>
                        <?php else: ?>
                            <span class="text-muted">No sections</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <span class="label label-<?= $row['status'] ? 'success' : 'danger' ?>">
                            <?= $row['status'] ? 'Active' : 'Inactive' ?>
                        </span>
                    </td>
                    <td class="action-buttons">
                        <button class="btn btn-xs btn-primary edit-class-btn" 
                                data-id="<?= $row['class_id'] ?>"
                                data-name="<?= htmlspecialchars($row['class']) ?>"
                                data-numeric="<?= $row['class_numeric'] ?>">
                            <i class="fa fa-edit"></i> Edit
                        </button>
                        
                        <a class="btn btn-xs <?= $row['status'] ? 'btn-warning' : 'btn-success' ?>"
                           href="?type=class&id=<?= $row['class_id'] ?>&toggle=<?= $row['status'] ? 0 : 1 ?>">
                            <i class="fa fa-power-off"></i> <?= $row['status'] ? 'Disable' : 'Enable' ?>
                        </a>
                        
                        <a class="btn btn-xs btn-danger delete-btn" 
                           href="?delete_class=<?= $row['class_id'] ?>"
                           onclick="return confirm('Are you sure you want to delete this class?')">
                            <i class="fa fa-trash"></i> Delete
                        </a>
                    </td>
                </tr>
                <?php endwhile; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- ================= SECTIONS TABLE ================= -->
<div class="panel">
    <div class="panel-heading">
        <h5>Manage Sections 
            <span class="badge badge-success"><?= $conn->query("SELECT COUNT(*) FROM sections")->fetch_row()[0] ?></span>
            <small class="pull-right text-muted">Total: <?= $conn->query("SELECT COUNT(*) FROM sections")->fetch_row()[0] ?> sections</small>
        </h5>
    </div>
    <div class="panel-body">
        <div class="table-responsive">
            <table class="table table-bordered table-striped table-hover">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Section Name</th>
                        <th>Mapped Classes</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                <?php
                $q = $conn->query("
                    SELECT s.*, 
                           GROUP_CONCAT(DISTINCT c.class ORDER BY c.class_numeric SEPARATOR ', ') as classes,
                           COUNT(DISTINCT cs.class_id) as class_count
                    FROM sections s
                    LEFT JOIN class_section cs ON s.section_id = cs.section_id AND cs.status = 1
                    LEFT JOIN classes c ON cs.class_id = c.class_id AND c.status = 1
                    GROUP BY s.section_id
                    ORDER BY s.section_name
                ");
                
                while ($row = $q->fetch_assoc()):
                ?>
                <tr>
                    <td><?= $row['section_id'] ?></td>
                    <td><?= htmlspecialchars($row['section_name']) ?></td>
                    <td>
                        <?php if ($row['classes']): ?>
                            <div>
                                <?php
                                $classes = explode(', ', $row['classes']);
                                foreach ($classes as $class):
                                    if (!empty(trim($class))):
                                ?>
                                <span class="section-badge active"><?= htmlspecialchars($class) ?></span>
                                <?php
                                    endif;
                                endforeach;
                                ?>
                            </div>
                            <small class="text-muted"><?= $row['class_count'] ?> class(es)</small>
                        <?php else: ?>
                            <span class="text-muted">No classes</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <span class="label label-<?= $row['status'] ? 'success' : 'danger' ?>">
                            <?= $row['status'] ? 'Active' : 'Inactive' ?>
                        </span>
                    </td>
                    <td class="action-buttons">
                        <button class="btn btn-xs btn-primary edit-section-btn" 
                                data-id="<?= $row['section_id'] ?>"
                                data-name="<?= htmlspecialchars($row['section_name']) ?>">
                            <i class="fa fa-edit"></i> Edit
                        </button>
                        
                        <a class="btn btn-xs <?= $row['status'] ? 'btn-warning' : 'btn-success' ?>"
                           href="?type=section&id=<?= $row['section_id'] ?>&toggle=<?= $row['status'] ? 0 : 1 ?>">
                            <i class="fa fa-power-off"></i> <?= $row['status'] ? 'Disable' : 'Enable' ?>
                        </a>
                        
                        <a class="btn btn-xs btn-danger delete-btn" 
                           href="?delete_section=<?= $row['section_id'] ?>"
                           onclick="return confirm('Are you sure you want to delete this section?')">
                            <i class="fa fa-trash"></i> Delete
                        </a>
                    </td>
                </tr>
                <?php endwhile; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- ================= DETAILED MAPPING TABLE ================= -->
<div class="panel">
    <div class="panel-heading">
        <h5>Class-Section Mappings 
            <span class="badge badge-info"><?= $conn->query("SELECT COUNT(*) FROM class_section WHERE status=1")->fetch_row()[0] ?></span>
            <small class="pull-right text-muted">Active mappings: <?= $conn->query("SELECT COUNT(*) FROM class_section WHERE status=1")->fetch_row()[0] ?></small>
        </h5>
    </div>
    <div class="panel-body">
        <div class="table-responsive">
            <table class="table table-bordered table-striped table-hover">
                <thead>
                    <tr>
                        <th>Mapping ID</th>
                        <th>Class</th>
                        <th>Section</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                <?php
                $q = $conn->query("
                    SELECT cs.id, c.class, s.section_name, cs.status
                    FROM class_section cs
                    JOIN classes c ON cs.class_id=c.class_id
                    JOIN sections s ON cs.section_id=s.section_id
                    ORDER BY c.class_numeric, s.section_name
                ");
                
                while ($row = $q->fetch_assoc()):
                ?>
                <tr>
                    <td><?= $row['id'] ?></td>
                    <td><?= htmlspecialchars($row['class']) ?></td>
                    <td><?= htmlspecialchars($row['section_name']) ?></td>
                    <td>
                        <span class="label label-<?= $row['status'] ? 'success' : 'danger' ?>">
                            <?= $row['status'] ? 'Active' : 'Inactive' ?>
                        </span>
                    </td>
                    <td>
                        <a class="btn btn-xs <?= $row['status'] ? 'btn-warning' : 'btn-success' ?>"
                           href="?type=map&id=<?= $row['id'] ?>&toggle=<?= $row['status'] ? 0 : 1 ?>">
                            <i class="fa fa-power-off"></i> <?= $row['status'] ? 'Disable' : 'Enable' ?>
                        </a>
                    </td>
                </tr>
                <?php endwhile; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

</div>
</div>
</div>
</div>
</div>

<!-- Edit Class Modal -->
<div class="modal fade" id="editClassModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Class</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="class_id" id="editClassId">
                    <div class="form-group">
                        <label>Class Name</label>
                        <input type="text" name="edit_class_name" id="editClassName" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Numeric Value</label>
                        <input type="number" name="edit_class_numeric" id="editClassNumeric" class="form-control" min="1" max="12" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" name="edit_class" class="btn btn-primary">Update Class</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Section Modal -->
<div class="modal fade" id="editSectionModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Section</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="section_id" id="editSectionId">
                    <div class="form-group">
                        <label>Section Name</label>
                        <input type="text" name="edit_section_name" id="editSectionName" class="form-control" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" name="edit_section" class="btn btn-primary">Update Section</button>
                </div>
            </form>
        </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/iscroll/iscroll.js"></script>
<script src="js/prism/prism.js"></script>
<script src="js/select2/select2.min.js"></script>
<script src="js/main.js"></script>
<script>
$(document).ready(function() {
    // Initialize select2
    $('#sectionSelect').select2({
        placeholder: "Select sections (leave empty to remove all)",
        allowClear: true,
        width: '100%'
    });
    
    $('#classSelect').select2({
        placeholder: "Select a class",
        allowClear: true,
        width: '100%'
    });
    
    // When class is selected, automatically select its mapped sections
    $('#classSelect').on('change', function() {
        var classId = $(this).val();
        if (classId) {
            $.ajax({
                url: 'ajax/get_class_sections.php',
                type: 'GET',
                data: { class_id: classId },
                success: function(response) {
                    try {
                        var sections = JSON.parse(response);
                        $('#sectionSelect').val(sections).trigger('change');
                    } catch(e) {
                        console.error('Error parsing response:', e);
                    }
                }
            });
        } else {
            $('#sectionSelect').val(null).trigger('change');
        }
    });
    
    // Edit Class button click
    $('.edit-class-btn').click(function() {
        var id = $(this).data('id');
        var name = $(this).data('name');
        var numeric = $(this).data('numeric');
        
        $('#editClassId').val(id);
        $('#editClassName').val(name);
        $('#editClassNumeric').val(numeric);
        
        $('#editClassModal').modal('show');
    });
    
    // Edit Section button click
    $('.edit-section-btn').click(function() {
        var id = $(this).data('id');
        var name = $(this).data('name');
        
        $('#editSectionId').val(id);
        $('#editSectionName').val(name);
        
        $('#editSectionModal').modal('show');
    });
    
    // Confirm before delete
    $('.delete-btn').click(function(e) {
        if (!confirm('Are you sure? This action cannot be undone.')) {
            e.preventDefault();
        }
    });
    
    // Auto-dismiss alerts after 5 seconds
    setTimeout(function() {
        $('.alert').fadeOut('slow');
    }, 5000);
});
</script>
</body>
</html>