<?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';

// Validation 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_resources . 'includes/aws_dynamo_config.php';
require_once $base_path_to_learning_resources . 'lib/common_modules/payroll/functions.php';
require_once $base_path_to_learning_resources . 'lib/common_modules/dynamodb_function/functions.php';
require_once $base_path_to_learning . "faculty_api/faculty_function/common_faculty_function.php";
require_once $base_path_to_learning . "principal_api/principal_function/principal_function.php";

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

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

if (
    // !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or
    !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);
$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;

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ['teacher'], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

require_once $base_path_to_learning . 'user_management/user_versioning.php';

$version = isset($_POST['version']) ? $_POST['version'] : (isset($postdata['version']) ? $postdata['version'] : null);
$updated_time = isset($_POST['updated_time']) ? $_POST['updated_time'] : (isset($postdata['updated_time']) ? $postdata['updated_time'] : null);

$response = user_data_refresh($conn_rjllearning, $conn_rjllearning_specific,$version, $updated_time, $userid, $institution_id);

$academic_id = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if ($academic_id == false) {
    errorreturn("Access denied. Academic session not active.");
}

$start_date = $postdata['start_date'] ?? date('Y-m-01');
$end_date = $postdata['end_date'] ?? date('Y-m-t');
$role = $postdata['role'] ?? 'Teacher';
$other_staff_role = ($role == "other") ? ($postdata['other_staff_role'] ?? null) : null;
$category_id = $postdata['category_id'] ?? null;

$type = $postdata['type'] ?? null;
$password = $postdata['password'] ?? null;
$date_created = date('Y-m-d');
$time_created = time();

$sql_faculty = $conn_rjllearning_specific->prepare("SELECT id FROM faculty_info WHERE userid = ? AND institution_id = ? AND branch_id = ?");
$sql_faculty->execute([$userid, $institution_id, $branch_id]);
$result_faculty = $sql_faculty->fetch(PDO::FETCH_ASSOC);
if (!$result_faculty) {
    errorreturn("Faculty not found.");
}

$faculty_id = $result_faculty['id'];
$function_type = $postdata['function_type'];

// Check faculty permissions
$teacher_data = getClassSectionSubjectsAndInChargeRoles($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $userid);
checkFacultyModuleGranted($function_type, $teacher_data['class_section_subjects'], $teacher_data['class_incharge_roles'], $teacher_data['staff_access_modules'], null, null, null, $conn_rjllearning);


if ($postdata['function_type'] == "generate_salary") {

    if (!empty($type) && !empty($password)) {
        $query = "SELECT password FROM users WHERE username = ? AND can_activate = 1 AND status = 1";
        $stmt = $conn_rjllearning->prepare($query);
        $stmt->execute([$username]);
        $row = $stmt->fetch();

        if (!$row || !password_verify($password, $row['password'])) {
            errorreturn('Invalid credentials.');
        }

        if ($type == "save") {
            $salaryData = getSalaryDetails(
                $conn_rjllearning_specific,
                $institution_id,
                $branch_id,
                $start_date,
                $end_date,
                $role,
                $other_staff_role,
                $category_id
            );
            // Create DynamoDB table (if not already created)
            create_Salarydetails_table($dynamoDb, $dynamoDB_table_name);

            // Insert salary data into DynamoDB
            $insert_result = insert_salary_Data_to_dynamoDB($dynamoDb, $salaryData['salary_data'], $institution_id, $branch_id, $workspace_id, $dynamoDB_table_name);
            if (!$insert_result || !isset($insert_result['batch_id'])) {
                errorreturn("Salary generated but DynamoDB save failed.");
            }

            $insert_query = "INSERT INTO payroll_log (institution_id, branch_id, start_date, end_date, role, other_staff_role, category_id, log_id, 
            date_created, time_created, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $stmt = $conn_rjllearning_specific->prepare($insert_query);
            $log_saved = $stmt->execute([
                $institution_id,
                $branch_id,
                $start_date,
                $end_date,
                $role,
                $other_staff_role,
                $category_id,
                $insert_result['batch_id'],
                $date_created,
                $time_created,
                $username
            ]);

            if ($log_saved) {
                $log_id = $conn_rjllearning_specific->lastInsertId();
                successreturn([
                    "message" => "Payroll log and salary data saved successfully",
                    "log_id" => $log_id,
                    "batch_id" => $insert_result['batch_id']
                ]);
            } else {
                errorreturn("Failed to save payroll log.");
            }
        }
    }
    $response = getSalaryDetails(
        $conn_rjllearning_specific,
        $institution_id,
        $branch_id,
        $start_date,
        $end_date,
        $role,
        $other_staff_role,
        $category_id
    );
    successreturn($response);
}
