<?php
// function getUnmarkedAttendanceDaywiseClassStudent($conn, $institution_id, $branch_id, $date) {
//     $data = [];
//     $today = date('Y-m-d');

//     // Step 1: Get distinct branch IDs from student_attendance_daywise
//     $branch_ids = [];

//   if ($branch_id === 'all') {
//     // Get all unique branch_ids from attendance records for this date
//     $stmt = $conn->prepare("SELECT DISTINCT branch_id FROM student_attendance_daywise WHERE institution_id = ? AND date = ?");
//     $stmt->execute([$institution_id, $date]);
//     $branch_ids = $stmt->fetchAll(PDO::FETCH_COLUMN);
//     } else {
//         // Use only the specific branch as array
//         $branch_ids = [$branch_id];
//     }

//     // print_r($branch_ids);
//     foreach ($branch_ids as $branch_id_actual) {
//         // Step 2: Get all class-section mappings (common across branches)
//         $sql = "
//             SELECT 
//                 c.id AS class_id,
//                 c.classname AS class_name,
//                 s.id AS section_id,
//                 s.section_name AS section_name
//             FROM class_info c
//             JOIN section_info s ON c.institution_id = s.institution_id
//             WHERE 
//                 c.institution_id = ? AND 
//                 c.status = 1 AND 
//                 s.status = 1
//         ";

//         $stmt = $conn->prepare($sql);
//         $stmt->execute([$institution_id]);
//         $classSections = $stmt->fetchAll(PDO::FETCH_ASSOC);

//         foreach ($classSections as $row) {
//             $class_id = $row['class_id'];
//             $section_id = $row['section_id'];
//             $class_name = $row['class_name'];
//             $section_name = $row['section_name'];

//             // Step 3: Get student count
//             if ($date == $today) {
//                 $sql_students = "SELECT COUNT(*) FROM students 
//                     WHERE class_id = ? AND section_id = ? AND institution_id = ? AND branch_id = ? AND status = 1";
//                 $studentStmt = $conn->prepare($sql_students);
//                 $studentStmt->execute([$class_id, $section_id, $institution_id, $branch_id_actual]);
//             } else {
//                 $sql_students = "SELECT COUNT(*) FROM cache_academic_students_data 
//                     WHERE class_id = ? AND section_id = ? AND institution_id = ? AND date = ? AND branch_id = ?";
//                 $studentStmt = $conn->prepare($sql_students);
//                 $studentStmt->execute([$class_id, $section_id, $institution_id, $date, $branch_id_actual]);
//             }

//             $total_students = (int)$studentStmt->fetchColumn();

//             // Step 4: Get marked student count from attendance
//             $sql_attendance = "SELECT COUNT(*) FROM student_attendance_daywise 
//                 WHERE class_id = ? AND section_id = ? AND institution_id = ? AND branch_id = ? AND date = ?";
//             $attendanceStmt = $conn->prepare($sql_attendance);
//             $attendanceStmt->execute([$class_id, $section_id, $institution_id, $branch_id_actual, $date]);
//             $marked_students = (int)$attendanceStmt->fetchColumn();

//             // Step 5: Compare and build data
//             $unmarked = $total_students - $marked_students;

//             if ($unmarked > 0) {
//                 $branch_info = getBranchInfo($conn, $institution_id, $branch_id_actual);

//                 $data[] = [
//                     'branch_id' => $branch_info,
//                     'class' => ['class_id' => $class_id, 'class_name' => $class_name],
//                     'section' => ['section_id' => $section_id, 'section_name' => $section_name],
//                     'total_students' => $total_students,
//                     'marked' => $marked_students,
//                     'unmarked' => $unmarked
//                 ];
//             }
//         }
//     }

//     return $data;
// }

function getUnmarkedAttendanceDaywiseClassStudent($conn, $institution_id, $branch_id, $date)
{
    $data = [];

    // Step 1: Fetch valid students with branch/class/section info
    $params = [$institution_id, $date, $date];
    $where_branch = '';
    if ($branch_id !== 'all') {
        $where_branch = " AND s.branch_id = ?";
        $params[] = $branch_id;
    }

    $sql_students_today = "
        SELECT s.id AS student_id, s.branch_id, s.class_id, s.section_id
        FROM students s
        WHERE s.institution_id = ?
          AND s.can_activate = 1
          AND s.date_admission <= ?
          AND (s.date_left > ? OR s.date_left IS NULL)
          $where_branch
    ";

    $sql_students_past = "
        SELECT s.id AS student_id, s.branch_id, cad.class_id, cad.section_id
        FROM students s
        JOIN (
            SELECT cad1.student_id, cad1.class_id, cad1.section_id
            FROM cache_academic_students_data cad1
            INNER JOIN (
                SELECT student_id, MAX(date) AS latest_date
                FROM cache_academic_students_data
                WHERE institution_id = ?
                  AND date <= ?
                GROUP BY student_id
            ) latest ON cad1.student_id = latest.student_id AND cad1.date = latest.latest_date
        ) cad ON s.id = cad.student_id
        WHERE s.institution_id = ?
          AND s.can_activate = 1
          AND s.date_admission <= ?
          AND (s.date_left > ? OR s.date_left IS NULL)
          $where_branch
    ";

    if ($date === date("Y-m-d")) {
        $stmt = $conn->prepare($sql_students_today);
        $stmt->execute($params);
    } else {
        $params = [$institution_id, $date, $institution_id, $date, $date];
        if ($branch_id !== 'all') {
            $params[] = $branch_id;
        }
        $stmt = $conn->prepare($sql_students_past);
        $stmt->execute($params);
    }

    $students = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (empty($students)) {
        return [];
    }

    // Step 2: Build groups
    $groups = [];
    $studentGroupMap = [];

    foreach ($students as $stu) {
        $key = "{$stu['branch_id']}_{$stu['class_id']}_{$stu['section_id']}";
        if (!isset($groups[$key])) {
            $groups[$key] = [
                'branch_id' => $stu['branch_id'],
                'class_id' => $stu['class_id'],
                'section_id' => $stu['section_id'],
                'students' => []
            ];
        }
        $groups[$key]['students'][] = $stu['student_id'];
        $studentGroupMap[$stu['student_id']] = $key;
    }

    $all_student_ids = array_keys($studentGroupMap);

    // Step 3: Fetch all marked attendance for given date and institution
    // Use only required students to limit data
    $chunks = array_chunk($all_student_ids, 1000); // avoid large IN clause
    $marked_ids = [];

    foreach ($chunks as $chunk) {
        $placeholders = implode(',', array_fill(0, count($chunk), '?'));
        $attendanceSql = "
            SELECT DISTINCT student_id 
            FROM student_attendance_daywise 
            WHERE institution_id = ? AND date = ? 
              AND student_id IN ($placeholders)
        ";
        $params = array_merge([$institution_id, $date], $chunk);
        $stmt = $conn->prepare($attendanceSql);
        $stmt->execute($params);
        $marked_ids = array_merge($marked_ids, $stmt->fetchAll(PDO::FETCH_COLUMN));
    }

    $marked_ids = array_flip($marked_ids); // For fast lookup

    // Step 4: Prepare final data
    foreach ($groups as $group_key => $group) {
        $total = count($group['students']);
        $marked = 0;

        foreach ($group['students'] as $sid) {
            if (isset($marked_ids[$sid])) {
                $marked++;
            }
        }

        $unmarked = $total - $marked;
        if ($unmarked <= 0) continue;

        // Fetch names
        $nameSql = "SELECT c.classname AS class_name, s.section_name 
                    FROM class_info c 
                    JOIN section_info s ON c.institution_id = s.institution_id AND s.id = ? 
                    WHERE c.id = ? AND c.institution_id = ? AND c.status = 1 AND s.status = 1";
        $nameStmt = $conn->prepare($nameSql);
        $nameStmt->execute([$group['section_id'], $group['class_id'], $institution_id]);
        $names = $nameStmt->fetch(PDO::FETCH_ASSOC);
        if (!$names) continue;

        $data[] = [
            'branch' => getBranchInfo($conn, $institution_id, $group['branch_id']),
            'class' => ['class_id' => $group['class_id'], 'class_name' => $names['class_name']],
            'section' => ['section_id' => $group['section_id'], 'section_name' => $names['section_name']],
            'total_students' => $total,
            'marked' => $marked,
            'unmarked' => $unmarked
        ];
    }

    return $data;
}
