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

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

require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning . 'functions/common_functions.php';

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

$requiredFields = ['name', 'api_signature', 'function_type', 'jwt_token'];

// Validate required fields
foreach ($requiredFields as $field) {
    if (!isset($postdata[$field]) || empty($postdata[$field])) {
        errorreturn("Field '$field' is required.");
    }
}
validateApiSignature($postdata['api_signature']);

// Extract input values into variables
$name = $postdata['name'];
$function_type = $postdata['function_type'];
$jwt_token = $postdata['jwt_token'];
$status = isset($postdata['status']) ? $postdata['status'] : '1';
$id = isset($postdata['id']) ? $postdata['id'] : null;

// Validate JWT Token
$jwt_validate = authenticate_jwt($jwt_token);
if (!$jwt_validate) {
    errorreturn("Invalid JWT token.");
}

// Extract user details from token
$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;

// Validate user access
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ['principal'], null);
if (!$specific_db_name) {
    errorreturn("Access denied.");
}

$conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
if (!$conn_rjllearning_specific) {
    errorreturn("Failed to connect to the database.");
}
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);

// Connect to the specific database
$academic_id = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if ($academic_id == false) {
    errorreturn("Access denied. Academic session not active.");
}

$allowed_leaves = $postdata['allowed_leaves'];
$allowed_leaves_basis = $postdata['allowed_leaves_basis'];

if ((!in_array($allowed_leaves_basis, ["weekly", "monthly", "quarterly", "half_yearly", "yearly"]))) {
    errorreturn("Validation failed: $allowed_leaves_basis is not a valid option for allowed leaves basis.");
}

// Check if payroll category name already exists
$query = "SELECT id FROM payroll_category WHERE institution_id = ? AND (branch_id = ? or branch_id = 'all') AND name = ?";
$stmt = $conn_rjllearning_specific->prepare($query);
$stmt->execute([$institution_id, $branch_id, $name]);
$existing_category = $stmt->fetch(PDO::FETCH_ASSOC);

if ($existing_category && $function_type === "create_payroll_category") {
    errorreturn("A payroll category with the same name already exists.");
}

$param = (int) trim($postdata['params']);

// $query = "SELECT id FROM payroll_profile WHERE institution_id = ? AND (branch_id = ? OR branch_id = 'all') AND id = ?";
// $stmt = $conn_rjllearning_specific->prepare($query);
// $stmt->execute([$institution_id, $branch_id, $param]);
// $existing_param = $stmt->fetch(PDO::FETCH_ASSOC);

// if (empty($existing_param)) {
//     errorreturn("Enter a valid payroll profile param");
// }

try {
    if ($function_type === "create_payroll_category") {
        // Insert query
        $query = "INSERT INTO payroll_category (institution_id, branch_id, name, payroll_profile_params, allowed_leaves, allowed_leaves_basis, 
                    created_by, created_on, status) 
                  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $conn_rjllearning_specific->prepare($query);

        if ($stmt->execute([$institution_id, $branch_id, $name, $param, $allowed_leaves, $allowed_leaves_basis, $username, date('Y-m-d'), $status])) {
            successreturn("Payroll category created successfully.");
        } else {
            errorreturn("Failed to create payroll category.");
        }
    } elseif ($function_type === "update_payroll_category") {
        if (!$id) {
            errorreturn("Field 'id' is required for updating payroll category.");
        }

        $query = "SELECT id FROM payroll_category WHERE institution_id = ? AND branch_id = ?  AND name = ? AND id != ?";
        $stmt = $conn_rjllearning_specific->prepare($query);
        $stmt->execute([$institution_id, $branch_id, $name, $id]);
        $existing_category = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($existing_category) {
            errorreturn("Another payroll category with the same name already exists.");
        }

        // Update query
        $query = "UPDATE payroll_category 
                  SET name = ?, payroll_profile_params = ?, allowed_leaves = ?, allowed_leaves_basis = ?, status = ? 
                  WHERE id = ? AND institution_id = ? AND branch_id = ?";
        $stmt = $conn_rjllearning_specific->prepare($query);

        if ($stmt->execute([$name, $param, $allowed_leaves, $allowed_leaves_basis, $status, $id, $institution_id, $branch_id])) {
            successreturn("Payroll category updated successfully.");
        } else {
            errorreturn("Failed to update payroll category.");
        }
    } else {
        errorreturn("Invalid function_type.");
    }
} catch (PDOException $e) {
    errorreturn("Database Error: " . $e->getMessage());
}
