<?php
ini_set('display_errors', 1);



require_once '../../../resources/base_path_include.php';

require_once $base_path_to_learning_resources  . "includes/connect.php"; // use require for mandatory files
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';

//valdation file
require_once $base_path_to_learning_resources . 'lib/validate_function.php';
require_once $base_path_to_learning . 'user_management/authenticate.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
//db access function
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';

//aws image store
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning . "vendor/autoload.php";

require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';
require_once $base_path_to_learning . 'students_api/student_api_function/common_api_function.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';


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

if (

      !isset($postdata['api_signature']) or !checkIfIssetAndNotEmpty($postdata['api_signature']) or 
      !isset($postdata['function_type']) or !checkIfIssetAndNotEmpty($postdata['function_type'])  or 
      !isset($postdata['jwt_token']) or  !checkIfIssetAndNotEmpty($postdata['jwt_token'])) {
    errorreturn("All * fields are required.");
}

validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
//then workspace_id is iin decodede data of jwt use from there
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;

$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);



require_once $base_path_to_learning . 'functions/get_branch_functions.php';


function getStudentProfile($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $student_id,$export_type, $template_id, $academic_session)
{
    // Fetch student profile details
    $query = "SELECT * FROM students WHERE institution_id = ? AND user_id = ?";
    $params = [$institution_id, $student_id];
    
    $stmt = $conn_rjllearning_specific->prepare($query);
    $stmt->execute($params);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // echo hello;

    if (!$result) {
        return null; // Return null if no student profile found
    }
    
    $branch_info = $result['branch_id'] == 'all' ? ['branch_id' => 'all', 'name' => ucwords('all')] : getBranchInfo($conn_rjllearning_specific, $institution_id, $result['branch_id']);

    $country_state_info = getBranchCountryStateInfo($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $result['branch_id']);

    $class_info = $result['class_id'] == 'all' ? ['class_id' => 'all', 'class_name' => ucwords('all')] : getClass($conn_rjllearning_specific, $institution_id, $result['class_id']);

    $section = $result['section_id'] == 'all' ? ['section_id' => 'all', 'section_name' => ucwords('all')] : getSection($conn_rjllearning_specific, $institution_id, $result['section_id']);

    $student_bus_id = $result['id'];
  
    // Fetch student bus assignment
    $query = "SELECT * FROM student_stops WHERE institution_id = ? AND student_id = ?";
    $params = [$institution_id, $student_bus_id];
    $stmt = $conn_rjllearning_specific->prepare($query);
    $stmt->execute($params);
    $bus_result = $stmt->fetch(PDO::FETCH_ASSOC);

    $bus_details = null; // Initialize bus_details as null

    if ($bus_result != null) {
        // Bus assignment exists, fetch associated details
        $bus_id = $bus_result['bus_id'];
        $route_id = $bus_result['route_id'];
        $stop_id = $bus_result['stop_id'];

        // Fetch bus details
        $query = "SELECT * FROM buses WHERE institution_id = ? AND id = ?";
        $params = [$institution_id, $bus_id];
        $stmt = $conn_rjllearning_specific->prepare($query);
        $stmt->execute($params);
        $bus_result_data = $stmt->fetch(PDO::FETCH_ASSOC);

        $bus_number = $bus_result_data ? $bus_result_data['bus_number'] : null;
    
        // Fetch bus stop details
        $query = "SELECT * FROM bus_stops WHERE institution_id = ? AND id = ?";
        $params = [$institution_id, $stop_id];
        $stmt = $conn_rjllearning_specific->prepare($query);
        $stmt->execute($params);
        $bus_result_stops = $stmt->fetch(PDO::FETCH_ASSOC);

        $bus_stop_name = $bus_result_stops ? $bus_result_stops['stop_names'] : null;

        // Fetch route details
        $query = "SELECT * FROM routes WHERE institution_id = ? AND id = ?";
        $params = [$institution_id, $route_id];
        $stmt = $conn_rjllearning_specific->prepare($query);
        $stmt->execute($params);
        $bus_result_route = $stmt->fetch(PDO::FETCH_ASSOC);

        $driver_name = $conductor_name = $incharge_name = null;
        $driver_email = $conductor_email = $incharge_email = null;
        $driver_mobile = $conductor_mobile = $incharge_mobile = null;
        $driver_address = $conductor_address = $incharge_address = null;

        if ($bus_result_route) {
            $driver_id = $bus_result_route['driver_id'];
            $conductor_id = $bus_result_route['conductor_id'];
            $incharge_id = $bus_result_route['incharge_id'];

            // Fetch faculty details for driver, conductor, and incharge
            $faculty_queries = [
                'driver' => $driver_id,
                'conductor' => $conductor_id,
                'incharge' => $incharge_id,
            ];

            foreach ($faculty_queries as $role => $faculty_id) {
                if ($faculty_id) {
                    $query = "SELECT * FROM faculty_info WHERE institution_id = ? AND id = ?";
                    $params = [$institution_id, $faculty_id];
                    $stmt = $conn_rjllearning_specific->prepare($query);
                    $stmt->execute($params);
                    $faculty_result = $stmt->fetch(PDO::FETCH_ASSOC);

                    if ($faculty_result) {
                        ${"{$role}_name"} = $faculty_result['name'];
                        ${"{$role}_email"} = $faculty_result['email'];
                        ${"{$role}_mobile"} = $faculty_result['mobile'];
                        ${"{$role}_address"} = $faculty_result['address'];
                    }
                }
            }
        }

        // Prepare bus details
        $bus_details = [
            'bus_id' => $bus_result_data['id'] ?? null,
            'bus_number' => $bus_number,
            'route_id' => $bus_result_route['id'] ?? null,
            'stop_id' => $bus_result_stops['id'] ?? null,
            'route_name' => $bus_result_route['route_name'] ?? null,
            'bus_stop_name' => $bus_stop_name,
            'driver' => [
                'name' => $driver_name,
                'email' => $driver_email,
                'mobile' => $driver_mobile,
                'address' => $driver_address
            ] ?? null,
            'conductor' => [
                'name' => $conductor_name,
                'email' => $conductor_email,
                'mobile' => $conductor_mobile,
                'address' => $conductor_address
            ] ?? null,
            'incharge' => [
                'name' => $incharge_name,
                'email' => $incharge_email,
                'mobile' => $incharge_mobile,
                'address' => $incharge_address
            ] ?? null,
        ];
    }

    // Process student profile image
    $student_profile_image = null;
    if ($result['student_profile_image'] && !is_array($result['student_profile_image'])) {
        $data_attachment = json_decode($result['student_profile_image'], true);
        $filePath = $data_attachment['filepath'];
        $originalName = $data_attachment['original_name'];
        $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath,1,$GLOBALS['cloudFrontDomain']);
        $student_profile_image = ["filepath" => $aws_attachment, "original_name" => $originalName];
    }

    // Process birth certificate
    $birth_certificate = null;
    if ($result['birth_certificate'] && !is_array($result['birth_certificate'])) {
        $data_attachment = json_decode($result['birth_certificate'], true);
        $filePath = $data_attachment['filepath'];
        $originalName = $data_attachment['original_name'];
        $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);
        $birth_certificate = ["filepath" => $aws_attachment, "original_name" => $originalName];
    }
    
    $nationality_proof = null;
    if ($result['nationality_proof'] && !is_array($result['nationality_proof'])) {
        $data_attachment = json_decode($result['nationality_proof'], true);
        $filePath = $data_attachment['filepath'];
        $originalName = $data_attachment['original_name'];
        $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);
        $nationality_proof = ["filepath" => $aws_attachment, "original_name" => $originalName];
    }

       
    $institution_info = getInstitution($conn_rjllearning, $institution_id);

    $additional_data = ['address', 'pincode', 'contact_number', 'email'];
    $student_branch_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $result['branch_id'], $additional_data);
    $student_info = []; // Ensure it is initialized
       $student_info[] = [
            'student_id' => $result['id'],
            'student_name' => $result['name'],
            'dob' => $result['dob'],
            'gender' => $result['gender'],
            'fathername' => $result['fathername'],
            'admissionnumber' => $result['admission_number'],
            'class' => $class_info,
            'section' => $section,
            'phone' => $result['mobile'],
            'bloodgroup' => $result['blood_group'],
            'address' => $result['address_line_1'],
            'student_images' => isset($student_profile_image['filepath']) ? $student_profile_image['filepath'] : ''



        ];
        
        
        // Assuming $conn_rjllearning_specific is your PDO connection
        
        
        // Check if the institution or branch is not found
        
        if ($export_type == 'print') {
            if (empty($template_id)) {
                errorreturn("Template ID is required.");
                exit(); // Stop execution
            }
            
            switch ($template_id) {
                case 1:
                    echo getIDCardTemplateData($institution_info, $student_branch_info, $academic_session, $student_info, 1);
                    exit(); // Stop execution
                case 2:
                    echo getIDCardTemplateDataSecond($institution_info, $student_branch_info, $academic_session, $student_info, 1);
                    exit(); // Stop execution
                default:
                    errorreturn("Invalid template selected.");
                    exit(); // Stop execution
            }
        } else {
        
            // Construct and return the student profile response
            return [
                "student_profile" => [
                    "id" => $result['id'],
                    "institution_id" => $result['institution_id'],
                    "branch_id" => $branch_info,
                    "academic_id" => $result['academic_id'],
                    "admission_id" => $result['admission_id'],
                    "nationality" => $result['nationality'],
                    "caste" => $result['caste'],
                    "admission_number" => $result['admission_number'],
                    "class_id" => $class_info,
                    "section_id" => $section,
                    "roll_no" => $result['roll_no'],
                    "username" => $result['username'],
                    "student_profile_image" => $student_profile_image,
                    "birth_certificate" => $birth_certificate,
                    "nationality_proof" => $nationality_proof,
                    "nationality_proof_number" => $result['nationality_proof_number'],
                    "name" => $result['name'],
                    "fathername" => $result['fathername'],
                    "mothername" => $result['mothername'],
                    "mobile" => $result['mobile'],
                    "email" => $result['email'],
                    "address_line_1" => $result['address_line_1'],
                    "city" => $result['city'],
                    "pincode" => $result['pincode'],
                    "dob" => $result['dob'],
                    "gender" => $result['gender'],
                    "blood_group" => $result['blood_group'],
                    "date_added" => $result['date_added'],
                    "added_by" => $result['added_by'],
                    "user_id" => $result['user_id'],
                    "can_activate" => $result['can_activate'],
                    "status" => $result['status'],
                    "bus_data" => $bus_details,
                    "country_name" => $country_state_info['country_name'],
                    "state_name" => $country_state_info['state_name'],
                    
                ]
            ];
         }
}

// Process the function type
if ($postdata['function_type'] == "students_My_profile") {
    

    // Check academic session
    $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
    if ($check_academic_confirmation != true) {
        errorreturn("Access denied. Academic session not active.");
    }
    
    $academic_session = GetAcademicSessionName($conn_rjllearning_specific, $institution_id, $check_academic_confirmation);
    if (!$academic_session) {
        errorreturn("No active academic session found for the given institution.");
    }

    $student_id = $userid;
    
    
        // Query to fetch institution settings
    $query = "SELECT id_card_setting 
          FROM institution_global_settings 
          WHERE institution_id = ? 
          AND branch_id = ?";

    // Prepare and execute the query (using PDO)
    $stmt = $conn_rjllearning_specific->prepare($query);
    $stmt->execute([$institution_id, $branch_id]);
    
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Extract template_id from JSON (if available)
    $db_template_id = !empty($result['id_card_setting']) 
        ? json_decode($result['id_card_setting'], true)['template_id'] ?? null 
        : null;
    
    // Determine the final template_id (send null if not found)
    $template_id = isset($postdata['template_id']) && !empty(trim($postdata['template_id'])) 
        ? trim($postdata['template_id']) 
        : $db_template_id; // If nothing found, it remains null
    
    // Ensure null if no ID is found
    $template_id = !empty($template_id) ? $template_id : 1;
    
    $export_type = (isset($postdata['export_type']) and !empty($postdata['export_type'])) ? trim($postdata['export_type']) : null;

    // Get student profile data
    // $success = getStudentProfile($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $student_id);
    $success = getStudentProfile($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $student_id,$export_type, $template_id, $academic_session);
    successreturn($success);
}