<?php
if (isset($_POST['result_upload_btn'])) {
    if (!isset($_POST["total_num"]) || empty($_POST["total_num"])) {
        $_SESSION['msg'] = "Total Score is missing or empty";
        $_SESSION['type'] = "error";
        exit();
    }

    $total_num = (int)$_POST["total_num"];

    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
        $ca1 = isset($_POST['student_ca1'][$j]) && $_POST['student_ca1'][$j] !== '' ? (int)inject_checker($connection, $_POST['student_ca1'][$j]) : null;
$ca2 = isset($_POST['student_ca2'][$j]) && $_POST['student_ca2'][$j] !== '' ? (int)inject_checker($connection, $_POST['student_ca2'][$j]) : null;

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

        // Check if result already exists
        $check_query = "SELECT id, ca1, ca2 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)) {
            // Record exists → update only provided CAs
            $update_fields = [];
            $params = [];
            $types = '';

            if ($ca1 !== null) {
                $update_fields[] = "ca1 = ?";
                $params[] = $ca1;
                $types .= 'd';
            }
            if ($ca2 !== null) {
                $update_fields[] = "ca2 = ?";
                $params[] = $ca2;
                $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 {
            // No record → insert new
            $subject_total = ($ca1 ?? 0) + ($ca2 ?? 0);
            $insert_query = "INSERT INTO `results1`
                (`class`, `term`, `session`, `reg_number`, `name`, `subjects`, `ca1`, `ca2`, `subject_total`, `date_of_upload`)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $stmt_insert = mysqli_prepare($connection, $insert_query);
            mysqli_stmt_bind_param($stmt_insert, "sssssssdds", 
                $student_class, $result_term, $result_session, 
                $student_id, $student_name, $result_subject, 
                $ca1, $ca2, $subject_total, $date
            );
            mysqli_stmt_execute($stmt_insert);
            mysqli_stmt_close($stmt_insert);
        }

        mysqli_stmt_close($stmt);
    }

    $_SESSION['msg'] = "C.A uploaded/updated successfully";
    $_SESSION['type'] = "success";
    header("Location: admin_upload_ca");
    exit();
}
?>




<div class='page-title'>
  <div>
    <h1><i class='fa fa-laptop'></i> Continuous Assessment</h1>
    <p>Upload Continuous Assessment (C.A) Scores</p>
  </div>
  <div>
    <a href='modules.php?excel_result_upload' class='btn btn-success'><i class='fa fa-file-excel-o'></i> Excel / CSV Result Upload & Export</a>
  </div>
</div>

<div class='card'>
  <div class='panel panel-primary print_div'>
    <div class='panel-body'>

      <!-- === STEP 1: SELECT PARAMETERS === -->
      <form class='noprint' method='POST' action='' id='result_upload'>
        <div class='row'>
          <div class='col-md-3'>
            <div class='input-group'>
              <span class='input-group-addon'>Class:</span>
              <select class='form-control' name='result_upload_class' id='class-select' required>
                <option selected disabled>Select Class</option>
                <?php
                $query = "SELECT * FROM `classes`";
                $run_query = mysqli_query($connection, $query);
                while ($result = mysqli_fetch_assoc($run_query)) {
                    echo "<option value='{$result['classes']}'>{$result['classes']}</option>";
                }
                ?>
              </select>
            </div>
          </div>

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

          <div class='col-md-3'>
            <div class='input-group'>
              <span class='input-group-addon'>Term:</span>
              <select class='form-control' name='result_upload_term' required>
                <option selected disabled>Select Term</option>
								    <option>First Term</option>
								     <option>Second Term</option>
								    <option>Third Term</option>
              </select>
            </div>
          </div>

          <div class='col-md-3'>
            <div class='input-group'>
              <span class='input-group-addon'>Session:</span>
              <select class='form-control' name='result_upload_session' required>
                <option selected disabled>Select Session</option>
                  					<?php
                                        $query = "SELECT * FROM `sessions`";
                                        $run_query = mysqli_query($connection, $query);
                                        if (mysqli_num_rows($run_query) > 0) {
                                            while ($result = mysqli_fetch_assoc($run_query)) {
                                                $all_sessions = $result['sessions'];
                                                echo "<option>{$all_sessions}</option>";
                                            }
                                        }
                                        ?>
              </select>
            </div>
          </div>

          <!-- New: 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='ca1'>CA1 Only</option>
                <option value='ca2'>CA2 Only</option>
                <option value='both'>CA1 & CA2</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']);

$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'
    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>CONTINUOUS ASSESSMENT 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}'>
          <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 CA headers
        if ($upload_type == 'ca1' || $upload_type == 'both') {
            echo "<th>CA1 (20 Marks)</th>";
        }
        if ($upload_type == 'ca2' || $upload_type == 'both') {
            echo "<th>CA2 (20 Marks)</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 last uploaded CA scores
            $fetch_result = mysqli_query($connection, "
                SELECT ca1, ca2 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_ca1 = $last['ca1'] ?? '';
            $last_ca2 = $last['ca2'] ?? '';

            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='result_term[]' value='{$term}' />
                <input type='hidden' name='result_session[]' value='{$sessionVal}' />
                <input type='hidden' name='result_subject[]' value='{$subject}' />";

            // Dynamic CA inputs
            if ($upload_type == 'ca1' || $upload_type == 'both') {
                echo "<td><input type='number' name='student_ca1[]' min='0' max='20' value='{$last_ca1}' class='form-control' /></td>";
            } else {
                echo "<input type='hidden' name='student_ca1[]' value='{$last_ca1}' />";
            }

            if ($upload_type == 'ca2' || $upload_type == 'both') {
                echo "<td><input type='number' name='student_ca2[]' min='0' max='20' value='{$last_ca2}' class='form-control' /></td>";
            } else {
                echo "<input type='hidden' name='student_ca2[]' value='{$last_ca2}' />";
            }

            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='result_upload_btn' class='btn btn-lg btn-primary'>Upload C.A</button>
          </div>
        </form>
        </div>";
    } else {
        $_SESSION['msg'] = "No student records found!";
        $_SESSION['type'] = "error";
    }
}
?>


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