<?php include("../database/auth_check.php"); ?>

<?php
$con = mysqli_connect("localhost","root","","WSAS");

// NEXT SCHOOL YEAR LOGIC
if(isset($_GET['next_sy'])){

    // get current active school year
    $sy_query = mysqli_query($con, "SELECT * FROM school_year WHERE is_active = 1 LIMIT 1");
    $current = mysqli_fetch_assoc($sy_query);

    if(!$current){
        header("Location: admindashboard.php");
        exit;
    }

    // Prevent switching if still 1st sem
    if($current['semester'] == '1st Semester'){
        
        exit;
    }

    $new_sy_begin = $current['sy_begin'] + 1;
    $new_sy_end   = $current['sy_end'] + 1;

    mysqli_query($con, "UPDATE school_year SET is_active = 0");

    // check if already exists
    $check = mysqli_query($con, "
        SELECT * FROM school_year 
        WHERE sy_begin = '$new_sy_begin' AND sy_end = '$new_sy_end'
        LIMIT 1
    ");

    // JANNA
    $today = date('Y-m-d');

    if(mysqli_num_rows($check) > 0){
        $existing = mysqli_fetch_assoc($check);

        // activate existing but reset to 1st semester
        mysqli_query($con, "
            UPDATE school_year  
            SET is_active = 1, semester = '1st Semester', semester_start_date = '$today'
            WHERE sy_id = {$existing['sy_id']}
        ");

    } else {

        mysqli_query($con, "
            INSERT INTO school_year 
            (sy_begin, sy_end, semester, is_active, semester_start_date)
            VALUES (
                '$new_sy_begin',
                '$new_sy_end',
                '1st Semester',
                1,
                '$today'
            )
        ");
    }

    header("Location: admindashboard.php");
    exit;
}

if(isset($_GET['switch_sem'])){
    $new_sem = $_GET['switch_sem'];
    $today = date('Y-m-d');

    // get current active school year
    $sy_query = mysqli_query($con, "SELECT * FROM school_year WHERE is_active = 1 LIMIT 1");
    $current = mysqli_fetch_assoc($sy_query);

    if(!$current){
        header("Location: admindashboard.php");
        exit;
    }

    // prevent duplicate click
    if($current['semester'] == $new_sem){
        header("Location: admindashboard.php");
        exit;
    }

    // deactivate current
    mysqli_query($con, "UPDATE school_year SET is_active = 0 WHERE sy_id = {$current['sy_id']}");

    // check if semester already exists
    $existing = mysqli_query($con, "
        SELECT * FROM school_year 
        WHERE sy_begin = '{$current['sy_begin']}' 
          AND sy_end = '{$current['sy_end']}' 
          AND semester = '{$new_sem}' 
        LIMIT 1
    ");

    $row = mysqli_fetch_assoc($existing);

    // activate if exist
    if($row){

        $sy_id = $row['sy_id'];

        mysqli_query($con, "
            UPDATE school_year 
            SET is_active = 1,
                semester_start_date = CURDATE()
            WHERE sy_id = $sy_id
        ");

    } else {

        // create new semester record if not
        mysqli_query($con, "
            INSERT INTO school_year 
            (sy_begin, sy_end, semester, is_active, semester_start_date)
            VALUES (
                '{$current['sy_begin']}',
                '{$current['sy_end']}',
                '$new_sem',
                1,
                CURDATE()
            )
        ");

        $sy_id = mysqli_insert_id($con);
    }

    // Exam Period
    $checkExam = mysqli_query($con, "
        SELECT * FROM exam_period 
        WHERE sy_id = $sy_id AND semester = '$new_sem'
    ");

    if(mysqli_num_rows($checkExam) == 0){

        mysqli_query($con, "
            INSERT INTO exam_period
            (sy_id, semester, exam_period, start_date, end_date, is_active)
            VALUES
            ($sy_id, '$new_sem', 'midterm', CURDATE(), NULL, 1),
            ($sy_id, '$new_sem', 'final', CURDATE(), NULL, 1)
        ");
    }

    header("Location: admindashboard.php");
    exit;
}

$sy_query = mysqli_query($con, "SELECT * FROM school_year WHERE is_active = 1 LIMIT 1");
$active_sy = mysqli_fetch_assoc($sy_query);

$exam_period = "none";
$active_sy_id = 0;
$current_sem = "";
$school_year_display = "No Active School Year";
$school_year_display1 = "No Active School Year";

// S.Y & Sem
if ($active_sy) {

    $active_sy_id = $active_sy['sy_id'];
    $current_sem = $active_sy['semester'];

    $school_year_display = "A.Y. {$active_sy['sy_begin']} - {$active_sy['sy_end']} ({$current_sem})";
    $school_year_display1 = "A.Y. {$active_sy['sy_begin']} - {$active_sy['sy_end']}";

    // Exam
    if (!empty($active_sy['semester_start_date'])) {

        $start = new DateTime($active_sy['semester_start_date']);
        $today = new DateTime();

        $diff = $start->diff($today);
        $month = ($diff->y * 12) + $diff->m + 1;

        if ($month == 3) {
            $exam_period = "midterm";
        } elseif ($month == 5) {
            $exam_period = "final";
        } else {
            $exam_period = "none";
        }
    }
}

$course_counts = [];
$total_students = 0;

$enroll_query = mysqli_query($con, "
    SELECT 
    e.course_id, 
    c.course_name, 
    c.course_code, 
    COUNT(*) as count
    FROM enroll_student e
    INNER JOIN admincourse c ON e.course_id = c.course_id
    WHERE e.sy_id = $active_sy_id
    GROUP BY e.course_id, c.course_name
");

if($enroll_query){
    while($row = mysqli_fetch_assoc($enroll_query)){

       $course_counts[] = [
            "course_id" => $row['course_id'],
            "course_name" => $row['course_name'],
            "course_code" => $row['course_code'],
            "count" => (int)$row['count']
        ];

        $total_students += (int)$row['count'];
    }
}
$chart_names = [];
$chart_counts = [];

foreach($course_counts as $course){
    $chart_names[] = $course['course_code'];
    $chart_counts[] = $course['count'];
}

$js_course_names = json_encode($chart_names);
$js_course_counts = json_encode($chart_counts);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE-edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - Admin</title>
    <link rel="shortcut icon" type="x-icon" href="../images/logo.png">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@24,400,0,0" />
    <link rel="stylesheet" href="../Style/navstyle.css">
    <style>
    /* Dashboard container */
    .dashboard-container {
        display: flex;
        min-height: 100vh;
        font-family: "Segoe UI", sans-serif;
        background-color: #f4f6f8;
    }

    /* Main sidebar / main content */
    .mainbar {
    margin-left: 270px;
    width: calc(100% - 270px);
    flex: 1;
    display: flex;
    flex-direction: column;
}

    .mainbar-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px 15px;
        border-bottom: 1px solid #e0e0e0;
        background-color: #f9f9f9;
        gap: 10px;
        flex-wrap: wrap;
    }

    .mainbar-header h1 {
        display: flex; 
        justify-content: space-between; 
        align-items: center;
    }

    h2 {
    font-size: 16px;
    margin-bottom: 8px;
    }

    h3 {
    font-size: 16px;
    margin-bottom: 8px;
    }

    h4 {
    font-size: 16px;
    margin-bottom: 8px;
    }

    .open-btn {
        display: inline-block;
        background-color: #4a9c3f;
        color: #fff;
        padding: 10px 18px;
        border: none;
        border-radius: 6px;
        cursor: pointer;
        font-weight: 500;
        text-decoration: none;
        transition: background-color 0.3s;
    }

    .open-btn:hover {
        background-color: #3e8c36;
    }

    /* Semester buttons row */
    .mainbar-header .semester-buttons {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
    }

    /* Main content */
    .mainbar-context {
        flex: 1;
        padding: 8px 16px;
        overflow-y: auto;
        background-color: #fff;
    }

    /* Courses container */
    .container {
        display: flex;
        flex-wrap: wrap;
        gap: 12px;
        margin-bottom: 10px;
    }

    /* Course cards */
    .courses{
        flex: 1 1 200px;
        min-width: 160px;
        max-width: 180px;
        padding: 12px;
        border-radius: 10px;
        text-align: center;
        color: white;
        font-weight: 600;
        box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        transition: transform 0.2s, box-shadow 0.2s;
    }

    .courses:hover{
        transform: translateY(-3px);
        box-shadow: 0 6px 18px rgba(0,0,0,0.15);
    }

    .label {
        display: block;
        font-size: 12px;
        margin-bottom: 8px;
    }

    .label-percent {
        font-size: 15px;
        font-weight: bold;
    }

    /* Plots container */
    .plots-container {
        display: flex;
        justify-content: center;
        align-items: flex-start;
        gap: 10px;
        flex-wrap: wrap;
        margin-top: 15px;
    }

    /* Plot cards */
    .myplot, .myplot1 {
        border-radius: 15px;
        background: rgba(255, 255, 255, 0.85);
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        display: flex;
        justify-content: center;
        align-items: center;
        backdrop-filter: blur(5px);
        padding: 12px;
    }

    .myplot {
        width: 300px;  /* was 380px */
        height: 300px;
    }

    .myplot1 {
        width: 480px;  /* was 600px */
        height: 300px;
    }

    /* Responsive adjustments */
    @media (max-width: 1024px) {
        .mainbar {
            margin-left: 0;
            margin-top: 70px;
        }

        .dashboard-container {
            flex-direction: column;
        }

        .container {
            justify-content: center;
        }

        .myplot, .myplot1 {
            width: 95%;
            height: auto;
        }
    }

    @media (max-width: 600px) {
        .mainbar-header h1 {
            font-size: 24px;
        }

        .open-btn {
            padding: 8px 14px;
            font-size: 14px;
        }

        .courses, .courses1, .courses2 {
            flex: 1 1 100%;
            max-width: 100%;
        }

        .plots-container {
            flex-direction: column;
            align-items: center;
        }
    }

    /* Left: SY info */
.sy-info .current-sy {
    margin: 0;
    font-size: 20px;
}
.sy-info .current-semester {
    font-size: 18px;
    color: #555;
}

/* Right: Actions */
.sy-actions {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    gap: 10px;
}
.manage-sy-btn {
    padding: 6px 12px;
    font-size: 13px;
}

/* Toggle wrapper */
.toggle-wrapper {
    position: relative;
    width: 60px;
    height: 30px;
}
.toggle-wrapper input {
    opacity: 0;
    position: absolute;
    width: 60px;
    height: 30px;
    cursor: pointer;
}
.toggle-wrapper label {
    display: flex;
    align-items: center;
    width: 60px;
    height: 30px;
    background: #4A9C3F;
    border-radius: 30px;
    position: relative;
    cursor: pointer;
    padding: 0 5px;
    box-sizing: border-
    box;
    transition: background-color 0.3s;
}
.toggle-ball {
    position: absolute;
    top: 3px;
    left: 3px;
    width: 24px;
    height: 24px;
    background: #fff;
    border-radius: 50%;
    transition: 0.3s;
    z-index: 2;
}
input:checked + label .toggle-ball {
    transform: translateX(30px);
}
.toggle-icon {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    font-size: 14px;
    z-index: 1;
}
.toggle-icon.sun { 
    left: 15px; 
    color: white; 
}
.toggle-icon.moon { 
    right: 15px; 
    color: white; 
}

/* Wrapper to align label and toggle horizontally */
.semester-switch-wrapper {
    display: flex;
    align-items: center;
    gap: 10px; /* space between text and toggle */
}

/* Label styling */
.switch-label {
    font-size: 14px;
    font-weight: 600;
    color: #333;
}
.toggle-wrapper input:disabled + label {
    background: #ccc;
    cursor: not-allowed;
}

.modal {
  display: none;
  position: fixed;
  z-index: 999;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.4);
}

.modal-content {
  background: white;
  width: 350px;
  margin: 12% auto;
  padding: 20px;
  border-radius: 10px;
  animation: pop 0.3s ease;
}

.close-btn {
  float: right;
  font-size: 22px;
  cursor: pointer;
}

@keyframes pop {
  from {transform: scale(0.7); opacity: 0;}
  to {transform: scale(1); opacity: 1;}
}
</style>
</head>
<body>
    <div class="dashboard-container">
        <?php include('adminnav.php'); ?>
        <aside class="mainbar">
            <div class="mainbar-header">
                
            <div class="sy-info">
                <h2 class="current-sy"><?php echo $school_year_display1; ?></h2>
                <span class="current-semester"><?php echo $current_sem ?: "No Active Semester"; ?></span>
            </div>

            <div class="sy-actions">
                <a href="javascript:void(0)" class="open-btn manage-sy-btn"
                    onclick="handleNextSY()">
                    Next School Year
                </a>

                <div class="semester-switch-wrapper">
                    <span class="switch-label">Switch Semester</span>
                    <div class="toggle-wrapper">
                        <input type="checkbox" 
                        id="semesterToggle" 
                        <?php echo ($current_sem=="2nd Semester") ? "checked" : ""; ?>>
                        <label for="semesterToggle">
                            <span class="toggle-ball"></span>
                            <span class="toggle-icon sun">1</span>
                            <span class="toggle-icon moon">2</span>
                        </label>
                    </div>
                </div>
            </div>
            </div>

            <div class="mainbar-context">
                <h2>Total Number of Students for <?php echo $school_year_display; ?>: <?php echo $total_students; ?></h2><br>
                <div class="container" id="courseContainer">
                <?php foreach($course_counts as $course): ?>
                    <a href="../view/course_student.php?course_id=<?php echo $course['course_id']; ?>" style="text-decoration:none;">
                        <div class="courses" data-course-name="<?php echo $course['course_name']; ?>">
                            <span class="label"><?php echo $course['course_name']; ?></span>
                            <span class="label-percent"><?php echo $course['count']; ?></span>
                        </div>
                    </a>
                <?php endforeach; ?>
            </div>

                <div class="plots-container">
                    <div id="myPlot" class="myplot"></div>
                    <div id="myPlot1" class="myplot1"><h1>Bar Chart: Coming Soon!</h1></div>
                </div>
            </div>
        </aside>
    </div>

    <!-- MODAL -->
        <div id="modal" class="modal">
        <div class="modal-content">
            <span class="close-btn" onclick="closeModal()">&times;</span>
            <p id="modalMessage"></p>

            <div style="margin-top:15px; text-align:right;">
            <button class="open-btn" onclick="confirmAction()">Confirm</button>
            <button class="open-btn" style="background:#999;" onclick="closeModal()">Cancel</button>
            </div>
        </div>
        </div>

    <!-- Scripts -->
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
    <script>
        document.addEventListener("DOMContentLoaded", () => {

        const xArray = <?php echo $js_course_names; ?>;
        const yArray = <?php echo $js_course_counts; ?>;

        // Generate a Plotly default color palette
        const colors = Plotly.d3.scale.category10().range();

        // Assign colors to each slice
        const data = [{
            labels: xArray,
            values: yArray,
            type: "pie",
            textinfo: "label+percent",
            textposition: "inside",
            insidetextorientation: "auto",
            textfont: { size: 14, color: "white" },
            hoverinfo: "label+percent+value",
            marker: { colors: colors.slice(0, xArray.length), line: { color: "#ffffff", width: 2 } }
        }];

        const layout = {
            showlegend: false,
            legend: { orientation: "h", y: -0.2, x: 0.5, xanchor: "center" },
            paper_bgcolor: "rgba(0,0,0,0)",
            plot_bgcolor: "rgba(0,0,0,0)",
            height: 350,
            width: 350,
            margin: { t: 50, b: 80, l: 0, r: 0 }
        };

        Plotly.newPlot("myPlot", data, layout, {displayModeBar: false}).then(() => {
            const cards = document.querySelectorAll("#courseContainer .courses");
            const pieColors = data[0].marker.colors;

            cards.forEach((card, index) => {
                if(pieColors[index]) {
                    card.style.backgroundColor = pieColors[index];
                }
            });
        });
    });
    </script>
    <script src="../Jscript/navscript.js"></script>
    <script>
    function handleNextSY(){
        <?php if($current_sem == '1st Semester'): ?>
            openModal("Finish 1st Semester first before moving to next school year.", "#");
        <?php else: ?>
            openModal("Are you sure you want to move to the next school year?", "?next_sy=1");
        <?php endif; ?>
    }

    const toggle = document.getElementById('semesterToggle');

    toggle.addEventListener('change', () => {
        let sem = toggle.checked ? '2nd Semester' : '1st Semester';

        openModal(
            `Are you sure you want to switch to ${sem}?`,
            `?switch_sem=${encodeURIComponent(sem)}`
        );

        // revert toggle until confirmed
        toggle.checked = !toggle.checked;
    });
    </script>
    <script>
        let actionUrl = "";

        function openModal(message, url){
            document.getElementById("modalMessage").innerText = message;
            actionUrl = url;
            document.getElementById("modal").style.display = "block";
        }

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

        function confirmAction(){
            window.location.href = actionUrl;
        }
        </script>
</body>
</html>