<?php

include('includes/session1.php');

error_reporting(0);

include('includes/dbconnection.php');
include('includes/flash.php');
include('includes/session_term_helper.php');



if (!isset($_SESSION['sid'])) {

    header('location:logoutteacher.php');

    exit();

}



$teacher_id = $_SESSION['sid'];



if (!isset($_GET['subject']) || !isset($_GET['class']) || !isset($_GET['section'])) {

    flash_alert('Invalid request!', 'teacher_dashboard.php?tab_id=' . $tabSessionID);
    header("Location: teacher_dashboard.php?tab_id=$tabSessionID");
    exit;

    exit();

}



$subject_name = urldecode($_GET['subject']);

$class_name = urldecode($_GET['class']);

$section = urldecode($_GET['section']);



// 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'];



// Verify teacher assignment

$verify_stmt = $con->prepare("

    SELECT COUNT(*) FROM teacher_assignments ta

    JOIN subjectcombination s ON ta.subject_id = s.id

    JOIN class_section c ON c.class = s.Class AND c.section = ?

    WHERE ta.teacher_id = ? AND s.Subject_name = ? AND c.class = ?

");

$verify_stmt->bind_param("siss", $section, $teacher_id, $subject_name, $class_name);

$verify_stmt->execute();

$verify_stmt->bind_result($isAssigned);

$verify_stmt->fetch();

$verify_stmt->close();



if ($isAssigned == 0) {

    flash_alert('You are not assigned to this subject!', 'teacher_dashboard.php?tab_id=' . $tabSessionID);
    header("Location: teacher_dashboard.php?tab_id=$tabSessionID");
    exit;

    exit();

}



// Fetch students and their existing scores based on session and term

// Fetch students and their existing scores including absence flags

$students_stmt = $con->prepare("

    SELECT 

        s.id, 

        s.studentName, 

        r.test_score, 

        r.class_performance, 

        r.weekly_assessment, 

        r.exam_score, 

        r.total_score, 

        r.status,

        r.status_test,

        r.test_absent,

        r.class_performance_absent,

        r.weekly_assessment_absent,

        r.exam_absent

    FROM subject_allocations sa

    JOIN students s ON sa.student_id = s.id

    LEFT JOIN results r ON r.student_id = s.id 

        AND r.subject = ? 

        AND r.class = ? 

        AND r.session_id = ? 

        AND r.term_id = ?

    WHERE sa.subject_name = ? 

      AND sa.class = ? 

      AND sa.section = ?

      AND s.status < 3

");

$students_stmt->bind_param(

    "ssiisss",

    $subject_name,

    $class_name,

    $currentSessionId,

    $currentTermId,

    $subject_name,

    $class_name,

    $section

);

$students_stmt->execute();

$students_result = $students_stmt->get_result();

$students = $students_result->fetch_all(MYSQLI_ASSOC);





// Count the total number of students in the class

$total_students_stmt = $con->prepare("SELECT COUNT(*) FROM students WHERE class = ? AND section = ?");

$total_students_stmt->bind_param("ss", $class_name, $section);

$total_students_stmt->execute();

$total_students_stmt->bind_result($total_students);

$total_students_stmt->fetch();

$total_students_stmt->close();



// Count the number of students who have already had results entered

$entered_results_query = "

    SELECT COUNT(DISTINCT student_id) 

    FROM results 

    WHERE subject = ? 

    AND class = ? 

    AND session_id = ? 

    AND term_id = ?

";

$entered_results_stmt = $con->prepare($entered_results_query);

$entered_results_stmt->bind_param("ssii", $subject_name, $class_name, $currentSessionId, $currentTermId);

$entered_results_stmt->execute();

$entered_results_stmt->bind_result($students_with_results);

$entered_results_stmt->fetch();

$entered_results_stmt->close();

// Processing POST request to save scores

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    function parseScoreField($field, $absentFlag)
    {

        if ($absentFlag)
            return null;

        if (isset($field) && $field !== '') {

            return is_numeric($field) ? floatval($field) : null;

        }

        return null;

    }



    // Build a whitelist of valid student IDs fetched for this teacher's subject/class/section

    $valid_student_ids = array_map('intval', array_column($students, 'id'));



    foreach ($_POST['scores'] as $student_id => $data) {

        // Security: reject any student_id not in the server-fetched list

        if (!in_array((int) $student_id, $valid_student_ids, true)) {

            continue;

        }



        $test_absent = isset($data['test_absent']) ? 1 : 0;

        $class_performance_absent = isset($data['class_performance_absent']) ? 1 : 0;

        $weekly_assessment_absent = isset($data['weekly_assessment_absent']) ? 1 : 0;

        $exam_absent = isset($data['exam_absent']) ? 1 : 0;



        $test_score = parseScoreField($data['test'] ?? null, $test_absent);

        $class_performance = parseScoreField($data['class_performance'] ?? null, $class_performance_absent);

        $weekly_assessment = parseScoreField($data['weekly_assessment'] ?? null, $weekly_assessment_absent);

        $exam_score = parseScoreField($data['exam'] ?? null, $exam_absent);



        // Check if result already exists

        $check_stmt = $con->prepare("SELECT id, status FROM results WHERE student_id = ? AND subject = ? AND class = ? AND session_id = ? AND term_id = ?");

        $check_stmt->bind_param("issii", $student_id, $subject_name, $class_name, $currentSessionId, $currentTermId);

        $check_stmt->execute();

        $check_stmt->store_result();

        $check_stmt->bind_result($result_id, $status);

        $check_stmt->fetch();



        if ($check_stmt->num_rows > 0) {

            if ($status === 'Approved') {

                $check_stmt->close();

                continue; // skip editing if already approved

            }



            // --- UPDATE EXISTING RECORD ---

            $fields = [];

            $params = [];

            $types = "";



            if (!$test_absent) {

                $fields[] = "test_score = ?";

                $params[] = $test_score;

                $types .= "i";

            } else {

                $fields[] = "test_score = NULL"; // clear old score

            }





            if (!$class_performance_absent) {

                $fields[] = "class_performance = ?";

                $params[] = $class_performance;

                $types .= "i";

            } else {

                $fields[] = "class_performance = NULL"; // clear old score

            }



            if (!$weekly_assessment_absent) {

                $fields[] = "weekly_assessment = ?";

                $params[] = $weekly_assessment;

                $types .= "i";

            } else {

                $fields[] = "weekly_assessment = NULL"; // clear old score

            }



            if (!$exam_absent) {

                $fields[] = "exam_score = ?";

                $params[] = $exam_score;

                $types .= "i";

            } else {

                $fields[] = "exam_score = NULL"; // clear old score

            }





            // Add fixed fields

            $fields[] = "status = 'Remarks Pending'";

            $fields[] = "test_absent = ?";

            $fields[] = "class_performance_absent = ?";

            $fields[] = "weekly_assessment_absent = ?";

            $fields[] = "exam_absent = ?";



            $params[] = $test_absent;

            $params[] = $class_performance_absent;

            $params[] = $weekly_assessment_absent;

            $params[] = $exam_absent;



            $types .= "iiii";



            $params[] = $result_id;

            $types .= "i";



            $sql = "UPDATE results SET " . implode(", ", $fields) . " WHERE id = ?";

            $update_stmt = $con->prepare($sql);

            $update_stmt->bind_param($types, ...$params);

            $update_stmt->execute();

            $update_stmt->close();

        } else {

            // --- INSERT NEW RECORD ---

            $columns = ["student_id", "subject", "class", "section", "session_id", "term_id", "teacher_id", "status"];

            $placeholders = ["?", "?", "?", "?", "?", "?", "?", "?"];

            $types = "isssiiis";

            $params = [$student_id, $subject_name, $class_name, $section, $currentSessionId, $currentTermId, $teacher_id, "Remarks Pending"];



            if (!$test_absent) {

                $columns[] = "test_score";

                $placeholders[] = "?";

                $types .= "i";

                $params[] = $test_score;

            }

            if (!$class_performance_absent) {

                $columns[] = "class_performance";

                $placeholders[] = "?";

                $types .= "i";

                $params[] = $class_performance;

            }

            if (!$weekly_assessment_absent) {

                $columns[] = "weekly_assessment";

                $placeholders[] = "?";

                $types .= "i";

                $params[] = $weekly_assessment;

            }

            if (!$exam_absent) {

                $columns[] = "exam_score";

                $placeholders[] = "?";

                $types .= "i";

                $params[] = $exam_score;

            }



            // Absence flags

            $columns[] = "test_absent";

            $placeholders[] = "?";

            $types .= "i";

            $params[] = $test_absent;



            $columns[] = "class_performance_absent";

            $placeholders[] = "?";

            $types .= "i";

            $params[] = $class_performance_absent;



            $columns[] = "weekly_assessment_absent";

            $placeholders[] = "?";

            $types .= "i";

            $params[] = $weekly_assessment_absent;



            $columns[] = "exam_absent";

            $placeholders[] = "?";

            $types .= "i";

            $params[] = $exam_absent;



            $sql = "INSERT INTO results (" . implode(", ", $columns) . ") VALUES (" . implode(", ", $placeholders) . ")";

            $insert_stmt = $con->prepare($sql);

            $insert_stmt->bind_param($types, ...$params);

            $insert_stmt->execute();

            $insert_stmt->close();

        }



        $check_stmt->close();

    }



    // Final check to update global status if needed

    if ($students_with_results == $total_students) {

        $update_status_query = "

            UPDATE results 

            SET status = 'Remarks Pending' 

            WHERE subject = ? 

            AND class = ? 

            AND session_id = ? 

            AND term_id = ?

        ";

        $update_status_stmt = $con->prepare($update_status_query);

        $update_status_stmt->bind_param("ssii", $subject_name, $class_name, $currentSessionId, $currentTermId);

        $update_status_stmt->execute();

        $update_status_stmt->close();

    }



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

    exit();

}



// Check if all remarks are already approved

$all_approved = true;

foreach ($students as $student) {

    if ($student['status'] !== 'Approved') {

        $all_approved = false;

        break;

    }

}



?>



<!DOCTYPE html>

<html lang="en">

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

<style>
    .card {

        border-radius: 10px;

        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);

    }



    .card-header {

        font-size: 1.2rem;

        font-weight: bold;

    }



    .btn-submit {

        background-color: #28a745;

        color: white;

        font-weight: bold;

    }
</style>



<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">Add Results -
                                                <?= htmlspecialchars($subject_name) ?></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 Results -
                                            <?= htmlspecialchars($subject_name) ?></li>

                                    </ol>

                                </nav>

                            </div>

                        </div>

                    </div>

                </div>

            </section>





            <section class="content">

                <div class="container-fluid">

                    <div class="row">

                        <div class="col-md-12">

                            <div class="card shadow-sm border-0">

                                <div class="card-header bg-primary text-white">

                                    <h5 class="mb-0"><i class="fas fa-book"></i> Add Results for
                                        <?= htmlspecialchars($class_name) ?> - <?= htmlspecialchars($section) ?></h5>

                                </div>

                                <div class="card-body">

                                    <form method="post">

                                        <table id="example11" class="table table-bordered table-hover table-striped">

                                            <thead>

                                                <tr>

                                                    <th>Student Name</th>

                                                    <th>C.A. Test (10)</th>

                                                    <th>Class Ex. & Projects (15)</th>

                                                    <th>Assignment (5)</th>

                                                    <th>Exam Score (70)</th>

                                                    <th>Total Score (100)</th>

                                                </tr>

                                            </thead>

                                            <tbody>

                                                <?php if (empty($students)): ?>

                                                        <tr>

                                                            <td colspan="7" class="text-center text-danger font-weight-bold">

                                                                No student assigned for this subject. Please contact the class
                                                                teacher.

                                                            </td>

                                                        </tr>

                                                <?php else: ?>

                                                        <?php foreach ($students as $student): ?>

                                                                <?php $status = $student['status'] ?? '';

                                                                $status_test = $student['status'] ?? '';



                                                                $readonly_all = ($status === 'Approved') ? 'readonly' : '';

                                                                $readonly_test = ($status === 'Approved' || $status_test === 'Approved') ? 'readonly' : '';

                                                                ?>

                                                                <tr>

                                                                    <td><?php echo $student['studentName']; ?></td>



                                                                    <!-- 1st C.A Test -->

                                                                    <!-- 1st C.A Test -->

                                                                    <td>

                                                                        <div class="form-group mb-2">

                                                                            <input type="number"
                                                                                name="scores[<?= $student['id']; ?>][test]"
                                                                                value="<?= $student['test_score']; ?>"
                                                                                class="form-control" min="0" max="10"
                                                                                placeholder="0 - 10" <?= $readonly_test ?>>

                                                                            <div class="form-group-append mt-1">

                                                                                <input type="checkbox"
                                                                                    name="scores[<?= $student['id']; ?>][test_absent]"
                                                                                    value="1" <?= (!empty($student['test_absent'])) ? 'checked' : ''; ?>                 <?= $readonly_test ?>> Absent

                                                                            </div>

                                                                        </div>

                                                                    </td>





                                                                    <!-- Class Performance -->

                                                                    <td>

                                                                        <div class="form-group mb-2">

                                                                            <input type="number"
                                                                                name="scores[<?php echo $student['id']; ?>][class_performance]"
                                                                                value="<?php echo $student['class_performance']; ?>"
                                                                                class="form-control" min="0" max="15"
                                                                                placeholder="0 - 15" <?= $readonly_all ?>>

                                                                            <div class="form-group-append mt-1">

                                                                                <input type="checkbox"
                                                                                    name="scores[<?php echo $student['id']; ?>][class_performance_absent]"
                                                                                    value="1" <?php echo (!empty($student['class_performance_absent'])) ? 'checked' : ''; ?>                 <?= $readonly_all ?>> Absent

                                                                            </div>

                                                                        </div>

                                                                    </td>



                                                                    <!-- Assignment -->

                                                                    <td>

                                                                        <div class="form-group mb-2">

                                                                            <input type="number"
                                                                                name="scores[<?php echo $student['id']; ?>][weekly_assessment]"
                                                                                value="<?php echo $student['weekly_assessment']; ?>"
                                                                                class="form-control" min="0" max="5" placeholder="0 - 5"
                                                                                <?= $readonly_all ?>>

                                                                            <div class="form-group-append mt-1">

                                                                                <input type="checkbox"
                                                                                    name="scores[<?php echo $student['id']; ?>][weekly_assessment_absent]"
                                                                                    value="1" <?php echo (!empty($student['weekly_assessment_absent'])) ? 'checked' : ''; ?>                 <?= $readonly_all ?>> Absent

                                                                            </div>

                                                                        </div>

                                                                    </td>



                                                                    <!-- Exam -->

                                                                    <td>

                                                                        <div class="form-group mb-2">

                                                                            <input type="number"
                                                                                name="scores[<?php echo $student['id']; ?>][exam]"
                                                                                value="<?php echo $student['exam_score']; ?>"
                                                                                class="form-control" min="0" max="70"
                                                                                placeholder="0 - 70" <?= $readonly_all ?>>

                                                                            <div class="form-group-append mt-1">

                                                                                <input type="checkbox"
                                                                                    name="scores[<?php echo $student['id']; ?>][exam_absent]"
                                                                                    value="1" <?php echo (!empty($student['exam_absent'])) ? 'checked' : ''; ?>                 <?= $readonly_all ?>> Absent

                                                                            </div>

                                                                        </div>

                                                                    </td>



                                                                    <!-- Total Score (Readonly) -->

                                                                    <td>

                                                                        <?php

                                                                        // Check if any required score is missing
                                                                
                                                                        $isComplete = true;



                                                                        // Check test score
                                                                
                                                                        if (empty($student['test_absent']) && (empty($student['test_score']) && $student['test_score'] !== '0' && $student['test_score'] !== 0)) {

                                                                            $isComplete = false;

                                                                        }





                                                                        // Check class performance
                                                                
                                                                        if (empty($student['class_performance_absent']) && (empty($student['class_performance']) && $student['class_performance'] !== '0' && $student['class_performance'] !== 0)) {

                                                                            $isComplete = false;

                                                                        }



                                                                        // Check weekly assessment
                                                                
                                                                        if (empty($student['weekly_assessment_absent']) && (empty($student['weekly_assessment']) && $student['weekly_assessment'] !== '0' && $student['weekly_assessment'] !== 0)) {

                                                                            $isComplete = false;

                                                                        }



                                                                        // Check exam score
                                                                
                                                                        if (empty($student['exam_absent']) && (empty($student['exam_score']) && $student['exam_score'] !== '0' && $student['exam_score'] !== 0)) {

                                                                            $isComplete = false;

                                                                        }



                                                                        // Display text if incomplete, otherwise show actual total
                                                                
                                                                        if (!$isComplete) {

                                                                            $displayText = ($student['total_score'] ?? 0) . ' (Incomplete)';

                                                                            $inputType = 'text';

                                                                        } else {

                                                                            $displayText = $student['total_score'] ?? '';

                                                                            $inputType = 'number';

                                                                        }

                                                                        ?>

                                                                        <?php if ($inputType === 'text'): ?>

                                                                                <input type="text" value="<?php echo $displayText; ?>"
                                                                                    class="form-control text-danger font-weight-bold" readonly
                                                                                    style="color: #dc3545 !important;">

                                                                        <?php else: ?>

                                                                                <input type="number" value="<?php echo $displayText; ?>"
                                                                                    class="form-control" readonly>

                                                                        <?php endif; ?>

                                                                    </td>

                                                                </tr>

                                                        <?php endforeach; ?>

                                                <?php endif; ?>

                                            </tbody>





                                        </table>

                                        <?php if (!empty($students)): ?>

                                                <?php

                                                // Collect all statuses
                                            
                                                $statuses = array_column($students, 'status');



                                                if (!empty($statuses) && count(array_unique($statuses)) === 1) {

                                                    // all students share the same status
                                            
                                                    $status = $statuses[0];

                                                } else {

                                                    $status = null; // mixed or not set
                                            
                                                }

                                                ?>



                                                <?php if ($status === 'Approved'): ?>

                                                        <div class="form-group alert alert-info mt-3 text-center">

                                                            <b>Result has been approved by the school and is now locked.</b>

                                                        </div>

                                                <?php elseif ($status === 'Submitted to Admin'): ?>

                                                        <div class="form-group alert alert-info mt-3 text-center">

                                                            <b>Result has been submitted to the school and is pending final
                                                                approval.</b>

                                                        </div>

                                                <?php else: ?>

                                                        <div class="form-group text-center">

                                                            <button type="submit" class="btn btn-primary btn-lg">

                                                                <i class="fas fa-save"></i> Save Results

                                                            </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: Results submitted are saved per page

                                                            </small>

                                                        </div>

                                                <?php endif; ?>

                                        <?php endif; ?>



                                    </form>

                                </div>



                            </div><!-- /.card -->

                        </div><!-- /.col-md-12 -->

                    </div><!-- /.row -->

                </div><!-- /.container-fluid -->

            </section><!-- /.content -->

        </div><!-- /.content-wrapper -->



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

    </div><!-- /.wrapper -->

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

</body>



</html>