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

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();
}


// Verify teacher is class teacher
$stmt = $con->prepare("
    SELECT 1 FROM teacher_assignments ta
    JOIN class_section cs ON ta.class_id = cs.id
    WHERE ta.teacher_id = ? AND ta.is_class_teacher = 1
      AND cs.class = ? AND cs.section = ?
    LIMIT 1
");
$stmt->bind_param("iss", $teacher_id, $selected_class, $selected_section);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    flash_alert('You are not assigned as a class teacher for this class!', 'teacher_dashboard.php?tab_id=' . $tabSessionID);
    header("Location: teacher_dashboard.php?tab_id=$tabSessionID");
    exit;
    exit();
}
$stmt->close();


// Fetch current session and term IDs
$stResult = resolveCurrentSessionTerm($con);
$currentSessionId = $stResult['session_id'];
$currentSessionName = $stResult['session_name'];
$currentTermId = $stResult['term_id'];
$currentTermName = $stResult['term_name'];

// Map label variables used later in psychomotor/affective queries
$currentSessionLabel = $currentSessionName;
$currentTermLabel = $currentTermName;


// Utility function (must be defined before use)
function mysqli_prepare_execute($con, $query, $types = "", $params = [])
{
    $stmt = $con->prepare($query);
    if ($types && $params) {
        $stmt->bind_param($types, ...$params);
    }
    $stmt->execute();
    return $stmt->get_result();
}

// Get total students
list($total_students) = mysqli_fetch_row(
    mysqli_prepare_execute($con, "
        SELECT COUNT(*) FROM students 
        WHERE class = ? AND section = ? AND status < 3
    ", "ss", [$selected_class, $selected_section])
);

// Fetch subject teachers and submission status
$teachers_stmt = $con->prepare("
    SELECT 
        ta.teacher_id, 
        CONCAT(t.name, ' ', t.lastname) AS teacher_name, 
        sub.subject_name,
        
        -- Count of submitted results for that subject (mid-term rule)
        (
            SELECT COUNT(DISTINCT r.student_id) 
            FROM results r
            INNER JOIN students s ON s.id = r.student_id
            WHERE r.class = ? 
              AND r.section = ? 
              AND r.session_id = ? 
              AND r.term_id = ? 
              AND r.teacher_id = ta.teacher_id 
              AND r.subject = sub.subject_name
              AND s.status < 3
                AND (
                ((r.test_score IS NOT NULL AND (r.test_score != '' OR r.test_score = 0)) OR r.test_absent = 1) 
                AND ((r.class_performance IS NOT NULL AND (r.class_performance != '' OR r.class_performance = 0)) OR r.class_performance_absent = 1) 
                AND ((r.weekly_assessment IS NOT NULL AND (r.weekly_assessment != '' OR r.weekly_assessment = 0)) OR r.weekly_assessment_absent = 1)
                )

        ) AS submitted_count,
        
        -- Total students offering the subject
        (
            SELECT COUNT(*) 
            FROM subject_allocations sa
            INNER JOIN students s ON s.id = sa.student_id
            WHERE sa.class = ? 
              AND sa.section = ? 
              AND sa.subject_name = sub.subject_name
              AND s.status < 3
        ) AS subject_total
        
    FROM teacher_assignments ta
    JOIN tblusers t ON ta.teacher_id = t.id
    JOIN subjectcombination sub ON ta.subject_id = sub.id
    JOIN class_section cs 
        ON sub.class = cs.class 
       AND sub.section = cs.section
    WHERE cs.class = ? 
      AND cs.section = ? 
      AND ta.subject_id IS NOT NULL
");

$teachers_stmt->bind_param(
    "ssssssss",
    $selected_class,
    $selected_section,
    $currentSessionId,
    $currentTermId,
    $selected_class,
    $selected_section,
    $selected_class,
    $selected_section
);

$teachers_stmt->execute();
$teachers_result = $teachers_stmt->get_result();


$submitted_teachers = [];
$missing_teachers = [];

while ($row = $teachers_result->fetch_assoc()) {
    // Use subject_total from the main query (already filters status < 3)
    $subject_total = (int) $row['subject_total'];

    // Compare submitted count to active students offering the subject
    if ((int) $row['submitted_count'] >= $subject_total) {
        $submitted_teachers[] = $row;
    } else {
        $missing_teachers[] = $row;
    }
}
$teachers_stmt->close();

$all_teachers_submitted = empty($missing_teachers);

// Fetch students if all submissions are done
$students = [];
if ($all_teachers_submitted) {
    $students_stmt = $con->prepare("
        SELECT 
            r.student_id, 
            s.studentName, 
            SUM(r.total_score) AS overall_score, 
            r.remarks, 
            r.status
        FROM results r
        JOIN students s ON r.student_id = s.id
        WHERE r.class = ? AND r.section = ? 
          AND r.session_id = ? AND r.term_id = ?
        GROUP BY r.student_id
    ");
    $students_stmt->bind_param("ssii", $selected_class, $selected_section, $currentSessionId, $currentTermId);
    $students_stmt->execute();
    $students_result = $students_stmt->get_result();
    $students = $students_result->fetch_all(MYSQLI_ASSOC);
    $students_stmt->close();
}



// Get total number of distinct subjects for the class/section/session/term
$subject_count_result = mysqli_fetch_row(mysqli_query($con, "
    SELECT COUNT(DISTINCT subject) FROM results 
    WHERE class = '$selected_class' 
    AND section = '$selected_section' 
    AND session_id = '$currentSessionId' 
    AND term_id = '$currentTermId'
"));
$total_subjects = $subject_count_result[0] ?? 1; // fallback to avoid division by zero
$max_score_per_subject = 100;
$total_max_score = $total_subjects * $max_score_per_subject;

// Remark generator
function generateRemark($percentage)
{
    if ($percentage >= 75) {
        return 'Excellent performance. Keep it up!';
    } elseif ($percentage >= 60) {
        return 'Very good results. You can aim higher!';
    } elseif ($percentage >= 50) {
        return 'Good effort. You can do better!';
    } elseif ($percentage >= 40) {
        return 'Fair results. Try to work harder!';
    } else {
        return 'Poor performance. Serious improvement needed!';
    }
}


// Handle POST remarks submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['remarks'])) {
    foreach ($_POST['remarks'] as $student_id => $remark) {
        $remark = trim($remark);
        $status = 'Submitted to Admin';

        $update_stmt = $con->prepare("
                UPDATE results
                SET remarks = ?, status = ?
                WHERE student_id = ? AND class = ? AND section = ?
                  AND session_id = ? AND term_id = ?
            ");
        $update_stmt->bind_param("ssissii", $remark, $status, $student_id, $selected_class, $selected_section, $currentSessionId, $currentTermId);
        $update_stmt->execute();
        $update_stmt->close();
    }

    flash_alert('Remarks updated successfully!');
    header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? 'javascript:history.back()'));
    exit;
    exit();
}


// Check approval status
list($pending_count) = mysqli_fetch_row(
    mysqli_prepare_execute($con, "
        SELECT COUNT(DISTINCT student_id) 
        FROM results
        WHERE class = ? AND section = ? 
          AND session_id = ? AND term_id = ?
          AND status != 'Approved'
    ", "ssii", [$selected_class, $selected_section, $currentSessionId, $currentTermId])
);

$all_approved = ($pending_count == 0);


// 🔹 Step 1: Get psychomotor columns
$psychColsRes = mysqli_query($con, "SHOW COLUMNS FROM psychomotor");
$psychCols = [];
while ($col = mysqli_fetch_assoc($psychColsRes)) {
    if (!in_array($col['Field'], ['id', 'student_id', 'term', 'session'])) {
        $psychCols[] = $col['Field'];
    }
}

// 🔹 Step 2: Get affective columns
$affColsRes = mysqli_query($con, "SHOW COLUMNS FROM affective");
$affCols = [];
while ($col = mysqli_fetch_assoc($affColsRes)) {
    if (!in_array($col['Field'], ['id', 'student_id', 'term', 'session'])) {
        $affCols[] = $col['Field'];
    }
}

// 🔹 Step 3: Build query (join both tables)
$sql = "
    SELECT 
        s.id, 
        s.studentName,
        p.*,
        a.*
    FROM students s
    LEFT JOIN psychomotor p
      ON p.student_id = s.id
     AND (TRIM(p.session) = ? OR TRIM(p.session) = CAST(? AS CHAR))
     AND (TRIM(p.term)    = ? OR TRIM(p.term)    = CAST(? AS CHAR))
    LEFT JOIN affective a
      ON a.student_id = s.id
     AND (TRIM(a.session) = ? OR TRIM(a.session) = CAST(? AS CHAR))
     AND (TRIM(a.term)    = ? OR TRIM(a.term)    = CAST(? AS CHAR))
    WHERE s.class = ? AND s.section = ? AND s.status < 3
";

$stmt = $con->prepare($sql);
$stmt->bind_param(
    "ssssssssss",
    $currentSessionLabel,
    $currentSessionId,
    $currentTermLabel,
    $currentTermId,
    $currentSessionLabel,
    $currentSessionId,
    $currentTermLabel,
    $currentTermId,
    $selected_class,
    $selected_section
);

$stmt->execute();
$result = $stmt->get_result();

// 🔹 Step 4: Build missing list
$missing_ratings = [];
while ($row = $result->fetch_assoc()) {
    $missingTraits = [];

    foreach ($psychCols as $col) {
        if (!isset($row[$col]) || $row[$col] === '' || $row[$col] == 0) {
            $missingTraits[] = "Psychomotor: " . ucfirst($col);
        }
    }

    foreach ($affCols as $col) {
        if (!isset($row[$col]) || $row[$col] === '' || $row[$col] == 0) {
            $missingTraits[] = "Affective: " . ucfirst($col);
        }
    }

    if (!empty($missingTraits)) {
        $missing_ratings[] = [
            'student_id' => $row['id'],
            'studentName' => $row['studentName'],
            'missing' => $missingTraits  // store as array, not string
        ];
    }
}
$all_ratings_submitted = empty($missing_ratings);

?>

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

<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 (Page 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-clipboard-list"></i>
                                    </div>
                                    <div>
                                        <h1 class="premium-title text-primary">
                                            Result Management
                                            <span class="premium-subtitle text-secondary">Manage Results</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 Remarks -
                                            <?= htmlspecialchars($selected_class) ?>
                                            (<?= htmlspecialchars($selected_section) ?>)</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">
                            <h5 class="mb-0"><i class="fas fa-user-graduate"></i> Manage Student Remarks -
                                <?= htmlspecialchars($selected_class . " " . $selected_section) ?></h5>
                        </div>

                        <div class="card-body">

                            <?php if (!$all_teachers_submitted): ?>
                                    <div class="alert alert-danger">
                                        <strong>Heads Up!</strong> Some subject teachers haven't submitted results yet. You
                                        can't add remarks until they do.
                                    </div>
                                    <!-- ✅ Submitted Teachers Table -->
                                    <?php if (!empty($submitted_teachers) || !empty($missing_teachers)): ?>
                                            <div class="card-header bg-primary text-white">
                                                <h5 class="mb-0">
                                                    <i class="fas fa-users"></i> Teachers End of the Term Result Submission Status
                                                    <small class="text-white">
                                                        (<?= count($submitted_teachers) ?> Completed,
                                                        <?= count($missing_teachers) ?> Pending)
                                                    </small>
                                                </h5>
                                            </div>
                                            <div class="card-body">
                                                <table class="table table-bordered table-hover">
                                                    <thead class="thead-light bg-primary text-white">
                                                        <tr>
                                                            <th>Teacher</th>
                                                            <th>Subject</th>
                                                            <th>Total Students</th>
                                                            <th>Submitted</th>
                                                            <th>Remaining</th>
                                                            <th>Status</th>
                                                            <th>Notify</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php foreach (array_merge($submitted_teachers, $missing_teachers) as $teacher): ?>
                                                                <?php
                                                                $submitted = (int) $teacher['submitted_count'];
                                                                $total = (int) $teacher['subject_total'];
                                                                $remaining = max(0, $total - $submitted);

                                                                if ($submitted === 0) {
                                                                    $status = '<span class="badge badge-danger">Not Submitted</span>';
                                                                } elseif ($submitted < $total) {
                                                                    $status = '<span class="badge badge-warning">In Progress</span>';
                                                                } else {
                                                                    $status = '<span class="badge badge-success">Completed</span>';
                                                                }
                                                                ?>
                                                                <tr>
                                                                    <td><?= htmlspecialchars($teacher['teacher_name']) ?></td>
                                                                    <td><?= htmlspecialchars($teacher['subject_name']) ?></td>
                                                                    <td><?= $total ?></td>
                                                                    <td><?= $submitted ?></td>
                                                                    <td><?= $remaining ?></td>
                                                                    <td><?= $status ?></td>
                                                                    <td>
                                                                        <?php if ($remaining > 0): ?>
                                                                                <form action="send_notification.php" method="POST" class="d-inline">
                                                                                    <input type="hidden" name="teacher_id"
                                                                                        value="<?= (int) $teacher['teacher_id'] ?>">
                                                                                    <input type="hidden" name="class"
                                                                                        value="<?= htmlspecialchars($selected_class) ?>">
                                                                                    <input type="hidden" name="section"
                                                                                        value="<?= htmlspecialchars($selected_section) ?>">
                                                                                    <button class="btn btn-sm btn-outline-primary">Send
                                                                                        Reminder</button>
                                                                                </form>
                                                                        <?php else: ?>
                                                                                <span class="text-success">✓ Completed</span>
                                                                        <?php endif; ?>
                                                                    </td>
                                                                </tr>
                                                        <?php endforeach; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                    <?php endif; ?>
                            <?php elseif (!$all_ratings_submitted): ?>
                                    <div class="alert alert-warning">
                                        <i class="fas fa-exclamation-circle"></i>
                                        Please complete <b>Psychomotor</b> and <b>Affective</b> ratings for all students before
                                        adding remarks.
                                    </div>

                                    <?php if (!empty($missing_ratings)): ?>
                                            <div class="card mt-3">
                                                <div class="card-header bg-danger text-white">
                                                    <i class="fas fa-frown"></i> Students with Missing Ratings
                                                    (<?= count($missing_ratings) ?>)
                                                </div>
                                                <div class="card-body table-responsive">
                                                    <table class="table table-bordered table-striped" id="example1">
                                                        <thead>
                                                            <tr>
                                                                <th>#</th>
                                                                <th>Student Name</th>
                                                                <th>Missing Ratings</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <?php foreach ($missing_ratings as $index => $student): ?>
                                                                    <tr>
                                                                        <td><?= $index + 1 ?></td>
                                                                        <td><?= htmlspecialchars($student['studentName']) ?></td>
                                                                        <td class="text-danger">
                                                                            <?= htmlspecialchars(implode(', ', $student['missing'])) ?></td>
                                                                    </tr>
                                                            <?php endforeach; ?>
                                                        </tbody>
                                                    </table>
                                                </div>
                                            </div>
                                    <?php endif; ?>


                            <?php else: ?>
                                    <?php if (empty($students)): ?>
                                            <div class="alert alert-info">
                                                No students found for this class and arm.
                                            </div>
                                    <?php else: ?>
                                            <!-- ✅ Show remarks table -->
                                            <form method="POST">
                                                <table class="table table-striped table-hover mt-4">
                                                    <thead>
                                                        <tr>
                                                            <th>#</th>
                                                            <th>Student Name</th>
                                                            <th>Total Score</th>
                                                            <th>Percentage</th>
                                                            <th>Auto Remark</th>
                                                            <th>Edit Remark</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php foreach ($students as $index => $student):
                                                            $overall_score = (float) $student['overall_score'];

                                                            // Calculate subject count for this student
                                                            $student_subjects_stmt = $con->prepare("
                            SELECT COUNT(DISTINCT subject) 
                            FROM results
                            WHERE student_id = ? AND class = ? AND section = ?
                              AND session_id = ? AND term_id = ?
                        ");
                                                            $student_subjects_stmt->bind_param("issii", $student['student_id'], $selected_class, $selected_section, $currentSessionId, $currentTermId);
                                                            $student_subjects_stmt->execute();
                                                            $student_subjects_stmt->bind_result($student_subject_count);
                                                            $student_subjects_stmt->fetch();
                                                            $student_subjects_stmt->close();

                                                            $student_max_score = $student_subject_count * $max_score_per_subject;
                                                            $percentage = $student_max_score > 0 ? round(($overall_score / $student_max_score) * 100, 2) : 0;

                                                            $generated_remark = generateRemark($percentage);
                                                            $existing_remark = trim($student['remarks'] ?? '');
                                                            ?>
                                                                <tr>
                                                                    <td><?= $index + 1 ?></td>
                                                                    <td><?= htmlspecialchars($student['studentName']) ?></td>
                                                                    <td><?= $overall_score ?></td>
                                                                    <td><?= $percentage ?>%</td>
                                                                    <td><em><?= $generated_remark ?></em></td>
                                                                    <td>
                                                                        <textarea name="remarks[<?= (int) $student['student_id'] ?>]" rows="2"
                                                                            class="form-control"><?= htmlspecialchars($existing_remark ?: $generated_remark) ?></textarea>
                                                                    </td>
                                                                </tr>
                                                        <?php endforeach; ?>
                                                    </tbody>
                                                </table>

                                                <?php if (!$all_approved): ?>
                                                        <div class="text-center mt-4">
                                                            <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Submit
                                                                Remarks</button>
                                                        </div>
                                                <?php else: ?>
                                                        <div class="alert alert-success text-center">
                                                            All remarks have been approved!
                                                        </div>
                                                <?php endif; ?>
                                            </form>
                                    <?php endif; ?>
                            <?php endif; ?>

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

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

    <script>
        document.querySelectorAll('.send-reminder-btn').forEach(button => {
            button.addEventListener('click', function (e) {
                e.preventDefault();
                button.disabled = true;
                button.innerText = 'Sending...';

                fetch('send_notification.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: `teacher_id=${button.dataset.teacherId}&class=${encodeURIComponent(button.dataset.class)}&section=${encodeURIComponent(button.dataset.section)}`
                })
                    .then(response => response.text())
                    .then(data => {
                        button.innerText = 'Sent ✅';
                        button.classList.remove('btn-outline-primary');
                        button.classList.add('btn-success');
                    })
                    .catch(err => {
                        console.error(err);
                        button.innerText = 'Failed ❌';
                        button.classList.remove('btn-outline-primary');
                        button.classList.add('btn-danger');
                    });
            });
        });
    </script>

</body>

</html>