<?php

namespace App\Helpers;

use Illuminate\Support\Facades\DB;


class QueryHelper
{
    /**
     * Execute a stored procedure with input and output parameters.
     *
     * @param string $procedureName The name of the stored procedure.
     * @param array $inputParams An associative array of input parameters.
     * @param array $outputParams An associative array of output parameters with PDO types.
     * @return array An associative array of output parameters with their values.
     */
    public static function returnProcedure($connection, $procedureName, $inputParams = [], $outputParams = [])
    {
        $connection = $connection->getPdo();

        $inputPlaceholders = [];
        $outputPlaceholders = [];
        $bindings = [];

        foreach ($inputParams as $key => $value) {
            $inputPlaceholders[] = ":{$key}";
            $bindings[":{$key}"] = $value;
        }

        foreach ($outputParams as $key => $type) {
            $outputPlaceholders[] = ":{$key}";
            $bindings[":{$key}"] = null;
        }

        // Build the SQL statement
        $sql = sprintf(
            'BEGIN %s(%s, %s); END;',
            $procedureName,
            implode(', ', $inputPlaceholders),
            implode(', ', $outputPlaceholders)
        );

        // Prepare the callable statement
        $stmt = $connection->prepare($sql);

        // Bind input parameters
        foreach ($inputParams as $key => $value) {
            $stmt->bindValue(":{$key}", $value);
        }

        // Bind output parameters with specific types
        foreach ($outputParams as $key => $type) {
            $stmt->bindParam(":{$key}", $bindings[":{$key}"], $type, 255);
        }
        // Execute the procedure
        $stmt->execute();

        // Fetch the output parameters
        $outputResults = [];
        foreach ($outputParams as $key => $type) {
            $outputResults[$key] = $bindings[":{$key}"];
        }

        $connection = null;
        return $outputResults;
    }



    public static function execProcedure($connection, $procedureName, $inputParams = [])
    {
        // Get the database connection
        $connection = $connection->getPdo();

        // Build the parameter placeholders for the stored procedure
        $placeholders = [];
        $bindings = [];

        foreach ($inputParams as $key => $value) {
            $placeholders[] = ":{$key}";
            $bindings[":{$key}"] = $value;
        }

        // Build the SQL statement
        $sql = sprintf(
            'BEGIN %s(%s); END;',
            $procedureName,
            implode(', ', $placeholders)
        );

        // Prepare the callable statement
        $stmt = $connection->prepare($sql);

        // Bind input parameters
        foreach ($inputParams as $key => $value) {
            $stmt->bindValue(":{$key}", $value);
        }


        // Execute the procedure
        $stmt->execute();
        $connection = null;
    }
}
