<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'>
                    <!-- FILTER FORM -->
                    <form class='noprint' method='POST' action='' id='view_result'>
                        <div class='row'>
                            <!-- Class -->
                            <div class='col-md-3'>
                                <div class='input-group'>
                                    <span class='input-group-addon'>Class:</span>
                                    <select class='form-control' name='view_upload_class' id='class-select' required>
                                        <option selected disabled>Select Class</option>
                                        <?php
                                        $query = "SELECT * FROM `classes`";
                                        $run_query = mysqli_query($connection, $query);
                                        if (mysqli_num_rows($run_query) > 0) {
                                            while ($result = mysqli_fetch_assoc($run_query)) {
                                                echo "<option value='{$result['classes']}'>{$result['classes']}</option>";
                                            }
                                        }
                                        ?>
                                    </select>
                                </div>
                            </div>

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

                            <!-- Term -->
                            <div class='col-md-3'>
                                <div class='input-group'>
                                    <span class='input-group-addon'>Term:</span>
                                    <select class='form-control' name='view_upload_term'>
                                        <option selected><?php echo $select ?></option>
                                        <?php
                                        $term_array = ["First Term","Second Term","Third Term"];
                                        foreach ($term_array as $term) echo "<option>$term</option>";
                                        ?>
                                    </select>
                                </div>
                            </div>

                            <!-- Session -->
                            <div class='col-md-3'>
                                <div class='input-group'>
                                    <span class='input-group-addon'>Session:</span>
                                    <select class='form-control' name='view_upload_session'>
                                        <?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)){
                                                echo "<option>{$result['sessions']}</option>";
                                            }
                                        }
                                        ?>
                                    </select>
                                </div>
                            </div>

                            <div class='col-md-3 mt-2'>
                                <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 type="button" onclick='printTable()' class='btn btn-sm btn-primary'>Print</button>
                            </div>
                        </div>
                    </form>
                    <br/>

                    <?php
                    // ----------------------------
                    // 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($view_upload_class == $select || $view_upload_subject == $select || $view_upload_term == $select){
                            $_SESSION['msg']="Please fill all fields"; $_SESSION['type']="error";
                        } else {
                            $query = "SELECT r.reg_number, r.ca1, r.ca2, r.exam, r.subject_total, r.subject_rank,
                                        CONCAT(s.firstname,' ',s.othername,' ',s.lastname) AS student_name
                                      FROM results1 r
                                      LEFT JOIN students s ON s.reg_number = r.reg_number
                                      WHERE r.class='$view_upload_class' 
                                      AND r.term='$view_upload_term' 
                                      AND r.session='$view_upload_session' 
                                      AND r.subjects='$view_upload_subject'
                                      ORDER BY r.subject_rank ASC";
                            $run_query = mysqli_query($connection, $query);

                            if(mysqli_num_rows($run_query) > 0){
                                $i = 0;
                    ?>

                    <!-- PRINTABLE TABLE -->
                    <div id='printableArea'>
                        <form method="POST" id="results_form">
                        <div class="text-right mb-2">
                            
                            <button type="submit" name="bulk_delete_btn" class="btn btn-sm btn-danger" onclick="return confirm('Delete selected results?')">Bulk Delete</button>
                            
                        </div>
                        
                        <div class="row text-center" style="margin-bottom:15px;">
    <div class="col-md-12 col-xs-12">
        <h4 style="margin:0;"><b><?= strtoupper($school_name) ?></b></h4>
        <h5 style="margin:3px 0;">EXAM SCORE SHEET</h5>
        <h6 style="margin:3px 0;">By <?= $full_name ?></h6>
    </div>
</div>

<div class="row text-center" style="margin-bottom:15px;">
    <div class="col-md-3 col-xs-6">
        <p><b>SUBJECT:</b><br><?= strtoupper($view_upload_subject) ?></p>
    </div>

    <div class="col-md-3 col-xs-6">
        <p><b>CLASS:</b><br><?= strtoupper($view_upload_class) ?></p>
    </div>

    <div class="col-md-3 col-xs-6">
        <p><b>TERM:</b><br><?= $view_upload_term ?></p>
    </div>

    <div class="col-md-3 col-xs-6">
        <p><b>SESSION:</b><br><?= $view_upload_session ?></p>
    </div>
</div>

                        <div class='table-responsive'>
                            <table class='table table-bordered'>
                                <thead>
                                    <tr>
                                        <th><input type="checkbox" id="checkAll"></th>
                                        <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 = $result['reg_number'];
                                        $name = trim($result['student_name']) ?: 'UNKNOWN STUDENT';
                                        $ca1 = $result['ca1'];
                                        $ca2 = $result['ca2'];
                                        $exam = $result['exam'];
                                        $total = $result['subject_total'];
                                        $rank = $result['subject_rank'];
                                    ?>
                                    <tr>
                                        <td><input type="checkbox" name="bulk_delete[]" value="<?= $reg_no ?>"></td>
                                        <td><?= $i ?></td>
                                        <td><?= $reg_no ?></td>
                                        <td><?= $name ?></td>
                                        <td><?= $ca1 ?></td>
                                        <td><?= $ca2 ?></td>
                                        <td><?= $exam ?></td>
                                        <td><?= $total ?></td>
                                        <td><?= $rank ?></td>
                                        <td>
                                            <!-- EDIT -->
                                            <button type="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='<?= $view_upload_class ?>'
                                                data-subject='<?= $view_upload_subject ?>'
                                                data-term='<?= $view_upload_term ?>'
                                                data-session='<?= $view_upload_session ?>'
                                                onclick='openEditModal(this)'>Edit</button>

                                            <!-- DELETE SINGLE -->
                                            <form method="POST" style="display:inline;">
                                                <input type="hidden" name="delete_reg_no" value="<?= $reg_no ?>">
                                                <input type="hidden" name="delete_class" value="<?= $view_upload_class ?>">
                                                <input type="hidden" name="delete_subject" value="<?= $view_upload_subject ?>">
                                                <input type="hidden" name="delete_term" value="<?= $view_upload_term ?>">
                                                <input type="hidden" name="delete_session" value="<?= $view_upload_session ?>">
                                                <button type="submit" name="delete_single_btn" class="btn btn-sm btn-danger" onclick="return confirm('Delete this result?')">Delete</button>
                                            </form>
                                        </td>
                                    </tr>
                                    <?php } ?>
                                </tbody>
                            </table>
                        </div>
                        </form>
                    </div>

                    <?php 
                            } else { 
                                echo "<p class='text-center'>No results found</p>";
                            }
                        }
                    }

                    // ----------------------------
                    // UPDATE SINGLE RESULT
                    // ----------------------------
                    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;

                        $query = "UPDATE results1 SET ca1='$ca1', ca2='$ca2', exam='$exam', subject_total='$total'
                                  WHERE reg_number='$reg_no' AND class='$class' AND subjects='$subject' 
                                  AND term='$term' AND session='$session'";
                        $run_query = mysqli_query($connection,$query);

                        if($run_query) { $_SESSION['msg']="Result Updated"; $_SESSION['type']="success"; }
                        else { $_SESSION['msg']="Failed to update"; $_SESSION['type']="error"; }
                    }

                    // ----------------------------
                    // DELETE SINGLE RESULT
                    // ----------------------------
                    if(isset($_POST['delete_single_btn'])){
                        $reg_no = $_POST['delete_reg_no'];
                        $class = $_POST['delete_class'];
                        $subject = $_POST['delete_subject'];
                        $term = $_POST['delete_term'];
                        $session = $_POST['delete_session'];

                        $query = "DELETE FROM results1 WHERE reg_number='$reg_no' AND class='$class' AND subjects='$subject'
                                  AND term='$term' AND session='$session'";
                        $run_query = mysqli_query($connection,$query);

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

                    // ----------------------------
                    // BULK DELETE RESULTS
                    // ----------------------------
                    if(isset($_POST['bulk_delete_btn']) && isset($_POST['bulk_delete'])){
                        $ids = $_POST['bulk_delete'];
                        $ids = array_map('mysqli_real_escape_string', array_fill(0,count($ids),$connection), $ids);
                        $ids_str = "'" . implode("','",$ids) . "'";
                        $query = "DELETE FROM results1 WHERE reg_number IN ($ids_str)";
                        $run_query = mysqli_query($connection,$query);

                        if($run_query){ $_SESSION['msg']="Selected results deleted"; $_SESSION['type']="success"; }
                        else{ $_SESSION['msg']="Bulk delete failed"; $_SESSION['type']="error"; }
                    }
                    ?>

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

<!-- EDIT MODAL -->
<div class="modal fade" id="editModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <div class="modal-header">
                    <h4>Edit Result</h4>
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                </div>
                <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>Name</label>
                        <input type="text" id="edit_name" class="form-control" readonly>
                    </div>
                    <div class="form-group">
                        <label>1st CA</label>
                        <input type="number" name="edit_ca1" id="edit_ca1" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>2nd CA</label>
                        <input type="number" name="edit_ca2" id="edit_ca2" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Exam</label>
                        <input type="number" name="edit_exam" id="edit_exam" class="form-control" 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>

<script>
function openEditModal(btn){
    document.getElementById('edit_reg_no').value = btn.getAttribute('data-regno');
    document.getElementById('edit_name').value = btn.getAttribute('data-name');
    document.getElementById('edit_ca1').value = btn.getAttribute('data-ca1');
    document.getElementById('edit_ca2').value = btn.getAttribute('data-ca2');
    document.getElementById('edit_exam').value = btn.getAttribute('data-exam');
    document.getElementById('edit_class').value = btn.getAttribute('data-class');
    document.getElementById('edit_subject').value = btn.getAttribute('data-subject');
    document.getElementById('edit_term').value = btn.getAttribute('data-term');
    document.getElementById('edit_session').value = btn.getAttribute('data-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;
}

// CHECK/UNCHECK ALL
document.getElementById('checkAll').addEventListener('click',function(){
    const boxes = document.querySelectorAll('input[name="bulk_delete[]"]');
    boxes.forEach(b=>b.checked=this.checked);
});
</script>
