<?php
// Assuming $connection, $school_name, $full_name, $staff_id, $current_term, and $current_session are defined elsewhere
$selected_class = $_POST['view_upload_class'] ?? '';
$selected_subject = $_POST['view_upload_subject'] ?? '';
$subjects = [];

if (!empty($selected_class)) {
    $stmt = $connection->prepare("SELECT DISTINCT subject FROM subject_teacher WHERE staff_id = ? AND class = ?");
    $stmt->bind_param("is", $staff_id, $selected_class);
    $stmt->execute();
    $result = $stmt->get_result();
    
    while ($row = $result->fetch_assoc()) {
        $subjects[] = $row['subject'];
    }
    $stmt->close();
}
?>

<div class='page-title'>
  <div>
    <h1><i class='fa fa-laptop'></i> Result Management</h1>
    <p>View and Edit Uploaded Results</p>
  </div>  
</div>

<div class="card">
    <div class='row'>
        <div class='col-xs-12 col-sm-12 col-md-12'>
            <div class='panel panel-primary ch'>
                <div class='panel-heading'>
                    <h4 class='text-center'>View and Edit Uploaded Results</h4>
                </div><br/>
                <div class='panel-body'>
                    <form class='noprint' method='POST' action='' id='view_result'>
                        <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='view_upload_class' onchange='this.form.submit()' required>
                                        <option disabled <?= $selected_class == '' ? 'selected' : '' ?>>Select Class</option>
                                        <?php
                                        $stmt = $connection->prepare("SELECT DISTINCT class FROM subject_teacher WHERE staff_id = ?");
                                        $stmt->bind_param("i", $staff_id);
                                        $stmt->execute();
                                        $result = $stmt->get_result();

                                        while ($row = $result->fetch_assoc()) {
                                            $class = htmlspecialchars($row['class']);
                                            $selected = ($selected_class == $class) ? 'selected' : '';
                                            echo "<option value='{$class}' $selected>{$class}</option>";
                                        }
                                        $stmt->close();
                                        ?>
                                    </select>
                                </div>
                                <br />
                            </div>

                            <div class='col-md-3'>
                                <div class='input-group'>
                                    <span class='input-group-addon' id='basic-addon2'>Subject:</span>
                                    <select class='form-control' name='view_upload_subject' required>
                                        <?php
                                        if (!empty($subjects)) {
                                            echo "<option disabled>Select Subject</option>";
                                            foreach ($subjects as $subj) {
                                                $subj = htmlspecialchars($subj);
                                                $selected = ($selected_subject == $subj) ? 'selected' : '';
                                                echo "<option value='{$subj}' {$selected}>{$subj}</option>";
                                            }
                                        } else {
                                            echo "<option>Select a class first</option>";
                                        }
                                        ?>
                                    </select>
                                </div>
                                <br />
                            </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='view_upload_term'>
                                        <option selected><?php echo $current_term; ?></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='view_upload_session'>
                                        <option selected><?php echo $current_session; ?></option>
                                    </select>
                                </div>
                                <br />
                            </div>

                            <div class='col-md-3'>
                                <input type='submit' name='view_upload_btn' value='VIEW' class='btn btn-sm btn-primary' />
                                <input type='submit' name='del_upload_btn' value='DELETE' class='btn btn-sm btn-danger' />
                                <button onclick='printTable()' class='btn btn-sm btn-primary'>Print</button>
                            </div>
                        </div>
                    </form>
                    <br />

                    <?php
                    // POST ACTION TO VIEW UPLOADED RESULTS
                    if (isset($_POST['view_upload_btn'])) {
                        $view_upload_class = $_POST['view_upload_class'];
                        $view_upload_subject = $_POST['view_upload_subject'];
                        $view_upload_term = $_POST['view_upload_term'];
                        $view_upload_session = $_POST['view_upload_session'];

                        if (empty($view_upload_class)) {
                            $_SESSION['msg'] = "Please Select Class";
                            $_SESSION['type'] = "error";
                        } elseif (empty($view_upload_subject)) {
                            $_SESSION['msg'] = "Please Select Subject";
                            $_SESSION['type'] = "error";
                        } elseif (empty($view_upload_term)) {
                            $_SESSION['msg'] = "Please Select Term";
                            $_SESSION['type'] = "error";
                        } else {
                            $stmt = $connection->prepare("SELECT * FROM `results1` 
                                                         WHERE `class` = ? 
                                                         AND `term` = ? 
                                                         AND `session` = ? 
                                                         AND `subjects` = ? 
                                                         ORDER BY `subject_rank` ASC");
                            $stmt->bind_param("ssss", $view_upload_class, $view_upload_term, $view_upload_session, $view_upload_subject);
                            $stmt->execute();
                            $run_query = $stmt->get_result();

                            if (mysqli_num_rows($run_query) > 0) {
                                $i = 0;
                                ?>
                                <div id='printableArea'>
                                    <div class='table-responsive'>
                                        <div class='row text-center'>
                                            <div class='col-md-12 col-xs-12'>
                                                <h5><?= $school_name ?></h5>                                                  
                                                <h5>EXAM SCORE SHEET</h5>
                                                <h5>By <?= $full_name ?></h5>
                                            </div>
                                            <div class='col-md-3 col-xs-3'>
                                                <p><b>SUBJECT: </b><br><?= htmlspecialchars($view_upload_subject) ?></p>
                                            </div>
                                            <div class='col-md-3 col-xs-3'>
                                                <p><b>CLASS: </b><br><?= htmlspecialchars($view_upload_class) ?></p>
                                            </div>
                                            <div class='col-md-3 col-xs-3'>
                                                <p><b>TERM: </b><br><?= htmlspecialchars($view_upload_term) ?></p>
                                            </div>
                                            <div class='col-md-3 col-xs-3'>
                                                <p><b>SESSION: </b><br><?= htmlspecialchars($view_upload_session) ?></p>
                                            </div>                                                                                
                                        </div>
                                        <table class='table table-bordered'>
                                            <thead>
                                                <tr>
                                                    <th>S/N</th>
                                                    <th>Reg No</th>
                                                    <th>Name</th>
                                                    <th>1ST CA</th>
                                                    <th>2ND CA</th>
                                                    <th>Exam</th>
                                                    <th>Total</th>
                                                    <th>Rank</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                            <?php
                                            while ($result = mysqli_fetch_assoc($run_query)) {
                                                $i++;
                                                $reg_no = htmlspecialchars($result['reg_number']);
                                                $name = htmlspecialchars($result['name']);
                                                $ca1 = $result['ca1'];
                                                $ca2 = $result['ca2'];
                                                $exam = $result['exam'];
                                                $total = $result['subject_total'];
                                                $rank = $result['subject_rank'];
                                                ?>
                                                <tr>
                                                    <td><?= $i ?></td>
                                                    <td class='warning'><?= $reg_no ?></td>
                                                    <td><?= $name ?></td>
                                                    <td class='info'><?= $ca1 ?></td>
                                                    <td class='error'><?= $ca2 ?></td>
                                                    <td class='success'><?= $exam ?></td>
                                                    <td class='success'><?= $total ?></td>
                                                    <td class='bg-primary'><?= $rank ?></td>
                                                    <td>
                                                        <button class='btn btn-sm btn-warning edit-btn' 
                                                                data-regno='<?= $reg_no ?>'
                                                                data-name='<?= $name ?>'
                                                                data-ca1='<?= $ca1 ?>'
                                                                data-ca2='<?= $ca2 ?>'
                                                                data-exam='<?= $exam ?>'
                                                                data-class='<?= htmlspecialchars($view_upload_class) ?>'
                                                                data-subject='<?= htmlspecialchars($view_upload_subject) ?>'
                                                                data-term='<?= htmlspecialchars($view_upload_term) ?>'
                                                                data-session='<?= htmlspecialchars($view_upload_session) ?>'
                                                                onclick='openEditModal(this)'>Edit</button>
                                                    </td>
                                                </tr>
                                            <?php } ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                                <?php
                            } else {
                                $_SESSION['msg'] = "Results Not Uploaded";
                                $_SESSION['type'] = "error";
                            }
                            $stmt->close();
                        }
                    }

                    // POST ACTION TO UPDATE RESULTS
                    if (isset($_POST['update_result_btn'])) {
                        $reg_no = $_POST['edit_reg_no'];
                        $ca1 = $_POST['edit_ca1'];
                        $ca2 = $_POST['edit_ca2'];
                        $exam = $_POST['edit_exam'];
                        $class = $_POST['edit_class'];
                        $subject = $_POST['edit_subject'];
                        $term = $_POST['edit_term'];
                        $session = $_POST['edit_session'];
                        $total = $ca1 + $ca2 + $exam;

                        $stmt = $connection->prepare("UPDATE `results1` 
                                                     SET `ca1` = ?, `ca2` = ?, `exam` = ?, `subject_total` = ?
                                                     WHERE `reg_number` = ? 
                                                     AND `class` = ? 
                                                     AND `subjects` = ? 
                                                     AND `term` = ? 
                                                     AND `session` = ?");
                        $stmt->bind_param("iiiisssss", $ca1, $ca2, $exam, $total, $reg_no, $class, $subject, $term, $session);
                        $success = $stmt->execute();

                        if ($success === true) {
                            $_SESSION['msg'] = "Result Updated Successfully";
                            $_SESSION['type'] = "success";
                        } else {
                            $_SESSION['msg'] = "Failed to Update Result";
                            $_SESSION['type'] = "error";
                        }
                        $stmt->close();
                    }

                    // POST ACTION TO DELETE UPLOADED RESULTS
                    if (isset($_POST['del_upload_btn'])) {
                        $view_upload_class = $_POST['view_upload_class'];
                        $view_upload_subject = $_POST['view_upload_subject'];
                        $view_upload_term = $_POST['view_upload_term'];
                        $view_upload_session = $_POST['view_upload_session'];

                        if (empty($view_upload_class)) {
                            $_SESSION['msg'] = "Please Select Class";
                            $_SESSION['type'] = "error";
                        } elseif (empty($view_upload_subject)) {
                            $_SESSION['msg'] = "Please Select Subject";
                            $_SESSION['type'] = "error";
                        } elseif (empty($view_upload_term)) {
                            $_SESSION['msg'] = "Please Select Term";
                            $_SESSION['type'] = "error";
                        } else {
                            $stmt = $connection->prepare("DELETE FROM `results1` 
                                                         WHERE `class` = ? 
                                                         AND `term` = ? 
                                                         AND `session` = ? 
                                                         AND `subjects` = ?");
                            $stmt->bind_param("ssss", $view_upload_class, $view_upload_term, $view_upload_session, $view_upload_subject);
                            $success = $stmt->execute();

                            if ($success === true) {
                                $_SESSION['msg'] = "Uploaded Results Deleted Successfully";
                                $_SESSION['type'] = "success";
                            } else {
                                $_SESSION['msg'] = "Uploaded Results Unable to Delete";
                                $_SESSION['type'] = "error";
                            }
                            $stmt->close();
                        }
                    }
                    ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Edit Modal -->
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="editModalLabel">Edit Result</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form method="POST" action="">
                <div class="modal-body">
                    <input type="hidden" name="edit_reg_no" id="edit_reg_no">
                    <input type="hidden" name="edit_class" id="edit_class">
                    <input type="hidden" name="edit_subject" id="edit_subject">
                    <input type="hidden" name="edit_term" id="edit_term">
                    <input type="hidden" name="edit_session" id="edit_session">
                    <div class="form-group">
                        <label>Student Name</label>
                        <input type="text" class="form-control" id="edit_name" readonly>
                    </div>
                    <div class="form-group">
                        <label>1st CA</label>
                        <input type="number" class="form-control" name="edit_ca1" id="edit_ca1" required>
                    </div>
                    <div class="form-group">
                        <label>2nd CA</label>
                        <input type="number" class="form-control" name="edit_ca2" id="edit_ca2" required>
                    </div>
                    <div class="form-group">
                        <label>Exam</label>
                        <input type="number" class="form-control" name="edit_exam" id="edit_exam" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <input type="submit" name="update_result_btn" class="btn btn-primary" value="Update">
                </div>
            </form>
        </div>
    </div>
</div>

<!-- JavaScript for Edit Functionality -->
<script>
function openEditModal(button) {
    const regNo = button.getAttribute('data-regno');
    const name = button.getAttribute('data-name');
    const ca1 = button.getAttribute('data-ca1');
    const ca2 = button.getAttribute('data-ca2');
    const exam = button.getAttribute('data-exam');
    const className = button.getAttribute('data-class');
    const subject = button.getAttribute('data-subject');
    const term = button.getAttribute('data-term');
    const session = button.getAttribute('data-session');

    document.getElementById('edit_reg_no').value = regNo;
    document.getElementById('edit_name').value = name;
    document.getElementById('edit_ca1').value = ca1;
    document.getElementById('edit_ca2').value = ca2;
    document.getElementById('edit_exam').value = exam;
    document.getElementById('edit_class').value = className;
    document.getElementById('edit_subject').value = subject;
    document.getElementById('edit_term').value = term;
    document.getElementById('edit_session').value = session;

    $('#editModal').modal('show');
}

function printTable() {
    var printContents = document.getElementById('printableArea').innerHTML;
    var originalContents = document.body.innerHTML;
    document.body.innerHTML = printContents;
    window.print();
    document.body.innerHTML = originalContents;
}
</script>