<?php
try {
    require_once('source/session.php');
    require_once('source/error.php');
    require_once('source/dbconfig.php');
    require_once('source/function.php');

    // Create a database connection 
    $conn = new PDO("mysql:host=localhost;dbname=british_schdb_coll", "british_smt_user", "@British22*#");
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Fetch dynamic options for class, term, and year from the database
    $query = "SELECT DISTINCT class FROM attendance";
    $stmt = $conn->prepare($query);
    $stmt->execute();
    $classes = $stmt->fetchAll(PDO::FETCH_COLUMN);

    $query = "SELECT DISTINCT term FROM attendance";
    $stmt = $conn->prepare($query);
    $stmt->execute();
    $terms = $stmt->fetchAll(PDO::FETCH_COLUMN);

    $query = "SELECT DISTINCT year FROM attendance";
    $stmt = $conn->prepare($query);
    $stmt->execute();
    $years = $stmt->fetchAll(PDO::FETCH_COLUMN);

    // Initialize variables to store class, term, and year for display
    $page_title = '';
    $total_results_count = 0;
    $class = '';
    $term = '';
    $year = '';

    $comments_results = array();

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // Extract search data from the form
        $class = strip_tags($_POST['class']);
        $term = strip_tags($_POST['term']);
        $year = strip_tags($_POST['year']);

        // Retrieve comments from the database based on the search criteria
        $query = "SELECT id, name, registration_no, class, year, term, TeachersRemarks FROM attendance WHERE class = ? AND term = ? AND year = ?";
        $stmt = $conn->prepare($query);
        $stmt->execute([$class, $term, $year]);
        $comments_results = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Set page title
        $page_title = "Comments Modification Page";

        // Count of total comments
        $total_results_count_query = "SELECT COUNT(DISTINCT id) FROM attendance WHERE class = ? AND term = ? AND year = ?";
        $stmt = $conn->prepare($total_results_count_query);
        $stmt->execute([$class, $term, $year]);
        $total_results_count = $stmt->fetchColumn();

        // Handle form submissions for saving comments
        if (isset($_POST['save'])) {
            $new_comments = $_POST['new_comment'];
            $comment_ids = $_POST['id'];

            foreach ($comment_ids as $index => $id) {
                $new_comment = strip_tags($new_comments[$index]);
                $update_query = "UPDATE attendance SET TeachersRemarks = ? WHERE id = ?";
                $update_stmt = $conn->prepare($update_query);
                $update_stmt->execute([$new_comment, $id]);
            }
        }

        // Handle form submissions for deleting comments
        if (isset($_POST['delete'])) {
            $delete_id = $_POST['delete_id'];
            $delete_query = "DELETE FROM attendance WHERE id = ?";
            $delete_stmt = $conn->prepare($delete_query);
            $delete_stmt->execute([$delete_id]);
        }
    }
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
    die();
}
?>

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

<head>
      <meta charset="utf-8">
  <link rel="icon" 
      type="image/png" 
      href="https://rportal.lahs.com.ng/admin/sch_logo.png">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">
  <title>BRITISH LEARNER'S COLLEGE, OWERRI, IMO STATE: COMMENT MODIFICATION PAGE</title>
  <!-- Bootstrap core CSS-->
  
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <!-- select-->
  <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
    <!-- Your head section goes here -->
    <style>
        body {
            display: flex;
            align-items: center;
            justify-content: center;
            height: auto;
            margin: 10;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        table,
        th,
        td {
            border: 1px solid #ddd;
        }

        th,
        td {
            padding: 10px;
            text-align: left;
        }
    </style>
</head>

<body class="fixed-nav sticky-footer bg-dark" id="page-top">
    <!-- Your navigation goes here -->

    <div class="content-wrapper">
        <div class="container-fluid">
            <!-- Breadcrumbs go here -->

            <div class="row">
                <div class="col-lg-12">
                    <center>
                        <h2>Comments Modification Page</h2>
                        <?php
                        if (!empty($page_title)) {
                            echo "<p>You Are Modifying Teachers & Principal's/Head Teacher's Comments For:</p>";
                            echo "<p>Class: $class, Term: $term, Year: $year</p>";
                        }
                        ?>
                    </center>

                    <div class="form-container">
                        <!-- Your search form goes here -->
                        <form method="POST">
                            <div>
                                <label for="class">Class:</label>
                                <select id="class" name="class" required>
                                    <?php foreach ($classes as $class_option) : ?>
                                        <option value="<?php echo $class_option; ?>" <?php echo ($class_option === $class) ? 'selected' : ''; ?>><?php echo $class_option; ?></option>
                                    <?php endforeach; ?>
                                </select>

                                <label for="term">Term:</label>
                                <select id="term" name="term" required>
                                    <?php foreach ($terms as $term_option) : ?>
                                        <option value="<?php echo $term_option; ?>" <?php echo ($term_option === $term) ? 'selected' : ''; ?>><?php echo $term_option; ?></option>
                                    <?php endforeach; ?>
                                </select>

                                <label for="year">Year:</label>
                                <select id="year" name="year" required>
                                    <?php foreach ($years as $year_option) : ?>
                                        <option value="<?php echo $year_option; ?>" <?php echo ($year_option === $year) ? 'selected' : ''; ?>><?php echo $year_option; ?></option>
                                    <?php endforeach; ?>
                                </select>

                                <button type="submit">Search</button>
                            </div>
                        </form>

                        <div>
                            <p style="color: black; transition: color 0.3s; display: inline-block;">
                                <?php echo "Total Comments Count: $total_results_count"; ?>
                            </p> 
                            | 
                            <a href="main.php" style="color: red; display: inline-block; padding: 5px; border: 1px solid black; text-decoration: none; transition: color 0.3s, width 0.3s;" onmouseover="this.style.color='purple'; this.style.width='500px';" onmouseout="this.style.color='red'; this.style.width='auto';">
                                BACK TO ADMIN DASHBOARD
                            </a>
                                                    </div>

                        <?php
                        if (isset($comments_results)) {
                            // Display comments based on the search result
                            ?>
                            <form method="POST">
                                <table>
                                    <tr>
                                        <th>S/N</th>
                                        <th>Name of Student</th>
                                        <th>Admission No</th>
                                        <th>Teacher's Comment</th>
                                        <th>Action</th>
                                    </tr>
                                    <?php
                                    $serial_number = 1;
                                    foreach ($comments_results as $record) {
                                        ?>
                                        <tr>
                                            <td><?php echo $serial_number++; ?></td>
                                            <td><?php echo $record['name']; ?></td>
                                            <td><?php echo $record['registration_no']; ?></td>
                                            <td>
                                                <textarea name="new_comment[]" rows="3"
                                                    cols="30"><?php echo $record['TeachersRemarks']; ?></textarea>
                                                <input type="hidden" name="id[]" value="<?php echo $record['id']; ?>">
                                            </td>
                                            <td>
                                                <button type="submit" name="save">Save</button>
                                                |
                                                <button type="submit" name="delete"
                                                    onclick="return confirm('Are you sure you want to delete this record?')">Delete</button>
                                                <input type="hidden" name="delete_id"
                                                    value="<?php echo $record['id']; ?>">
                                            </td>
                                        </tr>
                                    <?php
                                }
                                ?>
                                </table>
                            </form>
                        <?php
                    }
                    ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Your footer goes here --> 

    <!-- Your scripts go here -->
</body>

</html>
