<?php
if (isset($_POST['report_sheet_btn'])) {
    $std_reg_number = $_POST['std_reg_number'];
    $std_class = $_POST['std_class'];
    $std_term = $_POST['std_term'];
    $std_session = $_POST['std_session'];

    // Prepare the SQL statement
    $stmt = $connection->prepare("SELECT * FROM `results1` WHERE `reg_number` = ? AND `class` = ? AND `term` = ? AND `session` = ?");
    if ($stmt) {
        $stmt->bind_param("ssss", $std_reg_number, $std_class, $std_term, $std_session);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result && $result->num_rows > 0) {
            $row = $result->fetch_assoc();
            $_SESSION['result'] = $row['id'];
            header("Location: termly_result.php");
            exit();
        } else {
            $_SESSION['msg'] = "No Result Records Found !!!";
            $_SESSION['type'] = "error";
            header("Location: view_published_result");
            exit();
        }
    } else {
        $_SESSION['msg'] = "Result Checking Failed !!!";
        $_SESSION['type'] = "error";
        header("Location: view_published_result");
        exit();
    }
}
?>


<?php
$post_class = isset($_POST['show_publish_result_class']) ? inject_checker($connection, $_POST['show_publish_result_class']) : '';
$post_term = isset($_POST['show_publish_result_term']) ? inject_checker($connection, $_POST['show_publish_result_term']) : ($current_term ?? 'First Term');
$post_session = isset($_POST['show_publish_result_session']) ? inject_checker($connection, $_POST['show_publish_result_session']) : ($current_session ?? '2025/2026');
?>

<div class='page-title'>
  <div>
    <h1><i class='fa fa-laptop'></i> Result Management</h1>
    <p>View Published Result</p>
  </div>
</div>

<div class='card'>
    <div class='panel panel-primary'>
        <div class='panel-heading'>
            <h4 class='text-center'>View Published Results</h4>
        </div>
        <div class='panel-body'>
            <form method='POST' action=''>
                <div class='row'>
                    <div class='col-md-3'>
                        <div class='input-group'>
                            <span class='input-group-addon' id='basic-addon2'>Class:</span>
                            <select class='form-control' name='show_publish_result_class' required>
                                <option value='' disabled <?php if(empty($post_class)) echo 'selected'; ?>>Select Class</option>
                                <?php
                                    $query = " SELECT * FROM `classes` ORDER BY `classes` ASC ";
                                    $run_query = mysqli_query($connection, $query);
                                    if(mysqli_num_rows($run_query) > 0){
                                        while($result = mysqli_fetch_assoc($run_query)){
                                            $publish_result_classes = $result['classes'];
                                            $is_selected = ($post_class === $publish_result_classes) ? 'selected' : '';
                                            echo "<option value='{$publish_result_classes}' {$is_selected}>{$publish_result_classes}</option>";
                                        }
                                    }
                                ?>
                            </select>
                        </div>
                    </div>

                    <div class='col-md-3'>
                        <div class='input-group'>
                            <span class='input-group-addon' id='basic-addon2'>Term:</span>
                            <select class='form-control' name='show_publish_result_term' required>
                                <?php
                                    $term_array = array("First Term", "Second Term", "Third Term");
                                    foreach ($term_array as $t) {
                                        $is_selected = ($post_term === $t) ? 'selected' : '';
                                        echo "<option value='{$t}' {$is_selected}>{$t}</option>";
                                    }
                                ?>
                            </select>
                        </div>
                    </div>

                    <div class='col-md-3'>
                        <div class='input-group'>
                            <span class='input-group-addon' id='basic-addon2'>Session:</span>
                            <select class='form-control' name='show_publish_result_session' required>
                                <?php
                                    $query = "SELECT * FROM `sessions` ORDER BY `sessions` DESC";
                                    $run_query = mysqli_query($connection, $query);
                                    if (mysqli_num_rows($run_query) > 0) {
                                        while ($result = mysqli_fetch_assoc($run_query)) {
                                            $all_sessions = $result['sessions'];
                                            $is_selected = ($post_session === $all_sessions) ? 'selected' : '';
                                            echo "<option value='{$all_sessions}' {$is_selected}>{$all_sessions}</option>";
                                        }
                                    }
                                ?>
                            </select>
                        </div>
                    </div>
                    <div class='col-md-3'>
                        <input type='submit' name='view_publish_result_btn' value='VIEW PUBLISHED' class='btn btn-primary btn-sm' />
                        <input type='submit' name='delete_published_result_btn' value='DELETE' class='btn btn-danger btn-sm' onclick="return confirm('Are you sure you want to delete these published results?');" />
                    </div>
                </div>
            </form>
            <br />

            <?php
///////////////// POST ACTION TO VIEW PUBLISHED RESULT ////////////
if(isset($_POST['view_publish_result_btn'])){
    $show_publish_result_class = $post_class;
    $show_publish_result_term = $post_term;
    $show_publish_result_session = $post_session;

    if(empty($show_publish_result_class) || $show_publish_result_class == $select){
     	echo "<div class='alert alert-danger'>Please select a Class to view published results.</div>";
    }
    elseif(empty($show_publish_result_term) || $show_publish_result_term == $select){
     	echo "<div class='alert alert-danger'>Please select a Term to view published results.</div>";
    }
    elseif(empty($show_publish_result_session) || $show_publish_result_session == $select){
     	echo "<div class='alert alert-danger'>Please select a Session to view published results.</div>";
    }else{
        $query_show = " SELECT * FROM `positions` WHERE `class` = '{$show_publish_result_class}' AND `term` = '{$show_publish_result_term}' AND `session` = '{$show_publish_result_session}' ORDER BY `class_position` ASC ";
        $run_query_show = mysqli_query($connection, $query_show);

        if(mysqli_num_rows($run_query_show) > 0){
            $i = 0;
            echo"
                <div class='table-responsive'>
                            <table class='table table-bordered table-hover' id='myTable'>
                        <thead>
                            <tr>
                                <th>SN</th>
                                <th>NAME</th>
                                <th>REG NO.</th>
                                <th>CLASS</th>
                                <th>TERM</th>
                                <th>SESSION</th>
                                <th>TOTAL</th>
                                <th>AVG</th>
                                <th>POS</th>
                                <th>ACTION</th>
                            </tr>
                        </thead>
                        <tbody>
            ";
			while ($result = mysqli_fetch_assoc($run_query_show)) {
				$i++;
				$name = $result['name'];
				$reg_number = $result['reg_number'];
				$class = $result['class'];
				$term = $result['term'];
				$session = $result['session'];
				$student_total = $result['students_sub_total'];
				$student_average = number_format($result['students_sub_average'], 1); // ← round to 1 decimal place
				$student_position = getOrdinal($result['class_position']);

				echo "
					<tr>
						<td>{$i}</td>
						<td>{$name}</td>
						<td class='warning'>{$reg_number}</td>
						<td>{$class}</td>
						<td>{$term}</td>
						<td>{$session}</td>
						<td class='success'>{$student_total}</td>
						<td class='danger'>{$student_average}</td>
						<td class='info'>{$student_position}</td>
						<td>
						    <form action='' method='POST'>
						        <input type='hidden' name='std_reg_number' value='{$reg_number}' />
						        <input type='hidden' name='std_class' value='{$class}' />
						        <input type='hidden' name='std_term' value='{$term}' />
						        <input type='hidden' name='std_session' value='{$session}' />
						        <input type='submit' name='report_sheet_btn' value='Report' class='btn btn-info btn-sm' />
						    </form>
						</td>
					</tr>
				";
			}
            echo"
                        </tbody>
                    </table>
                </div>               
            ";
        }else{
        		$_SESSION['msg'] = "This Particular Result is yet to be published";
        		$_SESSION['type'] ="error";
        		    header("Location: view_published_result");
    exit();
        }
    }										
}


                ///////////////// POST ACTION TO DELETE PUBLISHED RESULT ////////////////////
if (isset($_POST['delete_published_result_btn'])) {
    $show_publish_result_class = $_POST['show_publish_result_class'];
    $show_publish_result_term = $_POST['show_publish_result_term'];
    $show_publish_result_session = $_POST['show_publish_result_session'];

    if ($show_publish_result_class == $select) {
        $_SESSION['msg'] = "Please Select Class";
        $_SESSION['type'] = "error";
    } elseif ($show_publish_result_term == $select) {
        $_SESSION['msg'] = "Please Select Term";
        $_SESSION['type'] = "error";
    } elseif ($show_publish_result_session == $select) {
        $_SESSION['msg'] = "Please Select Session";
        $_SESSION['type'] = "error";
    } else {
        $query = "DELETE FROM `positions` WHERE `class` = '{$show_publish_result_class}' AND `term` = '{$show_publish_result_term}' AND `session` = '{$show_publish_result_session}'";
        $run_query = mysqli_query($connection, $query);

        if ($run_query) {
            $_SESSION['msg'] = "Published Result Deleted Successfully";
            $_SESSION['type'] = "success";
        } else {
            $_SESSION['msg'] = "Published Result Failed to Delete";
            $_SESSION['type'] = "error";
        }
    }

    // Optional: Redirect to prevent form resubmission on refresh
    header("Location: view_published_result");
    exit();
}

            ?>

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

