<?php 
session_start();
ob_start(); 
error_reporting(E_ALL);
ini_set('display_errors', 1);
include "../include/config.php";

if (!isset($_SESSION['email'])) {
    header("location:../index.php");
    exit();
}

$userlogin = $_SESSION['email'];
$role      = $_SESSION['role'];
$intake    = $_SESSION['department'];

if (isset($_POST['marks'])) {
    $intake  = $_POST['intake'];
    $Year    = $_POST['year']; 
    $course  = $_POST['course'];  
    $program = $_POST['program'];  
    $Term    = $_POST['term'];
}

// Handle Excel Export
if (isset($_GET['export']) && $_GET['export'] == 'excel') {
    // Get parameters from GET for export
    $intake  = isset($_GET['intake']) ? $_GET['intake'] : $intake;
    $Year    = isset($_GET['year']) ? $_GET['year'] : $Year; 
    $course  = isset($_GET['course']) ? $_GET['course'] : $course;  
    $program = isset($_GET['program']) ? $_GET['program'] : $program;  
    $Term    = isset($_GET['term']) ? $_GET['term'] : $Term;
    
    // Set headers for Excel file download
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment; filename="marks_'.$course.'_'.$Year.'_'.$Term.'_'.date('Y-m-d').'.xls"');
    header('Cache-Control: max-age=0');
    
    // Query for export data
    if($role == "Admin"){
        $export_query = mysqli_query($conn,"SELECT * FROM students 
        INNER JOIN results ON students.studentid = results.studentid 
        WHERE results.year='$Year' 
        AND results.course='$course' 
        AND results.term='$Term' 
        AND students.program='$program'");
    } else {
        $export_query = mysqli_query($conn,"SELECT * FROM students 
        INNER JOIN results ON students.studentid = results.studentid 
        WHERE results.year='$Year' 
        AND results.course='$course' 
        AND results.term='$Term' 
        AND students.program='$program'");
    }
    
    // Start HTML table for Excel
    echo '<table border="1">';
    echo '<tr>';
    echo '<th>Student ID</th>';
    echo '<th>Name</th>';
    echo '<th>Intake</th>';
    echo '<th>Program</th>';
    echo '<th>Year</th>';
    echo '<th>Semester</th>';
    echo '<th>Course</th>';
    echo '<th>CA</th>';
    echo '<th>CA1</th>';
    echo '<th>CA2</th>';
    if($role=="Admin") {
        echo '<th>EXAM</th>';
        echo '<th>TOTAL</th>';
    }
    echo '</tr>';
    
    while($row = mysqli_fetch_array($export_query)) {
        echo '<tr>';
        echo '<td>' . $row['studentid'] . '</td>';
        echo '<td>' . $row['studentname'] . '</td>';
        echo '<td>' . $row['intake'] . '</td>';
        echo '<td>' . $row['program'] . '</td>';
        echo '<td>' . $row['year'] . '</td>';
        echo '<td>' . $row['term'] . '</td>';
        echo '<td>' . $row['course'] . '</td>';
        echo '<td>' . $row['ca'] . '</td>';
        echo '<td>' . $row['ca1'] . '</td>';
        echo '<td>' . $row['ca2'] . '</td>';
        if($role=="Admin") {
            echo '<td>' . $row['exam'] . '</td>';
            // Calculate total
            $ca = floatval($row['ca']);
            $ca1 = floatval($row['ca1']);
            $ca2 = floatval($row['ca2']);
            $exam = floatval($row['exam']);
            $total = $ca + $ca1 + $ca2 + $exam;
            echo '<td>' . $total . '</td>';
        }
        echo '</tr>';
    }
    
    echo '</table>';
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Submit Marks</title>
    <link rel="stylesheet" href="../../boostrap/1.css">
    <link rel="stylesheet" href="../../boostrap/2.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300&family=Source+Sans+Pro:wght@300&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="icon" href="favicon.png" type="image/png">
    <meta name="theme-color" content="#d03f4d">
    <script src='https://kit.fontawesome.com/a076d05399.js' crossorigin='anonymous'></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" crossorigin="anonymous">
    <link href="https://fonts.googleapis.com/css2?family=Signika+Negative:wght@300..700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="res/bootstrap@5.2.0.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>

    <style>
        body {
            font-family: 'Source Sans Pro', sans-serif;
        }
        .scroll {
            overflow-x: auto;
        }
        .export-btn {
            background-color: #28a745;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 5px;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 5px;
            margin-bottom: 15px;
        }
        .export-btn:hover {
            background-color: #218838;
            color: white;
            text-decoration: none;
        }
        .print-btn {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 5px;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 5px;
            margin-bottom: 15px;
            margin-left: 10px;
        }
        .print-btn:hover {
            background-color: #0056b3;
            color: white;
            text-decoration: none;
        }
    </style>
</head>
<body>
<?php include "../include/nav.php";?>

<div class="content">
    <br>
    <div style="padding-left:30px;">
       <h4 style="color: #d03f4d;margin-top:10px">Submit Marks</h4>   
       <li><b>Course</b>: <?php echo $course;?>  <b>Intake</b>: <?php echo $intake;?></li>
       <li><b>Year</b>: <?php echo $Year;?> <b>Semester</b>: <?php echo $Term;?></li>
       <li><b>Program</b>: <?php echo $program;?></li>
    </div>

    <?php if (isset($_GET['error'])) { ?>
    <div class="alert alert-success text-center">
      <p><i class="fa fa-check"></i> <?php echo $_GET['error'];?></p>
    </div>
    <?php } ?>

    <div class="scroll p-3 w-100">
    <?php
    // Query depending on role
    if($role == "Admin"){
        $query = mysqli_query($conn,"SELECT * FROM students 
        INNER JOIN results ON students.studentid = results.studentid 
        WHERE results.year='$Year' 
        AND results.course='$course' 
        AND results.term='$Term' 
        AND students.program='$program'");
    } else {
        $query = mysqli_query($conn,"SELECT * FROM students 
        INNER JOIN results ON students.studentid = results.studentid 
        WHERE results.year='$Year' 
        AND results.course='$course' 
        AND results.term='$Term' 
        AND students.program='$program'");
    }

    // Check if there are records
    $row_count = mysqli_num_rows($query);
    mysqli_data_seek($query, 0); // Reset pointer to beginning
    ?>
    
    <!-- Export and Print Buttons -->
    <div style="padding-left:30px; margin-bottom: 20px;">
        <?php if($row_count > 0): ?>
        <a href="?export=excel&year=<?php echo $Year; ?>&course=<?php echo $course; ?>&term=<?php echo $Term; ?>&program=<?php echo $program; ?>&intake=<?php echo $intake; ?>" 
           class="export-btn">
            <i class="fa fa-file-excel-o"></i> Export to Excel
        </a>
        <?php endif; ?>
        
        <button onclick="window.print()" class="print-btn">
            <i class="fa fa-print"></i> Print
        </button>
    </div>
    
        <form action="update.php" method="POST">

            <!-- 🔍 Search Input -->
            <div class="row mb-3">
              <div class="col-md-6">
                <input type="text" id="searchInput" class="form-control" placeholder="Search student by name or ID...">
              </div>
            </div>

            <table id="myTable" class="table table-striped table-bordered table-responsive table-hover w-100">  
              <thead>  
                  <tr>             
                      <th hidden>Id No:</th>  
                      <th hidden>Roll No:</th>
                      <th>Name</th>   
                      <th hidden>Intake</th>
                      <th hidden>Term</th>
                      <th hidden>Year</th>
                      <th hidden>Course</th>
                      <th>CA1</th>
                      <th>CA2</th>
                      <th>CA3</th>
                      <?php if($role=="Admin"){ ?>
                      <th>EXAM</th>
                      <?php } ?>
                  </tr>  
              </thead>  
              <tbody>  
              <?php while($row=mysqli_fetch_array($query)){ 
                  $ca   = $row['ca'];
                  $ca1  = $row['ca1'];
                  $ca2  = $row['ca2'];
                  $exam = $row['exam'];
              ?>
              <tr>  
                <td hidden><input type="hidden" name="id[]" value="<?php echo $row['id'];?>"></td>
                <td hidden><input type="hidden" name="studentid[]" value="<?php echo $row['studentid'];?>"></td>  
                <td><?php echo $row['studentname'];?></td> 
                <td hidden><input type="hidden" name="intake[]" value="<?php echo $row['intake'];?>"></td>  
                <td hidden><input type="hidden" name="term[]" value="<?php echo $row['term'];?>"></td>  
                <td hidden><input type="hidden" name="year[]" value="<?php echo $Year;?>"></td>  
                <td hidden><input type="hidden" name="subject[]" value="<?php echo $row['course'];?>"></td>  

                <!-- CA -->
                <td>
                  <input class="form-control" type="text" name="ca[]" 
                    value="<?php echo $ca;?>" 
                    <?php if($role!="Admin" && $ca !== "" && $ca >= 0){ echo ""; }?> />
                </td>

                <!-- CA1 -->
                <td>
                  <input class="form-control" type="text" name="ca1[]" 
                    value="<?php echo $ca1;?>" 
                    <?php if($role!="Admin" && $ca1 !== "" && $ca1 >= 0){ echo ""; }?> />
                </td>

                <!-- CA2 -->
                <td>
                  <input class="form-control" type="text" name="ca2[]" 
                    value="<?php echo $ca2;?>" 
                    <?php if($role!="Admin" && $ca2 !== "" && $ca2 >= 0){ echo ""; }?> />
                </td>

                <!-- EXAM (Admin only) -->
                <?php if($role=="Admin"){ ?>
                <td>
                  <input class="form-control" type="text" name="exam[]" value="<?php echo $exam;?>" />
                </td>
                <?php } ?>
              </tr>  
              <?php } ?>  
              </tbody>  
            </table>  
            <hr>
            <input class="btn btn-success" type="submit" name="update" value="UPDATE RESULTS"/>
        </form>
  
    </div>
    
      <br><br><br>
</div>

<!-- 🔎 Search Filter Script -->
<script>
document.getElementById("searchInput").addEventListener("keyup", function() {
  var input = this.value.toLowerCase();
  var rows = document.querySelectorAll("#myTable tbody tr");
  rows.forEach(function(row) {
    var text = row.textContent.toLowerCase();
    row.style.display = text.includes(input) ? "" : "none";
  });
});
</script>

</body>
</html>