<?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/check_username_availability.php';
require_once $base_path_to_learning . 'user_management/authenticate.php';

//db access function
require_once $base_path_to_learning_resources . 'includes/specific_db_config.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 . 'user_management/faculty/functions.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'admin_api/modules/staff/staff_details/staff_functions.php';

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

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

// checkIfNoPhpContentsReceive();
// print_R($postdata);die();
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);
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;

if (!in_array($role, ['superadmin', 'admin', 'principal'])) {
    errorreturn('Access denied.');
}

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

// Function to Terminate Faculty
function insertStaffPayrollCategoryInfo($conn_rjllearning_specific, $institution_id, $branch_id, $group_name) {
    try {
        // Base query
        $query = "SELECT id FROM staff_payroll_category_info WHERE institution_id = ? AND group_name = ?";
        $params = [$institution_id, $group_name];

        // Append branch_id conditionally
        if ($branch_id !== "all") {
            $query .= " AND branch_id = ?";
            $params[] = $branch_id;
        }

        // Prepare & execute query
        $stmt = $conn_rjllearning_specific->prepare($query);
        $stmt->execute($params);
        $existing = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($existing) {
            return $existing['id']; // Return existing ID if found
        }

        // Insert new record if not found
        $stmt = $conn_rjllearning_specific->prepare("INSERT INTO staff_payroll_category_info (institution_id, branch_id, group_name) VALUES (?, ?, ?)");
        $stmt->execute([$institution_id, $branch_id, $group_name]);
        
        return $conn_rjllearning_specific->lastInsertId();
    } catch (PDOException $e) {
        return "Error: " . $e->getMessage();
    }
}

// Handle API Function Type
if ($postdata['function_type'] === "staff_payroll_group") {
    $institution_id = $postdata['institution_id'];
    $branch_id = $postdata['branch_id'] ?? "all";
    $group_name = $postdata['group_name'];

    $response = insertStaffPayrollCategoryInfo($conn_rjllearning_specific, $institution_id, $branch_id, $group_name);
    
    successreturn("Successfully stored category $response");
} else {
    errorreturn("Invalid function type.");
}
