<?php
// function geStudenIDCardTemplate($conn_rjllearning,$conn_rjllearning_specific, $institution_id,$branch_id,$class_id,$section_id,$student_id,$display_filter){
 
//     $SqlTemplate = "SELECT * FROM   print_settings WHERE institution_id = ? AND status = ?";
//     $StmtTemplate = $conn_rjllearning_specific->prepare($SqlTemplate);
//     $StmtTemplate->execute(array($institution_id,1));
//     $result = $StmtTemplate->fetchAll();
  
//     if(count($result) < 1){
//       errorreturn("Template not found. contact admin");
//     } 

//     if (count($result) >= 1) {
//         $primary_color =  $result[0]['primary_color'];
//         $secondary_color =  $result[0]['secondary_color'];
//         $id_card_template_selected =  $result[0]['id_card_template_selected'];
//     }    
     
//     $SqlStudentTemplate = "SELECT * FROM  student_id_cards WHERE institution_id = ? AND selected_template  =  ? AND status = ?";
//     $array_params = [$institution_id,$id_card_template_selected,1];
//      if ($class_id == 'all') {
//             $SqlStudentTemplate .= "";
//     } else if ($class_id !=  null  && $class_id != 'all') {
//             $SqlStudentTemplate .= " AND class_id = ? ";
//             $array_params[] = $class_id;
//     }
        
//     if ($section_id == 'all') {
//             $SqlStudentTemplate .= "";
//     } else if ($section_id !=  null  && $section_id != 'all') {
//             $SqlStudentTemplate .= " AND section_id = ? ";
//             $array_params[] = $section_id;
//     }
   
    
//     $StmtStudentTemplate = $conn_rjllearning_specific->prepare($SqlStudentTemplate);
//     $StmtStudentTemplate->execute($array_params);
//     $StudentResult = $StmtStudentTemplate->fetchAll();
//     //   print_r($StudentResult);die();
//     if(count($StudentResult) < 1){
//       errorreturn("Template not found for this class or section. contact admin");
//     } 

//     if(count($StudentResult) >= 1){
//         $data_printed = json_decode($StudentResult[0]['data_printed']);
//     }
    
//  $SqlStudents = "SELECT * FROM students WHERE institution_id = ? AND branch_id = ? AND status = ?";
// $array_params = [$institution_id, $branch_id, 1];

// // Handling class_id
// if ($class_id != null && $class_id != 'all') {
//     $SqlStudents .= " AND class_id = ?";
//     $array_params[] = $class_id;
// }

// // Handling section_id
// if ($section_id != null && $section_id != 'all') {
//     $SqlStudents .= " AND section_id = ?";
//     $array_params[] = $section_id;
// }

// // Handling student_id
// if ($student_id != null && $student_id != 'all') {
//     $SqlStudents .= " AND id = ?";
//     $array_params[] = $student_id;
// }

// // Prepare and execute the query
// $StmtStudents = $conn_rjllearning_specific->prepare($SqlStudents);
// $StmtStudents->execute($array_params);
// $StudentsResult = $StmtStudents->fetchAll(PDO::FETCH_ASSOC); // Fetch as associative array

// $student_data_array = [];

// foreach ($StudentsResult as $student_rows) {
//     // Initialize an empty array to store filtered student data
//     $filtered_student_data = [];

//     // Iterate over the data_printed keys to filter the student data
//     foreach ($data_printed as $key => $value) {
//         if (isset($student_rows[$key])) {
//             // Handle specific fields like 'student_profile_image', 'class_id', 'section_id'
//             if ($key === 'student_profile_image') {
//                 if ($student_rows['student_profile_image'] != null && !is_array($student_rows['student_profile_image'])) {
//                     $data_attachment = json_decode($student_rows['student_profile_image'], true);
//                     $filePath = $data_attachment['filepath'];
//                     $filtered_student_data['student_profile_image'] = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);
//                 }
//             } elseif ($key === 'class_id') {
//                 $filtered_student_data['class'] = getClass($conn_rjllearning_specific, $institution_id, $student_rows['class_id']);
//             } elseif ($key === 'section_id') {
//                 $filtered_student_data['section'] = getSection($conn_rjllearning_specific, $institution_id, $student_rows['section_id']);
//             } else {
//                 // Map other fields directly
//                 $filtered_student_data['student_id'] = $student_rows['id'];
//                 $filtered_student_data[$key] = $student_rows[$key];
//             }
//         }
  
//     }
//       // Only add if there is filtered data
//     if (!empty($filtered_student_data)) {
//         $student_data_array[] = array("student"=>$filtered_student_data);
//     }
   
// }

// // Return the full array with all students' filtered data
// return $student_data_array;

    
// }



function geStudenIDCardTemplate($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $branch_id, $class_id, $section_id, $student_id, $display_filter) {
    // Step 1: Fetch ID card template settings for the institution
    $SqlTemplate = "SELECT * FROM print_settings WHERE institution_id = ? AND status = ?";
    $StmtTemplate = $conn_rjllearning_specific->prepare($SqlTemplate);
    $StmtTemplate->execute(array($institution_id, 1));
    $result = $StmtTemplate->fetchAll();

    if (count($result) < 1) {
        errorreturn("Template not found. Contact admin.");
    }

    if (count($result) >= 1) {
        $primary_color = $result[0]['primary_color'];
        $secondary_color = $result[0]['secondary_color'];
        $id_card_template_selected = $result[0]['id_card_template_selected'];
    }

    // Step 2: Fetch student ID card template data for the selected template
    $SqlStudentTemplate = "SELECT * FROM student_id_cards WHERE institution_id = ? AND selected_template = ? AND status = ?";
    $array_params = [$institution_id, $id_card_template_selected, 1];

    // Handle class and section filters
    if ($class_id != 'all') {
        $SqlStudentTemplate .= " AND class_id = ?";
        $array_params[] = $class_id;
    }
    if ($section_id != 'all') {
        $SqlStudentTemplate .= " AND section_id = ?";
        $array_params[] = $section_id;
    }

    $StmtStudentTemplate = $conn_rjllearning_specific->prepare($SqlStudentTemplate);
    $StmtStudentTemplate->execute($array_params);
    $StudentResult = $StmtStudentTemplate->fetchAll();

    if (count($StudentResult) < 1) {
        errorreturn("Template not found for this class or section. Contact admin.");
    }

    if (count($StudentResult) >= 1) {
        $data_printed = json_decode($StudentResult[0]['data_printed'], true);
    }

    // Step 3: Fetch students based on the given criteria (institution, branch, class, section, student)
    $SqlStudents = "SELECT * FROM students WHERE institution_id = ? AND branch_id = ? AND status = ?";
    $array_params = [$institution_id, $branch_id, 1];

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

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

    if ($student_id != 'all') {
        $SqlStudents .= " AND id = ?";
        $array_params[] = $student_id;
    }

    $StmtStudents = $conn_rjllearning_specific->prepare($SqlStudents);
    $StmtStudents->execute($array_params);
    $StudentsResult = $StmtStudents->fetchAll(PDO::FETCH_ASSOC);

    $student_data_array = [];

    // Step 4: Process each student and filter the data according to the template
    foreach ($StudentsResult as $student_rows) {
        $filtered_student_data = [];

        foreach ($data_printed as $key => $value) {
            if (isset($student_rows[$key])) {
                // Handle specific fields like 'student_profile_image', 'class_id', 'section_id'
                if ($key === 'student_profile_image') {
                    if (!empty($student_rows['student_profile_image'])) {
                        $data_attachment = json_decode($student_rows['student_profile_image'], true);
                        $filePath = $data_attachment['filepath'];
                        $filtered_student_data['student_profile_image'] = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);
                    }
                } elseif ($key === 'class_id') {
                    $filtered_student_data['class'] = getClass($conn_rjllearning_specific, $institution_id, $student_rows['class_id']);
                } elseif ($key === 'section_id') {
                    $filtered_student_data['section'] = getSection($conn_rjllearning_specific, $institution_id, $student_rows['section_id']);
                } elseif ($key === 'address_line_1') {
                    // Convert the address to valid UTF-8
                    $addrress = $student_rows['address_line_1'];
                    $address = mb_convert_encoding($addrress, 'UTF-8', 'UTF-8');
                    $address = str_replace("?", " ", $address);
                    $filtered_student_data['address_line_1'] = $address;
                } else {
                    $filtered_student_data[$key] = $student_rows[$key];
                }
            }
        }

        // Add filtered data to the result array if not empty
        if (!empty($filtered_student_data)) {
            $student_data_array[] = ["student" => $filtered_student_data];
        }
    }

    return $student_data_array;
}


    
?>