<?php
include('includes/session1.php');
include('includes/dbconnection.php');
include('includes/session_term_helper.php');
include('includes/flash.php');
error_reporting(0);

if (!isset($_SESSION['sid'])) {
    header('Location: logoutteacher.php');
    exit();
}

$teacher_id = (int) $_SESSION['sid'];
$selected_class = $_GET['class'] ?? '';
$selected_section = $_GET['section'] ?? '';

if (!$selected_class || !$selected_section) {
    flash_alert('Invalid class selection!', 'teacher_dashboard.php?tab_id=' . $tabSessionID);
    header("Location: teacher_dashboard.php?tab_id=$tabSessionID");
    exit;
    exit();
}

// Fetch active session ordered by earliest start_date

// Resolve current session and term (with fallback support)
$sessionTerm = resolveCurrentSessionTerm($con);
$currentSessionId = $sessionTerm['session_id'] ?: null;
$currentSessionName = $sessionTerm['session_name'];
$currentTermId = $sessionTerm['term_id'] ?: null;
$currentTermName = $sessionTerm['term_name'];

// Fetch students in this class
$sql = "SELECT id, studentName FROM students WHERE class = ? AND section = ? AND status < 3";
$stmt = $con->prepare($sql);
$stmt->bind_param("ss", $selected_class, $selected_section);
$stmt->execute();
$students = $stmt->get_result();
?>

<!DOCTYPE html>
<html lang="en">
<?php @include("includes/head.php"); ?>

<head>
    <style>
        .card-body {
            overflow-x: auto;
            padding: 1rem;
        }

        table {
            width: 100%;
            max-width: 100%;
            border-collapse: collapse;
            table-layout: fixed;
        }

        th,
        td {
            padding: 8px;
            border: 1px solid #ccc;
            text-align: center;
            word-wrap: break-word;
        }

        input[type="number"] {
            width: 100%;
            box-sizing: border-box;
            max-width: 60px;
        }

        @media (max-width: 768px) {

            table,
            thead,
            tbody,
            th,
            td,
            tr {
                display: block;
            }

            thead tr {
                display: none;
            }

            tr {
                margin-bottom: 1rem;
                border: 1px solid #ccc;
                border-radius: 8px;
                padding: 10px;
            }

            td {
                position: relative;
                padding-left: 50%;
                text-align: left;
                border: none;
                border-bottom: 1px solid #eee;
            }

            td::before {
                position: absolute;
                left: 10px;
                top: 50%;
                transform: translateY(-50%);
                font-weight: bold;
                white-space: nowrap;
            }

            td:nth-of-type(1)::before {
                content: "Student";
            }

            td:nth-of-type(2)::before {
                content: "Fluency";
            }

            td:nth-of-type(3)::before {
                content: "Handwriting";
            }

            td:nth-of-type(4)::before {
                content: "Lab/Workshop";
            }

            td:nth-of-type(5)::before {
                content: "Music";
            }

            td:nth-of-type(6)::before {
                content: "Sports";
            }

            td:nth-of-type(7)::before {
                content: "Punctuality";
            }

            td:nth-of-type(8)::before {
                content: "Reliability";
            }

            td:nth-of-type(9)::before {
                content: "Politeness";
            }

            td:nth-of-type(10)::before {
                content: "Charisma";
            }

            td:nth-of-type(11)::before {
                content: "Org. Ability";
            }

            td:nth-of-type(12)::before {
                content: "Self Control";
            }

            input[type="number"] {
                max-width: 100%;
            }
        }
    </style>
</head>

<body class="hold-transition sidebar-mini layout-fixed">
    <div class="wrapper">
        <?php @include("includes/headert.php"); ?>
        <?php @include("includes/sidebart.php"); ?>

        <div class="content-wrapper">
            <!-- Content Header -->

            <section class="content-header premium-header">
                <div class="container-fluid">
                    <div class="header-glass-card">
                        <div class="row align-items-center">
                            <div class="col-md-8">
                                <div class="title-section">
                                    <div class="icon-box bg-primary-gradient shadow-sm">
                                        <i class="fas fa-chart-line"></i>
                                    </div>
                                    <div>
                                        <h1 class="premium-title text-primary">
                                            Result Management
                                            <span class="premium-subtitle text-secondary">Manage Student Rating</span>
                                        </h1>
                                        <div class="mt-1">
                                            <?php if ($currentSessionName): ?>
                                                <span class="badge badge-primary mr-1">
                                                    <i class="fas fa-calendar-alt"></i>
                                                    <?= htmlspecialchars($currentSessionName) ?>
                                                </span>
                                            <?php endif; ?>
                                            <?php if ($currentTermName): ?>
                                                <span class="badge badge-success">
                                                    <i class="fas fa-bookmark"></i>
                                                    <?= htmlspecialchars($currentTermName) ?>
                                                </span>
                                            <?php else: ?>
                                                <span class="badge badge-warning">
                                                    <i class="fas fa-exclamation-triangle"></i> No active term
                                                </span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <nav aria-label="breadcrumb">
                                    <ol class="breadcrumb premium-breadcrumb">
                                        <li class="breadcrumb-item"><a href="teacher_dashboard.php"
                                                class="text-primary">Home</a></li>
                                        <li class="breadcrumb-item active" aria-current="page">Add Rating</li>
                                    </ol>
                                </nav>
                            </div>
                        </div>
                    </div>
                </div>
            </section>

            <section class="content">
                <div class="container-fluid">
                    <div class="card border-primary">
                        <div class="card-header bg-primary text-white font-weight-bold">
                            <h5 class="mb-0"><i class="fas fa-user-graduate"></i> Psychomotor & Affective Rating -
                                <?= htmlspecialchars($selected_class . " (" . $selected_section . ")") ?>
                            </h5>
                        </div>
                        <div class="card-body">
                            <form action="submit_ratings.php" method="POST">
                                <input type="hidden" name="term" value="<?= $currentTermName ?>">
                                <input type="hidden" name="session" value="<?= $currentSessionName ?>">
                                <input type="hidden" name="class" value="<?= $selected_class ?>">
                                <input type="hidden" name="section" value="<?= $selected_section ?>">

                                <table id="example1">
                                    <thead>
                                        <tr>
                                            <th>Student Name</th>
                                            <th colspan="5">Psychomotor (1–5)</th>
                                            <th colspan="6">Affective (1–5)</th>
                                        </tr>
                                        <tr>
                                            <th></th>
                                            <th>Fluency</th>
                                            <th>Handwriting</th>
                                            <th>Lab/Workshop</th>
                                            <th>Music</th>
                                            <th>Sports</th>
                                            <th>Punctuality</th>
                                            <th>Reliability</th>
                                            <th>Politeness</th>
                                            <th>Charisma</th>
                                            <th>Org. Ability</th>
                                            <th>Self Control</th>
                                        </tr>
                                    </thead>
                                    <tbody>

                                        <?php
                                        $previousRatings = [];

                                        // Fetch psychomotor data
                                        $psychomotorStmt = $con->prepare("
                                            SELECT student_id, fluency, handwriting, lab_workshops, musical_skills, sports 
                                            FROM psychomotor 
                                            WHERE term = ? AND session = ?
                                        ");
                                        $psychomotorStmt->bind_param("ss", $currentTermName, $currentSessionName);
                                        $psychomotorStmt->execute();
                                        $psychomotorResult = $psychomotorStmt->get_result();

                                        while ($row = $psychomotorResult->fetch_assoc()) {
                                            $sid = $row['student_id'];
                                            $previousRatings[$sid] = $previousRatings[$sid] ?? [];
                                            $previousRatings[$sid] = array_merge($previousRatings[$sid], $row);
                                        }

                                        // Fetch affective data
                                        $affectiveStmt = $con->prepare("
                                            SELECT student_id, punctuality, reliability, politeness_honesty, charisma, organizational_ability, self_control 
                                            FROM affective 
                                            WHERE term = ? AND session = ?
                                        ");
                                        $affectiveStmt->bind_param("ss", $currentTermName, $currentSessionName);
                                        $affectiveStmt->execute();
                                        $affectiveResult = $affectiveStmt->get_result();

                                        while ($row = $affectiveResult->fetch_assoc()) {
                                            $sid = $row['student_id'];
                                            $previousRatings[$sid] = $previousRatings[$sid] ?? [];
                                            $previousRatings[$sid] = array_merge($previousRatings[$sid], $row);
                                        }


                                        while ($row = $students->fetch_assoc()): ?>
                                            <tr class="student-row">
                                                <td><?= htmlspecialchars($row['studentName']) ?></td>
                                                <?php $id = $row['id']; ?>
                                                <!-- Psychomotor -->
                                                <?php
                                                $rating = $previousRatings[$id] ?? [];
                                                ?>
                                                <td><input type="number" name="fluency[<?= $id ?>]" min="1" max="5"
                                                        value="<?= $rating['fluency'] ?? '' ?>"></td>
                                                <td><input type="number" name="handwriting[<?= $id ?>]" min="1" max="5"
                                                        value="<?= $rating['handwriting'] ?? '' ?>"></td>
                                                <td><input type="number" name="lab_workshops[<?= $id ?>]" min="1" max="5"
                                                        value="<?= $rating['lab_workshops'] ?? '' ?>"></td>
                                                <td><input type="number" name="musical_skills[<?= $id ?>]" min="1" max="5"
                                                        value="<?= $rating['musical_skills'] ?? '' ?>"></td>
                                                <td><input type="number" name="sports[<?= $id ?>]" min="1" max="5"
                                                        value="<?= $rating['sports'] ?? '' ?>"></td>
                                                <!-- Affective -->
                                                <td><input type="number" name="punctuality[<?= $id ?>]" min="1" max="5"
                                                        value="<?= $rating['punctuality'] ?? '' ?>"></td>
                                                <td><input type="number" name="reliability[<?= $id ?>]" min="1" max="5"
                                                        value="<?= $rating['reliability'] ?? '' ?>"></td>
                                                <td><input type="number" name="politeness_honesty[<?= $id ?>]" min="1"
                                                        max="5" value="<?= $rating['politeness_honesty'] ?? '' ?>"></td>
                                                <td><input type="number" name="charisma[<?= $id ?>]" min="1" max="5"
                                                        value="<?= $rating['charisma'] ?? '' ?>"></td>
                                                <td><input type="number" name="organizational_ability[<?= $id ?>]" min="1"
                                                        max="5" value="<?= $rating['organizational_ability'] ?? '' ?>"></td>
                                                <td><input type="number" name="self_control[<?= $id ?>]" min="1" max="5"
                                                        value="<?= $rating['self_control'] ?? '' ?>"></td>

                                            </tr>
                                        <?php endwhile; ?>
                                    </tbody>
                                </table>

                                <div class="text-center">
                                    <button type="submit" class="btn btn-primary mt-3">Submit Ratings <i
                                            class="fas fa-paper-plane"></i></button>
                                </div>
                                <div class="form-group text-center">
                                    <small class="text-danger" style="font-size: 1rem;">
                                        <i class="fas fa-info-circle text-primary"></i>
                                        Note: Ratings submitted are saved per page
                                    </small>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </section>
        </div>

        <?php @include("includes/footer.php"); ?>
    </div>
    <?php @include("includes/foot.php"); ?>


</body>

</html>