<?php

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';
require_once $base_path_to_learning . 'students_api/modules/idcard/fetch_id_cards.php';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

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

checkIfNoPhpContentsReceive();

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['section_id']) || !checkIfIssetAndNotEmpty($postdata['section_id']) ||
    !isset($postdata['student_id']) || !checkIfIssetAndNotEmpty($postdata['student_id']) ||
    !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.");
}

// 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;



$institution_id = $jwt_validate->data->institution_id;
$branch_id = $jwt_validate->data->branch_id;
$class_id = $jwt_validate->data->class;
$section_id = $jwt_validate->data->section;

$specific_db_name = validateStudentAcess($conn_rjllearning, $role, $workspace_id, ["student"], null, null, $userid);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}
validateStudentClassSection($conn_rjllearning_specific, $userid, $institution_id, $branch_id, $class_id, $section_id);



$student_id = trim($postdata['student_id']);
$template_id = isset($postdata['template_id']) && !empty(trim($postdata['template_id'])) ? trim($postdata['template_id']) : 1;

$grid = 1; // Defaulting to 1 since it's a single student



// 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.");
}

// Fetch student details
function getSingleStudentDetails($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $branch_id, $class_id, $section_id, $student_id, $template_id, $academic_session)
{
    // Fetch template path
    $template_query = "SELECT path FROM id_card_template_info WHERE id = ? AND (institution_id = ? OR institution_id IS NULL)";
    $template_stmt = $conn_rjllearning->prepare($template_query);
    $template_stmt->execute([$template_id, $institution_id]);
    $template_result = $template_stmt->fetch(PDO::FETCH_ASSOC);



    if (!$template_result) {
        errorreturn("Invalid or non-existent template_id for the given institution.");
    }

    $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 section_id = ? AND id = ? AND status = 1 AND can_activate = 1";

    $student_stmt = $conn_rjllearning_specific->prepare($student_query);
    $student_stmt->execute([$institution_id, $branch_id, $class_id, $section_id, $student_id]);
    $student = $student_stmt->fetch(PDO::FETCH_ASSOC);

    if (!$student) {
        errorreturn("Student not found or inactive.");
    }

    $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);
    // Fetch additional details
    $class_info = getClass($conn_rjllearning_specific, $institution_id, $student['class_id']);
    $section_info = getSection($conn_rjllearning_specific, $institution_id, $student['section_id']);

    // Fetch student profile image
    $student_image = null;
    if (!empty($student['student_profile_image'])) {
        $data_attachment = json_decode($student['student_profile_image'], true);
        if (is_array($data_attachment) && isset($data_attachment['filepath'])) {
            $student_image = displayFileFromS3(
                $GLOBALS['s3_learning_bucket'],
                $GLOBALS['learning_bucketName'],
                $data_attachment['filepath'],
                1,
                $GLOBALS['cloudFrontDomain']
            );
        }
    }

    // Format student data
    $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 response
    $response = [
        "institution_info" => $institution_info,
        "branch_info" => $branch_info,
        "academic_session" => $academic_session,
        "template_path" => $template_path,
        "student" => $student_info
    ];

    // if ($export_type == 'print') {
        if ($template_id == 1) {
            echo get_IDCardTemplate1_Data($institution_info, $branch_info, $academic_session, $student_info, 1);
        } else {
            echo get_IDCard_TemplateData_2($institution_info, $branch_info, $academic_session, $student_info, 1);
        }
    // }

    return $response;
}

// Generate ID card for a specific student
if ($postdata['function_type'] == "generate_id_card") {
    // $export_type = isset($postdata['export_type']) ? trim($postdata['export_type']) : null;
    $success['data'] = getSingleStudentDetails($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $branch_id, $class_id, $section_id, $student_id, $template_id, $academic_session);
}
