<?php

function getSubjectwiseAttendanceStats($conn_rjllearning_specific, $institution_id, $academic_id, $userid, $branch_id, $class_id, $section_id, $subject_id, $min_date, $max_date) {
    // Get total students
    $sql_total_students = "SELECT COUNT(*) AS total_students FROM students WHERE institution_id = ? and user_id=?";
    $array_params = [$institution_id, $userid];

    if ($branch_id != 'all') {
        $sql_total_students .= " AND branch_id = ?";
        $array_params[] = $branch_id;
    }

    if ($class_id != 'all') {
        $sql_total_students .= " AND class_id = ?";
        $array_params[] = $class_id;
    }

    if ($section_id != 'all') {
        $sql_total_students .= " AND section_id = ?";
        $array_params[] = $section_id;
    }

    $stmt = $conn_rjllearning_specific->prepare($sql_total_students);
    $stmt->execute($array_params);
    $total_students_result = $stmt->fetch();
    $total_students = $total_students_result['total_students'];

    // Get attendance summary
    $possible_values = ['H', 'P', 'A', 'L'];

    $sql_attendance_summary = "SELECT date, value,subject_id, COUNT(*) AS attendance_summary 
                               FROM student_attendance_subjectwise 
                               WHERE institution_id = ? and student_id=?";
    $array_params = [$institution_id, $userid];

    if ($branch_id != 'all') {
        $sql_attendance_summary .= " AND branch_id = ?";
        $array_params[] = $branch_id;
    }

    if ($class_id != 'all') {
        $sql_attendance_summary .= " AND class_id = ?";
        $array_params[] = $class_id;
    }

    if ($section_id != 'all') {
        $sql_attendance_summary .= " AND section_id = ?";
        $array_params[] = $section_id;
    }

    if ($subject_id != 'all') {
        $sql_attendance_summary .= " AND subject_id = ?";
        $array_params[] = $subject_id;
    }

    if ($min_date === $max_date) {
        $sql_attendance_summary .= " AND date = ?";
        $array_params[] = $min_date;
    } else {
        $sql_attendance_summary .= " AND date BETWEEN ? AND ?";
        $array_params[] = $min_date;
        $array_params[] = $max_date;
    }

    $sql_attendance_summary .= " GROUP BY date, value";


    $stmt = $conn_rjllearning_specific->prepare($sql_attendance_summary);
    $stmt->execute($array_params);
    $attendance_summary_results = $stmt->fetchAll();
// VAR_DUMP($attendance_summary_results);
    // Initialize arrays to store attendance summary
    $attendance_summary = array_fill_keys($possible_values, 0);
    $attendance_counts_separate = [];

    foreach ($attendance_summary_results as $row) {
        $date = $row['date'];
        $value = $row['value'];
         $subject_id = $row['subject_id'];  
        $count = $row['attendance_summary'];
              $subject_info = getSubject($conn_rjllearning_specific, $institution_id, $subject_id);
        if (!isset($attendance_counts_separate[$subject_id])) {
            $attendance_counts_separate[$subject_id] = [
                'subject_id' => $subject_id,
                'subject_name'=>$subject_info['subject_name'],
                'dates' => []
            ];
        }

        if (!isset($attendance_counts_separate[$subject_id]['dates'][$date])) {
            $attendance_counts_separate[$subject_id]['dates'][$date] = array_fill_keys($possible_values, 0);
        }

        // Increment attendance value for the subject on this date
        $attendance_counts_separate[$subject_id]['dates'][$date][$value] = $count;
    }

    // Ensure that all dates within the range are represented
    $current_date = isset($min_date) ? strtotime($min_date) : strtotime('today');
    $end_date = isset($max_date) ? strtotime($max_date) : strtotime('today');

    while ($current_date <= $end_date) {
        $date = date('Y-m-d', $current_date);
        if (!isset($attendance_counts_separate[$date])) {
            $attendance_counts_separate[$date] = array_fill_keys($possible_values, 0);
        }
        $current_date = strtotime('+1 day', $current_date);
    }

   $attendance_counts_separate = array_filter($attendance_counts_separate, function ($counts) {
    // Check if 'dates' key exists and is an array
    return isset($counts['dates']) && is_array($counts['dates']) && array_sum(array_map('array_sum', $counts['dates'])) > 0;
});

// Reindex the array to remove subject ID keys and turn it into an indexed array
$attendance_counts_separate = array_values($attendance_counts_separate);

    // Calculate total marked days
  // SQL query to count distinct marked days for each subject
$sql_total_marked_days = "
    SELECT subject_id, COUNT(DISTINCT date) AS total_marked_days 
    FROM student_attendance_subjectwise 
    WHERE institution_id = ? AND student_id = ?";
$array_params = [$institution_id, $userid];

if ($branch_id != 'all') {
    $sql_total_marked_days .= " AND branch_id = ?";
    $array_params[] = $branch_id;
}

if ($class_id != 'all') {
    $sql_total_marked_days .= " AND class_id = ?";
    $array_params[] = $class_id;
}

if ($section_id != 'all') {
    $sql_total_marked_days .= " AND section_id = ?";
    $array_params[] = $section_id;
}

// Remove the filter for subject_id to get counts for all subjects
$sql_total_marked_days .= " AND date BETWEEN ? AND ? GROUP BY subject_id";
$array_params[] = $min_date;
$array_params[] = $max_date;

// Prepare and execute the query
$stmt = $conn_rjllearning_specific->prepare($sql_total_marked_days);
$stmt->execute($array_params);

// Fetch all results
$total_marked_days_results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Initialize the attendance counts array
$total_maked_days_subjectwise = [];

foreach ($total_marked_days_results as $result) {
    $subject_id = $result['subject_id'];
    $total_marked_days = $result['total_marked_days'];

    // Get subject information using the function
    $subject_info = getSubject($conn_rjllearning_specific, $institution_id, $subject_id);

    // Store the results in the attendance counts separate array
    $total_maked_days_subjectwise[] = [
        'subject_info' => $subject_info, // Store all subject info returned from the function
        'total_marked_days' => $total_marked_days
    ];
}

// You can now use $attendance_counts_separate to build your final response
// Initialize attendance variables to zero or appropriate defaults
$total_present = 0;
$total_late = 0;
$total_half_day = 0;
$total_absent = 0;


    // Get total marked attendance
$sql_subjects = "SELECT id, subject_name FROM subject_info WHERE institution_id = ?";
$subject_stmt = $conn_rjllearning_specific->prepare($sql_subjects);
$subject_stmt->execute([$institution_id]);
$subjects = $subject_stmt->fetchAll(PDO::FETCH_KEY_PAIR); // Fetches as [subject_id => subject_name]

// SQL query to get total marked attendance per subject
$sql_total_marked_attendance = "
    SELECT subject_id, 
           SUM(CASE WHEN value = 'P' THEN 1 ELSE 0 END) AS total_present,
           SUM(CASE WHEN value = 'L' THEN 1 ELSE 0 END) AS total_late,
           SUM(CASE WHEN value = 'H' THEN 1 ELSE 0 END) AS total_half_day,
           SUM(CASE WHEN value = 'A' THEN 1 ELSE 0 END) AS total_absent,
           COUNT(*) AS total_marked_attendance 
    FROM student_attendance_subjectwise 
    WHERE institution_id = ?
    and student_id=?
";

// Initialize parameters array
$array_params = [$institution_id,$userid];

// Conditional parameters
if ($branch_id != 'all') {
    $sql_total_marked_attendance .= " AND branch_id = ?";
    $array_params[] = $branch_id;
}

if ($class_id != 'all') {
    $sql_total_marked_attendance .= " AND class_id = ?";
    $array_params[] = $class_id;
}

if ($section_id != 'all') {
    $sql_total_marked_attendance .= " AND section_id = ?";
    $array_params[] = $section_id;
}

// Date range filter
$sql_total_marked_attendance .= " AND date BETWEEN ? AND ?";
$array_params[] = $min_date;
$array_params[] = $max_date;

// Group by subject_id to count attendance per subject
$sql_total_marked_attendance .= " GROUP BY subject_id";

// Prepare and execute the query
$stmt = $conn_rjllearning_specific->prepare($sql_total_marked_attendance);
$stmt->execute($array_params);

// Fetch the results
$total_marked_attendance_results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Initialize the attendance percentages array
$attendance_percentages = [];

// Calculate attendance percentages for each subject
foreach ($total_marked_attendance_results as $result) {
    $subject_id = $result['subject_id'];
    $total_marked_attendance = $result['total_marked_attendance'];

    // Get attendance counts directly from the result
    $total_present = $result['total_present'];
    $total_late = $result['total_late'];
    $total_half_day = $result['total_half_day'];
    $total_absent = $result['total_absent'];

    // Calculate percentages
    $attendance_percentages_subject = [
        'P' => $total_marked_attendance != 0 ? round(($total_present / $total_marked_attendance) * 100) : 0,
        'L' => $total_marked_attendance != 0 ? round(($total_late / $total_marked_attendance) * 100) : 0,
        'H' => $total_marked_attendance != 0 ? round(($total_half_day / $total_marked_attendance) * 100) : 0,
        'A' => $total_marked_attendance != 0 ? round(($total_absent / $total_marked_attendance) * 100) : 0,
    ];
 $subject_info = getSubject($conn_rjllearning_specific, $institution_id, $subject_id);
    // Store the results in the desired structure
    $attendance_percentages[] = [
        'subject_info' => $subject_info,
        'attendance_percentages' => $attendance_percentages_subject,
    ];
}
    // Calculate marked students
    $total_marked_students = $total_present + $total_late + $total_half_day + $total_absent;

    // Calculate unmarked students
    $unmarked_students = $total_students > $total_marked_students ? $total_students - $total_marked_students : 0;

    // Get total attendance record
  // SQL query to count total attendance records by subject_id
// Fetch all attendance records based on the specified filters
$sql_total_attendance_record = "
    SELECT subject_id, COUNT(*) AS total_attendance 
    FROM student_attendance_subjectwise 
    WHERE institution_id = ?  AND class_id = ? AND section_id = ? AND branch_id = ? 
    AND date BETWEEN ? AND ? 
    GROUP BY subject_id"; // Group by subject_id to count attendance

// Initialize parameters array
$array_params = [$institution_id, $class_id, $section_id, $branch_id, $min_date, $max_date];

// Prepare and execute the query
$stmt = $conn_rjllearning_specific->prepare($sql_total_attendance_record);
$stmt->execute($array_params);

// Fetch the results
$total_attendance_record_results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Initialize the attendance records array
$attendance_records = [];

// Store the results in the desired structure
foreach ($total_attendance_record_results as $result) {
    $subject_id = $result['subject_id'];
    $total_attendance = $result['total_attendance'];

    // Get subject information using the getSubject function
    $subject_info = getSubject($conn_rjllearning_specific, $institution_id, $subject_id);

    // Store the results in the desired format
    $attendance_records[] = [
        'subject_info' => $subject_info,  // Assuming getSubject returns an array with subject details
        'total_attendance' => $total_attendance,
    ];
}






    // Prepare the result array
    $result = [
        'total_marked_days' => $total_maked_days_subjectwise,
        'attendance_counts_separate' => $attendance_counts_separate,
        'attendance_percentages' => $attendance_percentages,
        'total_attendance_record' => $attendance_records,
        
    ];

    return $result;
}





function checkAttendanceSystemAndFetchAttendance($conn_rjllearning_specific, $institution_id, $academic_id, $userid, $branch_id, $class_id, $section_id, $subject_id, $min_date, $max_date, $search_string, $student_id, $from_date, $to_date) {
    // Query to check the attendance system type
    $sql_check_attendance_system = "SELECT attendance_system FROM institution_global_settings WHERE institution_id = ? and branch_id=?";
    $stmt = $conn_rjllearning_specific->prepare($sql_check_attendance_system);
    $stmt->execute([$institution_id,$branch_id]);
    $result = $stmt->fetch();

    if ($result && isset($result['attendance_system'])) {
        $attendance_system = $result['attendance_system'];
     
        if ($attendance_system === 'subject_wise') {
            // Call the subject-wise attendance function
            $attendance_data['subject'] = getSubjectwiseAttendanceStats($conn_rjllearning_specific, $institution_id, $academic_id, $userid, $branch_id, $class_id, $section_id, $subject_id, $min_date, $max_date);
            successreturn($attendance_data);
        } elseif ($attendance_system === 'day_wise') {
            // Call the day-wise attendance function
            $attendance_data['day'] = getattendance($conn_rjllearning_specific, $institution_id, $academic_id, $search_string, $branch_id, $class_id, $section_id, $student_id, $from_date, $to_date);
            successreturn($attendance_data);
        } else {
            // Handle case where attendance system type is not recognized
            errorreturn('Invalid attendance system type.');
        }
    } else {
        // Handle case where attendance system type could not be determined
        errorreturn('Attendance system type not found.');
    }
}
