<?php
function fetchTeachersTimetableWithClassSection($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $userid)
{
    // Fetch faculty ID based on user ID
    $faculty_query = "SELECT id FROM faculty_info WHERE userid = ? AND institution_id = ? AND branch_id = ?";
    $faculty_stmt = $conn_rjllearning_specific->prepare($faculty_query);
    $faculty_stmt->execute([$userid, $institution_id, $branch_id]);
    $faculty_info = $faculty_stmt->fetch(PDO::FETCH_ASSOC);

    if (!$faculty_info) {
        return errorreturn("Faculty not found.");
    }

    $faculty_id = $faculty_info['id'];

    // Fetch timetable details
    $sql_timetable = "
        SELECT * 
        FROM timetable 
        WHERE institution_id = ? 
          AND branch_id = ? 
          AND faculty_id = ? 
          AND type = 'faculty_role'
        ORDER BY period_start ASC
    ";
    $stmt = $conn_rjllearning_specific->prepare($sql_timetable);
    $stmt->execute([$institution_id, $branch_id, $faculty_id]);
    $rows = $stmt->fetchAll();

    if (empty($rows)) {
        return false;
    }

    $timetable_info = [];
    $currentDay = date('N'); // Get current day (1=Monday to 7=Sunday)
    $currentTime = date('H:i:s');

    $currentPeriod = null;
    $nextPeriod = null;

    foreach ($rows as $entry) {
        // Ensure 'day' is valid before unserializing
        $days = is_string($entry['day']) ? unserialize($entry['day']) : [];

        if (is_array($days) && in_array($currentDay, $days)) {
            // Check if the current time falls within the period
            if ($currentTime >= $entry['period_start'] && $currentTime < $entry['end_time']) {
                $currentPeriod = [
                    'class_id' => getClass($conn_rjllearning_specific, $institution_id, $entry['class_id']),
                    'section_id' => getSection($conn_rjllearning_specific, $institution_id, $entry['section_id']),
                    'subject_id' => getSubject($conn_rjllearning_specific, $institution_id, $entry['subject_id']),
                    'period_start' => $entry['period_start'],
                    'end_time' => $entry['end_time'],
                    'day' => $days
                ];
            }

            // Find the next period after the current time
            if ($entry['period_start'] > $currentTime && !$nextPeriod) {
                $nextPeriod = [
                    'class_id' => getClass($conn_rjllearning_specific, $institution_id, $entry['class_id']),
                    'section_id' => getSection($conn_rjllearning_specific, $institution_id, $entry['section_id']),
                    'subject_id' => getSubject($conn_rjllearning_specific, $institution_id, $entry['subject_id']),
                    'period_start' => $entry['period_start'],
                    'end_time' => $entry['end_time'],
                    'day' => $days
                ];
            }

            // Store timetable information for the day
            $timetable_info[] = [
                'class_id' => getClass($conn_rjllearning_specific, $institution_id, $entry['class_id']),
                'section_id' => getSection($conn_rjllearning_specific, $institution_id, $entry['section_id']),
                'subject_id' => getSubject($conn_rjllearning_specific, $institution_id, $entry['subject_id']),
                'period_start' => $entry['period_start'],
                'end_time' => $entry['end_time'],
                'day' => $days
            ];
        }
    }

    // If no next period is found, reset to the first period of the next day
    if (!$nextPeriod) {
        $nextPeriod = reset($timetable_info);
    }

    // Response structure
    return [
        'faculty_id' => $faculty_id,
        'current_period' => $currentPeriod,
        'next_period' => $nextPeriod,
        'timetable_info' => $timetable_info
    ];
}




function fetchAssignmentSubmissionStatus(
    $conn_rjllearning_specific,
    $institution_id,
    $branch_id,
    $userid
) {
    // Step 1: Fetch faculty ID from the faculty_info table
    $faculty_query = "SELECT id FROM faculty_info WHERE userid = ? AND institution_id = ? AND branch_id = ?";
    $faculty_stmt = $conn_rjllearning_specific->prepare($faculty_query);
    $faculty_stmt->execute([$userid, $institution_id, $branch_id]);
    $faculty_info = $faculty_stmt->fetch(PDO::FETCH_ASSOC);

    if (!$faculty_info) {
        return errorreturn("Faculty not found.");
    }

    $faculty_id = $faculty_info['id'];

    // Step 2: Fetch all assigned class-section combinations for the teacher
    $class_section_query = "
        SELECT DISTINCT class_id, section_id
        FROM timetable
        WHERE faculty_id = ? AND institution_id = ? AND branch_id = ?";
    $class_section_stmt = $conn_rjllearning_specific->prepare($class_section_query);
    $class_section_stmt->execute([$faculty_id, $institution_id, $branch_id]);
    $class_sections = $class_section_stmt->fetchAll(PDO::FETCH_ASSOC);

    if (empty($class_sections)) {
        return errorreturn("No classes assigned to the teacher.");
    }

    // Step 3: Prepare dates for assignment submission checks (today and yesterday)
    $today = date('Y-m-d');
    $yesterday = date('Y-m-d', strtotime('-1 day'));

    // Step 4: Initialize response arrays
    $today_status = [];
    $yesterday_status = [];

    // Step 5: Loop through each class-section combination
    foreach ($class_sections as $cs) {
        $class_id = $cs['class_id'];
        $section_id = $cs['section_id'];

        // Step 5.1: Fetch all assignments for the current class and section
        $assignment_query = "
            SELECT id AS assignment_id, name 
            FROM assignments 
            WHERE class_id = ? AND section_id = ? AND institution_id = ? AND branch_id = ?";
        $assignment_stmt = $conn_rjllearning_specific->prepare($assignment_query);
        $assignment_stmt->execute([$class_id, $section_id, $institution_id, $branch_id]);
        $assignments = $assignment_stmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($assignments as $assignment) {
            $assignment_id = $assignment['assignment_id'];

            // Step 5.2: Get total students in the class-section
            $student_count_query = "
                SELECT COUNT(*) AS total_students 
                FROM students 
                WHERE class_id = ? AND section_id = ? AND institution_id = ? AND branch_id = ?";
            $student_count_stmt = $conn_rjllearning_specific->prepare($student_count_query);
            $student_count_stmt->execute([$class_id, $section_id, $institution_id, $branch_id]);
            $student_count = $student_count_stmt->fetch(PDO::FETCH_ASSOC)['total_students'];

            // Step 5.3: Get submitted assignment count for today
            $submitted_today_query = "
                SELECT COUNT(*) AS submitted_count 
                FROM assignment_submission 
                WHERE assignment_id = ? AND date_created = ?";
            $submitted_today_stmt = $conn_rjllearning_specific->prepare($submitted_today_query);
            $submitted_today_stmt->execute([$assignment_id, $today]);
            $submitted_today = $submitted_today_stmt->fetch(PDO::FETCH_ASSOC)['submitted_count'];

            // Step 5.4: Get submitted assignment count for yesterday
            $submitted_yesterday_query = "
                SELECT COUNT(*) AS submitted_count 
                FROM assignment_submission 
                WHERE assignment_id = ? AND date_created = ?";
            $submitted_yesterday_stmt = $conn_rjllearning_specific->prepare($submitted_yesterday_query);
            $submitted_yesterday_stmt->execute([$assignment_id, $yesterday]);
            $submitted_yesterday = $submitted_yesterday_stmt->fetch(PDO::FETCH_ASSOC)['submitted_count'];

            // Step 5.5: Add data to respective arrays
            $today_status[] = [
                'assignment_id' => $assignment_id,
                'assignment_title' => $assignment['name'],
                'class_id' => $class_id,
                'section_id' => $section_id,
                'total_students' => $student_count,
                'submitted' => $submitted_today
            ];

            $yesterday_status[] = [
                'assignment_id' => $assignment_id,
                'assignment_title' => $assignment['name'],
                'class_id' => $class_id,
                'section_id' => $section_id,
                'total_students' => $student_count,
                'submitted' => $submitted_yesterday
            ];
        }
    }

    // Step 6: Return response
    return [
        'today_status' => $today_status,
        'yesterday_status' => $yesterday_status
    ];
}





function fetchUnmarkedAttendance(
    $conn_rjllearning_specific,
    $institution_id,
    $branch_id,
    $userid
) {
   
    // Step 1: Fetch faculty ID from the faculty_info table
    $faculty_query = "SELECT id FROM faculty_info WHERE userid = ? AND institution_id = ? AND branch_id = ?";
    $faculty_stmt = $conn_rjllearning_specific->prepare($faculty_query);
    $faculty_stmt->execute([$userid, $institution_id, $branch_id]);
    $faculty_info = $faculty_stmt->fetch(PDO::FETCH_ASSOC);

    if (!$faculty_info) {
        return errorreturn("Faculty not found.");
    }

    $faculty_id = $faculty_info['id'];

    // Step 2: Fetch all assigned class-section combinations for the teacher
    $class_section_query = "
        SELECT DISTINCT class_id, section_id
        FROM timetable
        WHERE faculty_id = ? AND institution_id = ? AND branch_id = ?";
    $class_section_stmt = $conn_rjllearning_specific->prepare($class_section_query);
    $class_section_stmt->execute([$faculty_id, $institution_id, $branch_id]);
    $class_sections = $class_section_stmt->fetchAll(PDO::FETCH_ASSOC);

    if (empty($class_sections)) {
        return errorreturn("No classes assigned to the teacher.");
    }

    // Step 3: Prepare dates for attendance checks (today and yesterday)
    $today = date('Y-m-d');
    $yesterday = date('Y-m-d', strtotime('-1 day'));

    // Step 4: Initialize response arrays
    $unmarked_today = [];
    $unmarked_yesterday = [];

    // Step 5: Loop through each class-section combination
    foreach ($class_sections as $cs) {
        $class_id = $cs['class_id'];
        $section_id = $cs['section_id'];

        // Step 5.1: Fetch students for the current class and section
        $student_query = "
            SELECT id, user_id, name
            FROM students 
            WHERE class_id = ? AND section_id = ? AND institution_id = ? AND branch_id = ?";
        $student_stmt = $conn_rjllearning_specific->prepare($student_query);
        $student_stmt->execute([$class_id, $section_id, $institution_id, $branch_id]);
        $students = $student_stmt->fetchAll(PDO::FETCH_ASSOC);

        // Step 5.2: Check attendance for each student
        foreach ($students as $student) {
            $attendance_query = "
                SELECT date 
                FROM student_attendance_daywise 
                WHERE student_id = ? AND class_id = ? AND section_id = ? 
                  AND institution_id = ? AND branch_id = ? 
                  AND date IN (?, ?)";
            $attendance_stmt = $conn_rjllearning_specific->prepare($attendance_query);
            $attendance_stmt->execute([
                $student['user_id'],
                $class_id,
                $section_id,
                $institution_id,
                $branch_id,
                $today,
                $yesterday
            ]);
            $attendance_dates = $attendance_stmt->fetchAll(PDO::FETCH_COLUMN);
            $class_info = getClass($conn_rjllearning_specific, $institution_id, $class_id);
            $section_info = getSection($conn_rjllearning_specific, $institution_id, $section_id);
                    // 'subject_id' => getSubject($conn_rjllearning_specific, $institution_id, $entry['subject_id']),

            // Step 5.3: Check for unmarked attendance for today
            if (!in_array($today, $attendance_dates)) {
                $unmarked_today[] = [
                    'user_id' => $student['user_id'],
                    'class_id' => $class_info,
                    'section_id' => $section_info,
                    'name' => $student['name'] ,
                    'unmarked_date' => $today
                ];
            }

            // Step 5.4: Check for unmarked attendance for yesterday
            if (!in_array($yesterday, $attendance_dates)) {
                $unmarked_yesterday[] = [
                    'user_id' => $student['user_id'],
                    'class_id' => $class_info,
                    'section_id' => $section_info,
                    'name' => $student['name'] ,
                    'unmarked_date' => $yesterday
                ];
            }
        }
    }

    // Step 6: Return response
    return [
        'unmarked_today' => $unmarked_today,
        'unmarked_yesterday' => $unmarked_yesterday
    ];
}

