<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once '../auth/auth.php';
require_once '../models/db_connection.php';
    // require_once '../models/student_model.php';
    // require_once '../models/course_model.php';
    // require_once '../models/exam_model.php';
    // require_once '../models/fee_model.php';
    // $student =  new Student($conn);
    // $exam =  new Exam($conn);
    // $fee =  new Fee($conn);
    // if (isset($_POST["add_marks"])) {
    //   $practical = $_POST["practical"];
    //   $theory =  $_POST["theory"];
    //   $stdId = $_POST["id"];
    //   $studentPayment = $fee->getTotalPaymentsForStudent($stdId);
    //   $studentFees = $fee->getSingleStudentFees($stdId);
    //   $due = $studentFees[0]['ammount'] - $studentPayment[0]['totalAmmount'];
    //     if($due > 0){
    //     header("Location: add_marks.php?message=You still have a due of $due");
    //     exit(); // Stop further execution
    //     }else{
    //     $success = $exam->addStudentMarksNew($stdId,$practical,$theory);
    //     header("Location: generate_results.php?message=Marks Added successfully");
    //     exit(); // Stop further execution
    //     }

    // }
    $id = isset($_GET['id']) ? $_GET['id'] : ''; // Make sure the ID is properly captured

    if (isset($_POST['add_marks'])) {
      $totalpay = 0;

      // First, fetch the course fee (ammount) for the student
      $feeQuery = mysqli_query($conn, "
    SELECT fees.ammount 
    FROM student_course
    JOIN fees ON student_course.course_id = fees.id
    WHERE student_course.s_id = '$id'
  ");

      $feeData = mysqli_fetch_assoc($feeQuery); // Get the fee data
      $courseFee = isset($feeData['ammount']) ? $feeData['ammount'] : 0; // Get the course fee (if it exists)

      // Now, fetch the total payments made by the student
      $selpayment = mysqli_query($conn, "
    SELECT student_payments.amount
    FROM student_payments
    WHERE student_payments.st_id = '$id'
  ");

      // Sum the payments
      while ($fetchpay = mysqli_fetch_assoc($selpayment)) {
        $totalpay += $fetchpay['amount'];
      }

      // Calculate the remaining balance
      $remain = $courseFee - $totalpay;

      if ($remain > 0) {
        echo "<script>
        alert('You still have a due balance of $remain');
        window.location.href = 'add_marks.php';
    </script>";
      } else {
        // Proceed with adding the marks
        $selstudent = mysqli_fetch_array(mysqli_query($conn, "
      SELECT * FROM students, student_course 
      WHERE students.en_id = student_course.s_id 
      AND students.student_id = '$id'
    "));
$average = ($_POST['practical'] + $_POST['theory'])/200 * 100;
if($average >= 70){
        $addmarks = mysqli_query($conn, "
      INSERT INTO student_exams(student, practical, theory, average, course,remark) 
      VALUES('$selstudent[student_id]', '$_POST[practical]', '$_POST[theory]', '$average', '$selstudent[course_id]','passed')
    ");
}
else{
      $addmarks = mysqli_query($conn, "
      INSERT INTO student_exams(student, practical, theory, average, course, remark) 
      VALUES('$selstudent[student_id]', '$_POST[practical]', '$_POST[theory]', '$average', '$selstudent[course_id]', 'failed')
    ");
}

        if ($addmarks) {
          echo "<script>
          alert('Marks added successfully');
          window.location.href = 'generate_results.php';
      </script>";
        }
      }
    }


?>
<!DOCTYPE html>
<html lang="en">

<head>
 <title>Student | Add Student </title>
 <?php include("../templates/header.php"); ?>
</head>
<body>
  <div class="container-scroller">
    <!-- partial:partials/_navbar.html -->
    <?php include("../templates/nav.php"); ?>
    <!-- partial -->
    <div class="container-fluid page-body-wrapper">
      <!-- partial:partials/_sidebar.html -->
      <?php include("../templates/sidenav.php"); ?>
      <!-- partial -->
      <div class="main-panel">
        <div class="content-wrapper">
        <div class="col-md-6 grid-margin stretch-card">
              <div class="card">
                <div class="card-body">
                  <h4 class="card-title">Add Student Marks</h4>
                  <p class="card-description"> 
                    Add Student  <code>Marks</code>                   
                  </p>
                  <form action="" method="POST">
                  <div class="form-group">
                    <label for="exampleFormControlSelect2">Student Id</label>
                    <input type="text" name='stdId' class='form-control' value="<?= $_GET['id'] ?>" disabled> 
                  </div>
                  <div class="form-group">
                    <label for="exampleFormControlSelect2">Practical</label>
                    <input type="text" name='practical' class='form-control' required>
                  </div>
                        <div class="form-group" >
                    <label for="exampleFormControlSelect2">Theory</label>
                    <input type="text" name='theory' class="form-control" required>
                  </div>
                  <input type="hidden" name="id" value="<?= $_GET['id'] ?>">
                  
                  
                  <div class="col-sm-9">
                          <button type="submit" name="add_marks" class="btn btn-dark btn-lg ">Add Marks</button>
                          </div>
                </div>
                </form>
              </div>
            </div>
        
        </div>
        <!-- content-wrapper ends -->
        <!-- partial:partials/_footer.html -->
        <?php include("../templates/footer.php"); ?>
        
        <!-- partial -->
      </div>
      <!-- main-panel ends -->
    </div>
    <!-- page-body-wrapper ends -->
  </div>
    <?php include("../templates/inc_scripts.php"); ?>
</body>

</html>

