<?php
if (isset($_POST['assignment_upload_btn'])) {
    if (!isset($_POST["total_num"]) || empty($_POST["total_num"])) {
        $_SESSION['msg'] = "Total number of students missing!";
        $_SESSION['type'] = "error";
        exit();
    }
 
    $total_num = (int)$_POST["total_num"];
    $classarm = inject_checker($connection, $_POST['classarm']);

    for ($j = 0; $j < $total_num; $j++) {
        $student_id = inject_checker($connection, $_POST['student_id'][$j]);
        $student_name = inject_checker($connection, $_POST['student_name'][$j]);
    $student_class = inject_checker($connection, $_POST['student_class'][$j]
        
        );
        
        $result_term = inject_checker($connection, $_POST['result_term'][$j]);
        $result_session = inject_checker($connection, $_POST['result_session'][$j]);
        $result_subject = inject_checker($connection, $_POST['result_subject'][$j]);

        // Independent scores
        $assignment1 = isset($_POST['student_assignment1'][$j]) && $_POST['student_assignment1'][$j] !== '' 
            ? (int)inject_checker($connection, $_POST['student_assignment1'][$j]) 
            : null;

        $assignment2 = isset($_POST['student_assignment2'][$j]) && $_POST['student_assignment2'][$j] !== '' 
            ? (int)inject_checker($connection, $_POST['student_assignment2'][$j]) 
            : null;

        $date = date('d/M/Y');

        // Check if record already exists
        $check_query = "SELECT id FROM `results1` 
                        WHERE `class`=? AND `term`=? AND `session`=? 
                        AND `subjects`=? AND `reg_number`=?";
        $stmt = mysqli_prepare($connection, $check_query);
        mysqli_stmt_bind_param($stmt, "sssss", $student_class, $result_term, $result_session, $result_subject, $student_id);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);

        if ($row = mysqli_fetch_assoc($result)) {
            // Update only provided assignments
            $update_fields = [];
            $params = [];
            $types = '';

            if ($assignment1 !== null) {
                $update_fields[] = "assignment1 = ?";
                $params[] = $assignment1;
                $types .= 'd';
            }
            if ($assignment2 !== null) {
                $update_fields[] = "assignment2 = ?";
                $params[] = $assignment2;
                $types .= 'd';
            }

            if (!empty($update_fields)) {
                $update_sql = "UPDATE `results1` SET " . implode(", ", $update_fields) . ", date_of_upload=? 
                               WHERE `id`=?";
                $params[] = $date;
                $params[] = $row['id'];
                $types .= 'si';

                $update_stmt = mysqli_prepare($connection, $update_sql);
                mysqli_stmt_bind_param($update_stmt, $types, ...$params);
                mysqli_stmt_execute($update_stmt);
                mysqli_stmt_close($update_stmt);
            } 
        } else {
            // Insert new record (without subject_total)
            $insert_query = "INSERT INTO `results1`
                (`class`, `classarm`, `term`, `session`, `reg_number`, `name`, `subjects`, `assignment1`, `assignment2`, `date_of_upload`)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $stmt_insert = mysqli_prepare($connection, $insert_query);
            mysqli_stmt_bind_param(
                $stmt_insert,
                "ssssssssds",
                $student_class,
                $classarm,
                $result_term,
                $result_session,
                $student_id,
                $student_name,
                $result_subject,
                $assignment1,
                $assignment2,
                $date
            );
            mysqli_stmt_execute($stmt_insert);
            mysqli_stmt_close($stmt_insert);
        }

        mysqli_stmt_close($stmt);
    }

    $_SESSION['msg'] = "Assignments uploaded/updated successfully";
    $_SESSION['type'] = "success";
    header("Location: class_teacher_upload_assignment");
    exit();
}
?>
<div class='page-title hidden-print'>
  <div>
    <h1><i class='fa fa-book'></i> Assignment Management</h1>
    <p>Upload Assignment Scores</p>
  </div>
</div>

<div class='card'>
  <div class='panel panel-primary print_div'>
    <div class='panel-body'>
      <!-- Step 1: Select Parameters -->
      <form method='POST' action='' id='assignment_upload'>
        <div class='row'>
          <div class='col-md-4'>
						<div class='input-group'>
							<span class='input-group-addon' id='basic-addon2'>Class:</span>
							<select class='form-control' name='result_upload_class' id='class-select'>
                                <option selected disabled>Select Class</option>
								<?php																
								// Query only classes assigned to this teacher
								$query = "SELECT DISTINCT class, arm FROM teacher_classes WHERE teacher_id = '$staff_id'";
								$run_query = mysqli_query($connection, $query);

								if (mysqli_num_rows($run_query) > 0) {
									while ($result = mysqli_fetch_assoc($run_query)) {
										$class = htmlspecialchars($result['class']);
										$arm = htmlspecialchars($result['arm']);
									
										echo "<option value='{$class}' data-arm='{$arm}'>{$class} - {$arm}</option>";
									}
								} else {
									echo "<option disabled>No class assigned</option>";
								}
								?>
                            </select>
                                                  <input type="hidden" name="reg_no_arm" id="reg_no_arm">
                                    
                                    <script>
document.getElementById('class-select').addEventListener('change', function() {
    // Get selected option
    var selectedOption = this.options[this.selectedIndex];
    // Get arm from data attribute
    var armValue = selectedOption.getAttribute('data-arm') || '';
    // Store it in hidden input
    document.getElementById('reg_no_arm').value = armValue;
});
</script>
                        </div>
                    </div>

                    <div class='col-md-4'>
                        <div class='input-group'>
                            <span class='input-group-addon' id='basic-addon2'>Subject:</span>
                            <select class='form-control' name='result_upload_subject' id='subject-select'>                                
                               <option selected>Select a Class First</option>
							</select>
						</div>
					</div>

					<div class='col-md-4'>
                        <div class='input-group'>
                            <span class='input-group-addon' id='basic-addon2'>Term:</span>
                            <select class='form-control' name='result_upload_term' required>
                                <?php
                                    $query = " SELECT * FROM `current_season` ";
                                    $run_query = mysqli_query($connection, $query);
                                    if(mysqli_num_rows($run_query) == 1){
                                        while($result = mysqli_fetch_assoc($run_query)){
                                            $show_current_term = $result['current_term'];
                                            echo "<option>{$show_current_term}</option>";
                                        }
                                    }
                                ?>
                            </select>
                        </div>
                        <br />
                    </div>

                    <div class='col-md-4'>
                        <div class='input-group'>
                            <span class='input-group-addon' id='basic-addon2'>Session:</span>
                            <select class='form-control' name='result_upload_session'>
                                <?php
                                    ///////////// POST ACTION TO DISPLAY CURRENT SESSION //////////////
                                    $query = " SELECT * FROM `current_season` ";
                                    $run_query = mysqli_query($connection, $query);
                                    if(mysqli_num_rows($run_query) == 1){
                                        while($result = mysqli_fetch_assoc($run_query)){
                                            $show_current_session = $result['current_session'];
                                            echo"
                                                <option>{$show_current_session}</option>
                                            ";
                                        }
                                    }
                                ?>
                            </select>
                        </div>
                        <br />
                    </div>

          <!-- Upload Type -->
          <div class='col-md-3'>
            <div class='input-group'>
              <span class='input-group-addon'>Upload:</span>
              <select class='form-control' name='upload_type' id='upload_type' required>
                <option disabled selected>Select Type</option>
                <option value='assignment1'>Assignment 1 Only</option>
                <option value='assignment2'>Assignment 2 Only</option>
                <option value='both'>Assignment 1 & 2</option>
              </select>
            </div>
          </div>

          <div class='col-md-2 mt-2'>
            <input type='submit' name='go_upload' value='GET' class='btn btn-md btn-primary' />
          </div>
        </div>
      </form>
      <br />
      <?php
        if (isset($_POST['go_upload'])) {
            $result_upload_class = inject_checker($connection, $_POST['result_upload_class']);
            $result_upload_subject = inject_checker($connection, $_POST['result_upload_subject']);
            $result_upload_term = inject_checker($connection, $_POST['result_upload_term']);
            $result_upload_session = inject_checker($connection, $_POST['result_upload_session']);
            $upload_type = inject_checker($connection, $_POST['upload_type']);
              $reg_no_arm = inject_checker($connection, $_POST['reg_no_arm']);
    $teacher_arm = $reg_no_arm;
        
            // ✅ Fetch mark settings once
            $settings_query = mysqli_query($connection, "SELECT * FROM score_settings LIMIT 1");
            $settings = mysqli_fetch_assoc($settings_query);
            $assignment1_mark = $settings['assignment1_mark'];
            $assignment2_mark = $settings['assignment2_mark'];
            $ca1_mark = $settings['ca1_mark'];
            $ca2_mark = $settings['ca2_mark'];
            $exam_mark = $settings['exam_mark'];
        
            $student_query = "
                SELECT s.*, st.status
                FROM `subjects` s
                INNER JOIN `students` st ON s.reg_number = st.reg_number
                WHERE s.class = '{$result_upload_class}'
                  AND s.subjects = '{$result_upload_subject}'
                  AND s.term = '{$result_upload_term}'
                  AND s.session = '{$result_upload_session}'
                  AND st.status = 'active'
                  AND st.classarm = '{$teacher_arm}'
                ORDER BY s.name ASC
            ";
            $run_query = mysqli_query($connection, $student_query);
        
            if (mysqli_num_rows($run_query) > 0) {
                echo "
                <div class='row text-center'>
                  <div class='col-md-12'>
                    <h4>{$school_name}</h4>
                    <h4>ASSIGNMENT SCORE SHEET</h4>
                  </div>
                  <div class='col-md-3'><p><b>CLASS:</b><br>{$result_upload_class}</p></div>
                  <div class='col-md-3'><p><b>SESSION:</b><br>{$result_upload_session}</p></div>
                  <div class='col-md-3'><p><b>TERM:</b><br>{$result_upload_term}</p></div>
                  <div class='col-md-3'><p><b>SUBJECT:</b><br>{$result_upload_subject}</p></div>
                </div>
        
                <div class='table-responsive'>
                <form method='POST' action=''>
                  <input type='hidden' name='upload_type' value='{$upload_type}'>
                    <input type='hidden' name='classarm' value='{$teacher_arm}'>
                  <table class='table table-hover table-bordered' id='myTable'>
                    <thead class='bg-light'>
                      <tr>
                        <th>S/N</th>
                        <th>Student Name</th>
                        <th>Reg No</th>";
        
                // ✅ Dynamic headers
                if ($upload_type == 'assignment1' || $upload_type == 'both') {
                    echo "<th>ASM 1 ({$assignment1_mark})</th>";
                }
                if ($upload_type == 'assignment2' || $upload_type == 'both') {
                    echo "<th>ASM 2 ({$assignment2_mark})</th>";
                }
        
                echo "</tr></thead><tbody>";
        
                $i = 0; $k = 1;
                while ($student = mysqli_fetch_assoc($run_query)) {
                    $reg_no = $student['reg_number'];
                    $class = $student['class'];
                    $term = $student['term'];
                    $sessionVal = $student['session'];
                    $subject = $student['subjects'];
        
                    // ✅ Fetch previous scores
                    $fetch_result = mysqli_query($connection, "
                        SELECT assignment1, assignment2 FROM results1 
                        WHERE class='$class' 
                        AND term='$term' 
                        AND session='$sessionVal' 
                        AND subjects='$subject' 
                        AND reg_number='$reg_no' 
                        LIMIT 1
                    ");
                    $last = mysqli_fetch_assoc($fetch_result);
                    $last_assignment1 = $last['assignment1'] ?? '';
                    $last_assignment2 = $last['assignment2'] ?? '';
        
                    echo "
                    <tr>
                        <td>{$k}</td>
                        <td>{$student['name']}
                          <input type='hidden' name='student_name[]' value='{$student['name']}' />
                        </td>
                        <td>{$reg_no}
                          <input type='hidden' name='student_id[]' value='{$reg_no}' />
                        </td> 
                        <input type='hidden' name='student_class[]' value='{$class}' />
                         <input type='hidden' name='student_arm[]' value='{$teacher_arm}' />
                        <input type='hidden' name='result_term[]' value='{$term}' />
                        <input type='hidden' name='result_session[]' value='{$sessionVal}' />
                        <input type='hidden' name='result_subject[]' value='{$subject}' />";
        
                    // ✅ Dynamic inputs
                    if ($upload_type == 'assignment1' || $upload_type == 'both') {
                        echo "<td><input type='number' name='student_assignment1[]' min='0' max='{$assignment1_mark}' value='{$last_assignment1}' class='form-control' /></td>";
                    } else {
                        echo "<input type='hidden' name='student_assignment1[]' value='{$last_assignment1}' />";
                    }
        
                    if ($upload_type == 'assignment2' || $upload_type == 'both') {
                        echo "<td><input type='number' name='student_assignment2[]' min='0' max='{$assignment2_mark}' value='{$last_assignment2}' class='form-control' /></td>";
                    } else {
                        echo "<input type='hidden' name='student_assignment2[]' value='{$last_assignment2}' />";
                    }
        
                    echo "</tr>";
                    $i++; $k++;
                }
        
                echo "
                    </tbody>
                  </table>
                  <input type='hidden' name='total_num' value='{$i}' />
                  <div class='text-left mt-3'>
                    <button type='submit' name='assignment_upload_btn' class='btn btn-lg btn-primary'>Upload</button>
                  </div>
                </form>
                </div>";
            } else {
                $_SESSION['msg'] = "No student records found!";
                $_SESSION['type'] = "error";
            }
        }
        ?>


    </div>
  </div>
</div>