<?php
if (isset($_POST['save_attendance_btn'])) {

    $roll_call_date = inject_checker($connection, $_POST['roll_call_date']);
    $current_term = inject_checker($connection, $_POST['current_term']);
    $current_session = inject_checker($connection, $_POST['current_session']);
    $total_num = (int)$_POST["total_num"];

    if (empty($roll_call_date)) {
        $_SESSION['msg'] = "Date field cannot be empty.";
        $_SESSION['type'] = "danger";
        header("Location: class_attendance"); 
        exit;
    }

    // Check for duplicate entry (using one student's class as reference)
    $sample_class = inject_checker($connection, $_POST['attendance_class'][0]);

    $check_stmt = $connection->prepare("SELECT id FROM student_attendance WHERE date = ? AND term = ? AND session = ? AND class = ?");
    $check_stmt->bind_param("ssss", $roll_call_date, $current_term, $current_session, $sample_class);
    $check_stmt->execute();
    $check_stmt->store_result();

    if ($check_stmt->num_rows > 0) {
        $_SESSION['msg'] = "This Roll Call has already been recorded for the selected class.";
        $_SESSION['type'] = "danger";
    } else {
        $query = "INSERT INTO student_attendance (reg_number, name, date, term, session, class, roll_call) VALUES ";
        $values = [];
        $params = [];
        $types = "";

        for ($j = 0; $j < $total_num; $j++) {
            $reg_no = inject_checker($connection, $_POST['attendance_reg_no'][$j]);
            $name = inject_checker($connection, $_POST['attendance_name'][$j]);
            $class = inject_checker($connection, $_POST['attendance_class'][$j]);
            $roll_call = inject_checker($connection, $_POST['class_roll_call'][$j]);

            $values[] = "(?, ?, ?, ?, ?, ?, ?)";
            $types .= "sssssss";
            array_push($params, $reg_no, $name, $roll_call_date, $current_term, $current_session, $class, $roll_call);
        }

        $query .= implode(", ", $values);
        $stmt = $connection->prepare($query);
        $stmt->bind_param($types, ...$params);

        if ($stmt->execute()) {
            $_SESSION['msg'] = "Roll Call saved successfully.";
            $_SESSION['type'] = "success";
        } else {
            $_SESSION['msg'] = "Roll Call failed to save.";
            $_SESSION['type'] = "danger";
        }
    }

    // Optional: redirect to prevent resubmission
    header("Location: class_attendance");
    exit;
}
?>


<div class='page-title'>
  <div>
    <h1><i class='fa fa-laptop'></i> Class Attendance</h1>
    <p>Save Daily Roll Call</p>
  </div>
</div>

<div class='card'>
    <div class='panel panel-primary'>
        <div class='panel-heading'>
            <h4 class='text-center'>Class Attendance</h4>
        </div>
        <div class='panel-body'>
            <form method='POST' action=''>
                <div class='row'>
                    <div class='col-md-4'>
                        <div class='input-group'>
                            <span class='input-group-addon' id='basic-addon2'>Student Class:</span>
                            <select class='form-control' name='attendance_class'>
                                <option selected ><?php echo $select; ?></option>
                                    <?php
                                        $role_id_current  = (int)($_SESSION['role'] ?? 0);
                                        $staff_id_current = (int)($_SESSION['staff'] ?? 0);
                                        $is_admin_user    = !empty($is_super_admin) || in_array($role_id_current, [1, 2, 3, 11]);

                                        if ($is_admin_user) {
                                            $query = " SELECT * FROM `classes` ORDER BY classes ASC ";
                                        } else {
                                            $query = " SELECT DISTINCT class AS classes FROM `teacher_classes` WHERE teacher_id = '$staff_id_current' ORDER BY class ASC ";
                                        }
                                        $run_query = mysqli_query($connection, $query);
                                        if($run_query && mysqli_num_rows($run_query) > 0){
                                            while($result = mysqli_fetch_assoc($run_query)){
                                                $attendance = htmlspecialchars($result['classes']);
                                                echo "<option value='{$attendance}'>{$attendance}</option>";
                                            }
                                        } else {
                                            echo "<option value='' disabled>No class assigned to you</option>";
                                        }
                                    ?>
                            </select>
                        </div>
                    </div>
                    <div class='col-md-2'>
                        <input type='submit' name='view_members_btn' value='VIEW CLASS MEMBERS' class='btn btn-primary' />
                    </div>

                </div>
            </form>
            <hr />
            <div class='row' style="margin-bottom: 10px;">
                <!-- Import CSV -->
                <div class='col-md-6'>
                    <form method="POST" action="import_attendance" enctype="multipart/form-data">
                        <div style="display:flex; flex-wrap:wrap; gap:8px; align-items:flex-end;">
                            <div>
                                <label style="font-size:12px; font-weight:600; display:block; margin-bottom:3px;">Date</label>
                                <input type="text" name="roll_call_date" class="form-control input-sm" placeholder="e.g. 21/11/2024" style="width:130px;" required />
                            </div>
                            <div>
                                <label style="font-size:12px; font-weight:600; display:block; margin-bottom:3px;">Class</label>
                                <select name="attendance_class" class="form-control input-sm" style="width:120px;" required>
                                    <option value="">-- Class --</option>
                                    <?php
                                    if ($is_admin_user) {
                                        $qc = mysqli_query($connection, "SELECT classes FROM classes ORDER BY classes ASC");
                                    } else {
                                        $qc = mysqli_query($connection, "SELECT DISTINCT class AS classes FROM teacher_classes WHERE teacher_id = '$staff_id_current' ORDER BY class ASC");
                                    }
                                    if ($qc && mysqli_num_rows($qc) > 0) {
                                        while ($rc = mysqli_fetch_assoc($qc)) {
                                            $c_name = htmlspecialchars($rc['classes']);
                                            echo "<option value='{$c_name}'>{$c_name}</option>";
                                        }
                                    } else {
                                        echo "<option value='' disabled>No class assigned</option>";
                                    }
                                    ?>
                                </select>
                            </div>
                            <div>
                                <label style="font-size:12px; font-weight:600; display:block; margin-bottom:3px;">CSV File</label>
                                <input type="file" name="import_file" class="form-control input-sm" accept=".csv" required style="width:160px;" />
                            </div>
                            <input type="hidden" name="current_term" value="<?php echo $current_term; ?>" />
                            <input type="hidden" name="current_session" value="<?php echo $current_session; ?>" />
                            <div>
                                <button type="submit" name="import_attendance_btn" class="btn btn-warning btn-sm">
                                    <i class='fa fa-upload'></i> Import CSV
                                </button>
                            </div>
                        </div>
                        <small class="text-muted">CSV columns: Reg No, Name, Class, Status (Present/Absent)</small>
                    </form>
                </div>

                <!-- Export CSV -->
                <div class='col-md-6 text-right'>
                    <form method="POST" action="export_attendance">
                        <div style="display:flex; flex-wrap:wrap; gap:8px; align-items:flex-end; justify-content:flex-end;">
                            <div>
                                <label style="font-size:12px; font-weight:600; display:block; margin-bottom:3px;">Date</label>
                                <input type="text" name="roll_call_date" class="form-control input-sm" placeholder="e.g. 21/11/2024" style="width:130px;" required />
                            </div>
                            <div>
                                <label style="font-size:12px; font-weight:600; display:block; margin-bottom:3px;">Class</label>
                                <select name="attendance_class" class="form-control input-sm" style="width:120px;" required>
                                    <option value="">-- Class --</option>
                                    <?php
                                    $qc2 = mysqli_query($connection, "SELECT classes FROM classes");
                                    while ($rc2 = mysqli_fetch_assoc($qc2)) {
                                        echo "<option value='{$rc2['classes']}'>{$rc2['classes']}</option>";
                                    }
                                    ?>
                                </select>
                            </div>
                            <input type="hidden" name="current_term" value="<?php echo $current_term; ?>" />
                            <input type="hidden" name="current_session" value="<?php echo $current_session; ?>" />
                            <div>
                                <button type="submit" name="export_attendance_btn" class="btn btn-success btn-sm">
                                    <i class='fa fa-download'></i> Export CSV
                                </button>
                            </div>
                        </div>
                        <small class="text-muted">&nbsp;</small>
                    </form>
                </div>
            </div>
            <br />
        </div>
    </div>
<?php
    if(isset($_POST['view_members_btn'])){
        $attendance_class = $_POST['attendance_class'];
        
        if($attendance_class == $select){
            $msg = "<p><b>Please select class for roll call</b></p>";
        }else{
            $query = " SELECT * FROM `students` WHERE `class` = '{$attendance_class}' ";
            $run_query = mysqli_query($connection, $query);
            
            if(mysqli_num_rows($run_query) > 0){
                $r = 1; $i = 0;
                echo "
                <form method='POST' action=''>
                    <div class='row'>
                        <div class='col-md-4'>
                            <div class='input-group'>
                                <span class='input-group-addon' id='basic-addon2'>Date</span>
                                <input type='text' name='roll_call_date' class='form-control' placeholder='Type roll call date e.g 21/11/2017' />
                            </div>
                        </div>
                        
                        <div class='col-md-4'>
                            <div class='input-group'>
                                <span class='input-group-addon' id='basic-addon2'>Term:</span>
                                <select class='form-control' name='current_term'>
                                    <option value='First Term' " . ($current_term === 'First Term' ? 'selected' : '') . ">First Term</option>
                                    <option value='Second Term' " . ($current_term === 'Second Term' ? 'selected' : '') . ">Second Term</option>
                                    <option value='Third Term' " . ($current_term === 'Third Term' ? 'selected' : '') . ">Third Term</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class='col-md-4'>
                            <div class='input-group'>
                                <span class='input-group-addon' id='basic-addon2'>Session:</span>
                                <select class='form-control' name='current_session'>";
                                    ///// POST ACTION TO DISPLAY CURRRENT TERM /////////////
                                    $sql = " SELECT * FROM `current_season` ";
                                    $run_sql = mysqli_query($connection, $sql);
                                    if(mysqli_num_rows($run_sql) == 1){
                                        while($result = mysqli_fetch_assoc($run_sql)){
                                            $show_current_session = $result['current_session'];
                                            echo"
                                                <option>{$show_current_session}</option>
                                            ";
                                        }
                                    }
                                    echo"
                                </select>
                            </div>
                        </div>
                    </div>
                    <br />
                    <div class='table-responsive'>
                        <table class='table table-bordered'>
                            <thead>
                                <tr>
                                    <th>S/N</th>
                                    <th>REG NO</th>
                                    <th>NAME</th>
                                    <th>CLASS</th>
                                    <th>ROLL CALL</th>
                                </tr>
                            </thead>
                ";
                while($result = mysqli_fetch_assoc($run_query)){
                    $reg_no = $result['reg_number'];
                    $fname = $result['firstname'];
                    $lname = $result['lastname'];
                    $oname = $result['othername'];
                    $class = $result['class'];
                    
                    echo "
                        <tbody>
                            <tr>
                                <td>{$r}</td>
                                <td>
                                    <input type='text' name='attendance_reg_no[]' value='{$reg_no}' class='form-control' readonly />
                                </td>
                                <td>
                                    <input type='text' name='attendance_name[]' value='{$fname} {$lname} {$oname}' class='form-control' readonly />
                                </td>
                                <td>
                                    <input type='text' name='attendance_class[]' value='{$class}' class='form-control' readonly />
                                </td>
                                <td>
                                    <select class='form-control' name='class_roll_call[]'>
                                        <option>Present</option>
                                        <option>Absent</option>
                                    </select>
                                </td>
                            </tr>
                        </tbody>
                    ";
                    $r++;$i++;
                }
                echo "
                        </table>
                    </div>
                    <input type='hidden' name='total_num' value='{$i}' />
                    <input name='save_attendance_btn' type='submit' class='btn btn-primary btn-sm' value='Save Roll Call' />
                </form>
"; ?>

<?php
            } else {
                echo "<p class='text-danger text-center'><b>No Records of students in {$attendance_class}</b></p>";
            }
        }
    }
?>

</div>