<?php
// require basic files
// validate jwt and other thing
// branch instituion and class are mandatory and cannot be all
// section can be all or specific
// student_id will either be null or specific

// template_id cannot be null, check if tmeplate id ewxists in common db  id card template info and is valid for that specific institution, get path
// grid will only be a whole number and greater than or equal to 1.

// get students info from it

// get branch info institution info


// call and get style function and put that in header

// call data function to print the id cards using grid

// Enable error display for debugging
ini_set('display_errors', 1);

// Include necessary files
require_once '../../../resources/base_path_include.php';
require_once $base_path_to_learning_resources  . "includes/connect.php";
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning . 'user_management/authenticate.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning_resources . 'idcard_template/template_1/template_function.php';
require_once $base_path_to_learning_resources . 'idcard_template/template_2/template_function.php';

require_once $base_path_to_learning . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';



// Validation and configuration
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

$postdata = json_decode(file_get_contents("php://input"), true);

checkIfNoPhpContentsReceive();

// Validate mandatory fields
if (
    !isset($postdata['institution_id']) || !checkIfIssetAndNotEmpty($postdata['institution_id']) ||
    !isset($postdata['branch_id']) || !checkIfIssetAndNotEmpty($postdata['branch_id']) ||
    !isset($postdata['class_id']) || !checkIfIssetAndNotEmpty($postdata['class_id']) ||
    !isset($postdata['template_id']) || !checkIfIssetAndNotEmpty($postdata['template_id']) ||
    !isset($postdata['grid']) || !is_numeric($postdata['grid']) || $postdata['grid'] < 1 ||
    !isset($postdata['api_signature']) || !checkIfIssetAndNotEmpty($postdata['api_signature']) ||
    !isset($postdata['jwt_token']) || !checkIfIssetAndNotEmpty($postdata['jwt_token']) ||
    !isset($postdata['function_type']) || !checkIfIssetAndNotEmpty($postdata['function_type'])
) {
    errorreturn("All fields are mandatory, and the grid must be a whole number greater than or equal to 1.");
}

// Validate JWT
validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);

$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;
$name = $jwt_validate->data->name;

// Retrieve parameters
$institution_id = trim($postdata['institution_id']);
$branch_id = trim($postdata['branch_id']);
$class_id = trim($postdata['class_id']);
$section_id = isset($postdata['section_id']) ? trim($postdata['section_id']) : 'all';
$student_id = isset($postdata['student_id']) ? trim($postdata['student_id']) : null;
$template_id = trim($postdata['template_id']);

$grid = $postdata['grid'];

// Specific DB Connection
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,['superadmin','admin'], $institution_id);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

// Validate academic session
$academicSessionId = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if (!$academicSessionId) {
    errorreturn("Invalid institution_id");
}

$academic_session = GetAcademicSessionName($conn_rjllearning_specific, $institution_id, $academicSessionId);
if (!$academic_session) {
    errorreturn("No active academic session found for the given institution.");
}

function getStudentDetails($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $branch_id, $class_id, $section_id, $student_id, $template_id, $academic_session, $export_type, $grid)
{

    // Validate the template_id
    // Start building the query
    $template_query = "SELECT path FROM id_card_template_info WHERE id = ?";

    // Initialize an array for query parameters
    $query_params = [$template_id];

    // Conditionally add the institution_id, workspace_id, and branch_id to the query and parameters

    // Check if institution_id is provided and append to query if necessary
    if (!empty($institution_id)) {
        $template_query .= " AND (institution_id = ? OR institution_id IS NULL)";
        $query_params[] = $institution_id;
    }

    // Check if workspace_id is provided
    if (!empty($workspace_id)) {
        $template_query .= " AND (workspace_id = ? OR workspace_id IS NULL)";
        $query_params[] = $workspace_id;
    }

    // Check if branch_id is provided
    if (!empty($branch_id)) {
        $template_query .= " AND (branch_id = ? OR branch_id IS NULL)";
        $query_params[] = $branch_id;
    }
    // Prepare and execute the query
    $template_stmt = $conn_rjllearning->prepare($template_query);
    $template_stmt->execute($query_params);

    // Fetch the result
    $template_result = $template_stmt->fetch(PDO::FETCH_ASSOC);

    // Check if the template exists
    if (!$template_result) {
        errorreturn("Invalid or non-existent template_id for the given parameters.");
    }

    // Get the template path
    $template_path = $template_result['path'];


    // Fetch student information
    $student_query = "SELECT id, name, dob,academic_id, fathername, admission_number, class_id, section_id, mobile, blood_group, address_line_1,gender, student_profile_image FROM students WHERE institution_id = ? AND branch_id = ? AND class_id = ? AND status = ? and can_activate = 1";
    $student_params = [$institution_id, $branch_id, $class_id, 1];

    if ($section_id == 'all') {
        $student_query .= "";
    } else if ($section_id != null && $section_id != 'all') {
        $student_query .= " AND section_id = ?";
        $student_params[] = $section_id;
    }

    if ($student_id == 'all') {
        $student_query .= "";
    } else if ($student_id != null && $student_id != 'all') {
        $student_query .= " AND id = ?";
        $student_params[] = $student_id;
    }


    $student_stmt = $conn_rjllearning_specific->prepare($student_query);
    $student_stmt->execute($student_params);
    $student_results = $student_stmt->fetchAll(PDO::FETCH_ASSOC);



    // Get institution and branch information
    $institution_info = getInstitution($conn_rjllearning, $institution_id);

    $additional_data = ['address', 'pincode', 'contact_number', 'email'];
    $branch_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $branch_id, $additional_data);

    // Format student data
    $student_info = [];
    foreach ($student_results as $student) {
        $class_info = getClass($conn_rjllearning_specific, $institution_id, $student['class_id']);

        $section_info = getSection($conn_rjllearning_specific, $institution_id, $student['section_id']);
        if (!empty($student['student_profile_image'])) {
            // Attempt to decode the JSON string
            $data_attachment = json_decode($student['student_profile_image'], true);

            // Check if decoding was successful and 'filepath' exists
            if (is_array($data_attachment) && isset($data_attachment['filepath'])) {
                $filePath = $data_attachment['filepath'];
                $student_image = displayFileFromS3(
                    $GLOBALS['s3_learning_bucket'],
                    $GLOBALS['learning_bucketName'],
                    $filePath,
                    1,
                    $GLOBALS['cloudFrontDomain']
                );
            }
        } else {
            // Handle cases where no profile image exists
            $student_image = null; // Or a default placeholder image URL
        }



        $student_info[] = [
            'student_id' => $student['id'],
            'student_name' => $student['name'],
            'dob' => $student['dob'],
            'gender' => $student['gender'],
            'fathername' => $student['fathername'],
            'admissionnumber' => $student['admission_number'],
            'class' => $class_info,
            'section' => $section_info,
            'phone' => $student['mobile'],
            'bloodgroup' => $student['blood_group'],
            'address' => $student['address_line_1'],
            'student_images' => $student_image


        ];
    }

    // Prepare the response data
    $response = [
        "institution_info" => $institution_info,
        "branch_info" => $branch_info,
        "academic_session" => $academic_session,
        "template_path" => $template_path,
        "students" => $student_info,
    ];
    if ($export_type == 'print') {

        if ($template_id == 1) {
            echo getIDCardTemplateData($institution_info, $branch_info, $academic_session, $student_info, $grid);
        } else {
            echo getIDCardTemplateDataSecond($institution_info, $branch_info, $academic_session, $student_info, $grid);
        }
    }
    // Return success response
    return $response;
}

if ($postdata['function_type'] == "generate_id_cards") {
    $export_type = (isset($postdata['export_type']) and !empty($postdata['export_type'])) ? trim($postdata['export_type']) : null;
    $success['data'] = getStudentDetails($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $branch_id, $class_id, $section_id, $student_id, $template_id, $academic_session, $export_type, $grid);
    if ($export_type == null) {
        successreturn($success);
    }
}
