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

$alert = "";

/* ---------- ADD CLASS ---------- */
if (isset($_POST['add_class'])) {
    $class = $conn->real_escape_string($_POST['class']);
    $num   = (int)$_POST['class_numeric'];

    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($_POST['section']);

    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;
        
        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 {
        $alert = "<div class='alert alert-danger'>Please select at least one section</div>";
    }
}

/* ---------- UPDATE STATUS (COMMON) ---------- */
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>Class Master</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-list {
        list-style: none;
        padding: 0;
        margin: 0;
    }
    .section-list li {
        display: inline-block;
        background: #e9ecef;
        padding: 3px 10px;
        margin: 2px;
        border-radius: 3px;
        font-size: 0.9em;
    }
</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 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" required>
                    </div>
                    <div class="col-md-4">
                        <input name="class_numeric" type="number" class="form-control" placeholder="Numeric" 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 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" 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>

<div class="panel">
<div class="panel-heading"><h5>Map Class & Section (Multiple 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()):
?>
<option value="<?= $c['class_id'] ?>"><?= $c['class'] ?> (<?= $c['class_numeric'] ?>)</option>
<?php endwhile; ?>
</select>
</div>

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

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

<!-- ================= DISPLAY TABLES ================= -->
<div class="row">
    <!-- Classes Table -->
    <div class="col-md-4">
        <div class="panel">
            <div class="panel-heading">
                <h5>Classes <span class="badge"><?= $conn->query("SELECT COUNT(*) FROM classes")->fetch_row()[0] ?></span></h5>
            </div>
            <div class="panel-body">
                <table class="table table-bordered table-striped">
                    <thead>
                        <tr>
                            <th>Class</th>
                            <th>Numeric</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php
                    $q = $conn->query("SELECT * FROM classes ORDER BY class_numeric");
                    while ($row = $q->fetch_assoc()):
                    ?>
                    <tr>
                        <td><?= htmlspecialchars($row['class']) ?></td>
                        <td><?= $row['class_numeric'] ?></td>
                        <td><?= $row['status'] ? 'Active' : 'Inactive' ?></td>
                        <td>
                            <a class="btn btn-xs <?= $row['status'] ? 'btn-warning' : 'btn-success' ?>"
                               href="?type=class&id=<?= $row['class_id'] ?>&toggle=<?= $row['status'] ? 0 : 1 ?>">
                                <?= $row['status'] ? 'Disable' : 'Enable' ?>
                            </a>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <!-- Sections Table -->
    <div class="col-md-4">
        <div class="panel">
            <div class="panel-heading">
                <h5>Sections <span class="badge"><?= $conn->query("SELECT COUNT(*) FROM sections")->fetch_row()[0] ?></span></h5>
            </div>
            <div class="panel-body">
                <table class="table table-bordered table-striped">
                    <thead>
                        <tr>
                            <th>Section</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php
                    $q = $conn->query("SELECT * FROM sections ORDER BY section_name");
                    while ($row = $q->fetch_assoc()):
                    ?>
                    <tr>
                        <td><?= htmlspecialchars($row['section_name']) ?></td>
                        <td><?= $row['status'] ? 'Active' : 'Inactive' ?></td>
                        <td>
                            <a class="btn btn-xs <?= $row['status'] ? 'btn-warning' : 'btn-success' ?>"
                               href="?type=section&id=<?= $row['section_id'] ?>&toggle=<?= $row['status'] ? 0 : 1 ?>">
                                <?= $row['status'] ? 'Disable' : 'Enable' ?>
                            </a>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <!-- Class-Section Mapping Summary -->
    <div class="col-md-4">
        <div class="panel">
            <div class="panel-heading">
                <h5>Class-Section Summary <span class="badge"><?= $conn->query("SELECT COUNT(*) FROM class_section WHERE status=1")->fetch_row()[0] ?></span></h5>
            </div>
            <div class="panel-body">
                <table class="table table-bordered table-striped">
                    <thead>
                        <tr>
                            <th>Class</th>
                            <th>Sections</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php
                    $q = $conn->query("
                        SELECT c.class_id, c.class, c.class_numeric, 
                               GROUP_CONCAT(s.section_name ORDER BY s.section_name SEPARATOR ', ') as sections_list
                        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
                        WHERE c.status = 1
                        GROUP BY c.class_id
                        ORDER BY c.class_numeric
                    ");
                    while ($row = $q->fetch_assoc()):
                    ?>
                    <tr>
                        <td><?= htmlspecialchars($row['class']) ?></td>
                        <td>
                            <?php if ($row['sections_list']): ?>
                                <ul class="section-list">
                                <?php
                                $sections = explode(', ', $row['sections_list']);
                                foreach ($sections as $section):
                                    if (!empty(trim($section))):
                                ?>
                                    <li><?= htmlspecialchars($section) ?></li>
                                <?php
                                    endif;
                                endforeach;
                                ?>
                                </ul>
                            <?php else: ?>
                                <span class="text-muted">No sections mapped</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Detailed Mapping Table -->
<div class="panel">
<div class="panel-heading"><h5>Detailed Class–Section Mapping</h5></div>
<div class="panel-body">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Class</th>
<th>Section</th>
<th>Status</th>
<th>Action</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 ?>">
<?= $row['status'] ? 'Disable' : 'Enable' ?>
</a>
</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</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/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 for multi-select
    $('#sectionSelect').select2({
        placeholder: "Select multiple sections",
        allowClear: true,
        width: '100%'
    });
    
    // Initialize select2 for class select
    $('#classSelect').select2({
        placeholder: "Select a class",
        allowClear: true,
        width: '100%'
    });
});
</script>
</body>
</html>