<?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 = ['institution_id', 'staff_type', 'leave_type', 'allowed_days', 'carry_forward', 'year', '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']);

$staff_type = $postdata['staff_type'];
$leave_type = $postdata['leave_type'];
$allowed_days = $postdata['allowed_days'];
$carry_forward = $postdata['carry_forward'];
$year = $postdata['year'];

$function_type = $postdata['function_type'];
$jwt_token = $postdata['jwt_token'];
$status = isset($postdata['status']) ? $postdata['status'] : '1'; // Default status to '1'
$id = isset($postdata['id']) ? $postdata['id'] : null; // ID for update/delete cases

// 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.");
}

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


// Connect to the specific database
$conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
if (!$conn_rjllearning_specific) {
    errorreturn("Failed to connect to the database.");
}
$response = user_data_refresh($conn_rjllearning, $conn_rjllearning_specific, $version, $updated_time, $userid, $institution_id);

try {
    if ($function_type === "create_allowed_leave") {
        // Insert query
        $query = "INSERT INTO allowed_leaves (institution_id, branch_id, staff_type, leave_type, allowed_days, carry_forward, year, created_by, created_on, status) 
                  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $conn_rjllearning_specific->prepare($query);

        if ($stmt->execute([$institution_id, $branch_id, $staff_type, $leave_type, $allowed_days, $carry_forward, $year, $username, date('Y-m-d'), $status])) {
            successreturn("Leave category created successfully.");
        } else {
            errorreturn("Failed to create leave category.");
        }
    } elseif ($function_type === "update_allowed_leave") {
        // Ensure 'id' is provided for update
        if (!$id) {
            errorreturn("Field 'id' is required for updating leave category.");
        }

        // Update query
        $query = "UPDATE allowed_leaves 
                  SET staff_type = ?, leave_type = ?, allowed_days = ?, carry_forward = ?, year = ?, status = ? 
                  WHERE id = ? AND institution_id = ?, branch_id = ?";
        $stmt = $conn_rjllearning_specific->prepare($query);

        if ($stmt->execute([$staff_type, $leave_type, $allowed_days, $carry_forward, $year, $status, $id, $institution_id, $branch_id])) {
            successreturn("Leave category updated successfully.");
        } else {
            errorreturn("Failed to update leave category.");
        }
    } elseif ($function_type === "delete_allowed_leave") {
        // Ensure 'id' is provided for delete
        if (!$id) {
            errorreturn("Field 'id' is required for deleting leave category.");
        }

        // Delete query
        $query = "DELETE FROM allowed_leaves WHERE id = ?";
        $stmt = $conn_rjllearning_specific->prepare($query);

        if ($stmt->execute([$id])) {
            successreturn("Leave category deleted successfully.");
        } else {
            errorreturn("Failed to delete leave category.");
        }
    } else {
        errorreturn("Invalid function_type.");
    }
} catch (PDOException $e) {
    errorreturn("Database Error: " . $e->getMessage());
}
?>
