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

// require_once '../resources/base_path_include.php';
// should we not call header and ch
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 . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'jwt/jwt_config.php';
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning . 'functions/common_functions.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/student_api_function/common_api_function.php';
require_once $base_path_to_learning . 'principal_api/principal_function/principal_function.php';

//fcm notification
require_once $base_path_to_learning . 'user_management/functions/fcm_token_function.php';

//jwt token
use \Firebase\JWT\JWT;
use \Firebase\JWT\Key;
//aws image store
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

function user_data_refresh($conn_rjllearning, $conn_rjllearning_specific, $version_number, $last_updated_user_time, $user_id, $institution_id)
{
    global $key, $issued_at, $expiration_time, $issuer;

    if ($last_updated_user_time === null || $last_updated_user_time === 'null' || $last_updated_user_time === '') {
        return true;
    }

    if (empty($version_number) || $version_number === null || !version_compare($version_number, '1.0.0', '>=')) {
        return true;
    }

    // Get server's last update time
    $sql = "SELECT last_update_time FROM user_role_update_time WHERE user_id = ? AND institution_id = ?";
    $stmt = $conn_rjllearning->prepare($sql);
    $stmt->execute([$user_id, $institution_id]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    $server_last_updated = $result ? (int)$result['last_update_time'] : null;
    $last_updated_user_time = (int)$last_updated_user_time;

    // Only proceed with refresh if timestamps don't match
    if ($server_last_updated === $last_updated_user_time) {
        return true;
    }

    // Fetch user data
    $query = "SELECT id, name, email, password, workspace_id, username, role, gender, institution_id 
              FROM users 
              WHERE id = ? AND can_activate = 1 AND status = 1";
    $stmt = $conn_rjllearning->prepare($query);
    $stmt->execute([$user_id]);
    $row = $stmt->fetchAll();

    if (empty($row)) {
        errorreturn('No Data Found');
    }

    // Get branch information
    $sql = "SELECT branch_id FROM faculty_info WHERE userid = ? AND institution_id = ?";
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute([$user_id, $institution_id]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$result) {
        errorreturn("User's branch information not found.");
    }

    $branch_id = $result['branch_id'];

    // Assign user data
    $userid = $row[0]['id'];
    $workspace_id = $row[0]['workspace_id'];
    $institution_id = $row[0]['institution_id'];
    $created_by = $row[0]['username'];
    $name = $row[0]['name'];
    $gender = $row[0]['gender'];
    $email = $row[0]['email'];
    $password2 = $row[0]['password'];
    $role = $row[0]['role'];

    // Generate new JWT token
    $token = array(
        "iat" => $issued_at,
        "exp" => $expiration_time,
        "iss" => $issuer,
        "data" => array(
            "institution_id" => $institution_id,
            "branch_id" => $branch_id,
            "id" => $userid,
            "name" => $name,
            "email" => $email,
            "workspace_id" => $workspace_id,
            "username" => $created_by,
            "role" => $role
        )
    );

    $jwt = JWT::encode($token, $key, 'HS256');

    $merged_array = array(
        "name" => $name,
        "username" => $created_by,
        "gender" => $gender,
        "role" => $role
    );

    $response_data = [];

    if ($role === 'principal') {
        $institution_info = getInstitution($conn_rjllearning, $institution_id);

        $sql = "SELECT last_update_time FROM user_role_update_time 
                WHERE user_id = ? AND institution_id = ?";
        $stmt = $conn_rjllearning->prepare($sql);
        $stmt->execute([$userid, $institution_id]);
        $roleUpdateTime = $stmt->fetch(PDO::FETCH_ASSOC);
        $last_update_time = $roleUpdateTime ? $roleUpdateTime['last_update_time'] : null;

        $sql = "SELECT db_name FROM workspace_database_info WHERE workspace_id = ? AND status = ?";
        $fetch_workspace = $conn_rjllearning->prepare($sql);
        $fetch_workspace->execute([$workspace_id, 1]);
        $result_workspace = $fetch_workspace->fetch(PDO::FETCH_ASSOC);

        if (!$result_workspace) {
            errorreturn('Fatal error (1). Access denied.');
        }

        $db_name = $result_workspace['db_name'];
        $conn_rjllearning_specific = dynamicDbConnection($db_name);

        $sql = "SELECT branch_id FROM faculty_info WHERE userid = ? AND institution_id = ?";
        $stmt = $conn_rjllearning_specific->prepare($sql);
        $stmt->execute([$userid, $institution_id]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$result) {
            errorreturn("User not found in specific branch context.");
        }

        $branch_id = $result['branch_id'];

        $branch_info = getPrincipalBranch($conn_rjllearning_specific, $institution_id, $branch_id);
        $site_setting = getPrintUISetting($conn_rjllearning_specific, $institution_id);

        $global_setting_query = "SELECT attendance_system, faculty_attendance_setting, otp_setting
                               FROM institution_global_settings
                               WHERE institution_id = ? AND branch_id = ?";
        $global_setting_stmt = $conn_rjllearning_specific->prepare($global_setting_query);
        $global_setting_stmt->execute([$institution_id, $branch_id]);
        $global_setting_data = $global_setting_stmt->fetch(PDO::FETCH_ASSOC);

        // Decode JSON settings
        $faculty_attendance_setting = isset($global_setting_data['faculty_attendance_setting'])
            ? json_decode($global_setting_data['faculty_attendance_setting'], true)
            : [];
        $otp_setting = isset($global_setting_data['otp_setting'])
            ? json_decode($global_setting_data['otp_setting'], true)
            : [];

        $global_settings = [
            "attendance_system" => $global_setting_data['attendance_system'] ?? null,
            "faculty_attendance_setting" => $faculty_attendance_setting,
            "otp_setting" => $otp_setting
        ];

        $response_data = [
            "jwt_token" => $jwt,
            "institution" => $institution_info,
            "branch" => $branch_info,
            "site_setting" => $site_setting,
            "global_settings" => $global_settings,
            "last_updated_time" => $last_update_time,
            "other_info" => $merged_array
        ];
    } elseif ($role === 'teacher') {
        $institution_info = getInstitution($conn_rjllearning, $institution_id);
        $conn_rjllearning_specific = getdbconnection($conn_rjllearning, $workspace_id);
        $teacher_data = getClassSectionSubjectsAndInChargeRoles($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $userid);

        $sql = "SELECT last_update_time FROM user_role_update_time 
                WHERE user_id = ? AND institution_id = ?";
        $stmt = $conn_rjllearning->prepare($sql);
        $stmt->execute([$userid, $institution_id]);
        $roleUpdateTime = $stmt->fetch(PDO::FETCH_ASSOC);
        $last_update_time = $roleUpdateTime ? $roleUpdateTime['last_update_time'] : null;

        $class_section_subjects = $teacher_data['class_section_subjects'];
        $class_incharge_roles = $teacher_data['class_incharge_roles'];
        $staff_access_modules = $teacher_data['staff_access_modules'];
        $global_setting_data = $teacher_data['global_settings'];

        $sql = "SELECT db_name FROM workspace_database_info WHERE workspace_id = ? AND status = ?";
        $fetch_workspace = $conn_rjllearning->prepare($sql);
        $fetch_workspace->execute([$workspace_id, 1]);
        $result_workspace = $fetch_workspace->fetchAll();

        if (count($result_workspace) < 1) {
            errorreturn('Fatal error (1). Access denied.');
        }

        $db_name = $result_workspace[0]['db_name'];
        $conn_rjllearning_specific = dynamicDbConnection($db_name);

        $sql = $conn_rjllearning_specific->prepare("SELECT branch_id FROM faculty_info WHERE userid = ? AND institution_id = ?");
        $sql->execute([$userid, $institution_id]);
        $result = $sql->fetchAll();

        if (count($result) !== 1) {
            errorreturn("Teacher not found.");
        }

        $branch_id = $result[0]['branch_id'];
        $branch_info = getPrincipalBranch($conn_rjllearning_specific, $institution_id, $branch_id);
        $site_setting = getPrintUISetting($conn_rjllearning_specific, $institution_id);

        $response_data = [
            "jwt_token" => $jwt,
            "institution" => $institution_info,
            "branch" => $branch_info,
            "class_section_subject" => $class_section_subjects,
            "class_incharge_roles" => $class_incharge_roles,
            "staff_access_modules" => empty($staff_access_modules) ? null : $staff_access_modules,
            "site_setting" => $site_setting,
            "global_settings" => $global_setting_data,
            "last_updated_time" => $last_update_time,
            "other_info" => $merged_array
        ];
    } else {
        $response_data = [
            "jwt_token" => $jwt,
            "other_info" => $merged_array,
            "last_updated_time" => $server_last_updated
        ];
    }

    // Only output if we actually refreshed data
    // errorreturn("DEBUG: Proceeding with data refresh");
    echo json_encode(['status' => -2, 'data' => $response_data]);
    exit;
}

function updateUserRoleTimestamp($conn_rjllearning, $conn_rjllearning_specific, $workspace_id, $institution_id, $faculty_id)
{
    
    $sql = "SELECT userid FROM faculty_info WHERE id = ? AND institution_id = ?";
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute([$faculty_id, $institution_id]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$result || empty($result['userid'])) {
        errorreturn("Error: No user_id found for faculty_id: $faculty_id in institution: $institution_id");
        return false;
    }

    $user_id = $result['userid'];
    $last_update_time = time();
    // error_log("Updating with values: last_update_time=$last_update_time, workspace_id=$workspace_id, user_id=$user_id, institution_id=$institution_id");

    try {

        $sql = "UPDATE user_role_update_time 
                SET last_update_time = ?, workspace_id = ?
                WHERE user_id = ? AND institution_id = ?";

        $stmt = $conn_rjllearning->prepare($sql);
        $stmt->execute([$last_update_time, $workspace_id, $user_id, $institution_id]);

        if ($stmt->rowCount() === 0) {
            $sql = "INSERT INTO user_role_update_time 
                    (workspace_id, institution_id, user_id, last_update_time) 
                    VALUES (?, ?, ?, ?)";

            $stmt = $conn_rjllearning->prepare($sql);
            $stmt->execute([$workspace_id, $institution_id, $user_id, $last_update_time]);
        }

        return true;
    } catch (PDOException $e) {

        errorreturn("Database error updating user_role_update_time: " . $e->getMessage());
        return false;
    } catch (Exception $e) {

        errorreturn("General error updating user_role_update_time: " . $e->getMessage());
        return false;
    }
}