<?php
    global $c;

    $strQueryDir = "files/queries";

    $varFiles = scandir($strQueryDir);
    $varFiles = array_diff($varFiles, [".", ".."]);

    $strSelection   = Request::getArg(0);
    $varInputs      = [[]];
    $varRows        = null;
    $strError       = null;

    if ($strSelection !== null && strlen($strSelection) > 0)
    {
        $strFileData = file_get_contents("{$strQueryDir}/{$strSelection}");

        preg_match_all("/declare\s+\@([A-Za-z0-9]{1,})\s+(.+)\s+=\s+\?/i", $strFileData, $varInputs);

        //Respond::json($varMatces);
    

        $intRun = Request::getParam("run");

        //if (Request::posts("run_query"))
        if ($intRun !== null && $intRun == 1)
        {
            $varPosted = Request::getParams();
            unset($varPosted["run"]);

            try
            {
                $varRows = $c->query("{$strQueryDir}/{$strSelection}", $varPosted);
            }
            catch (Exception $x)
            {
                $strMessage = $x->getMessage();
                $strError = $strMessage;
                $strError .= "\n\n";

                $strFile = $x->getFile();
                $intLine = $x->getLine();
                
                $strError .= "#-1 {$strFile}({$intLine}): {$strMessage}\n";
                $strError .= $x->getTraceAsString();
            }
        }
    }
?>

<div class="navbar navbar-expand bg-primary d-print-none">
    <div class="container-fluid justify-content-between">
        <div class="d-inline-flex align-items-center">
            <a class="navbar-brand" href="/"><?= $strSelection ?? "Report"; ?></a>

            <a class="nav-item btn btn-outline-light me-2" onclick="fnShowPage('#page-input');"><i class="fa fa-fw fa-edit"></i> <span class="d-none d-lg-inline">Setup</span></a>

            <?php if ($varRows !== null && count($varRows) > 0): ?>
                <a class="nav-item btn btn-outline-light me-2" onclick="fnShowPage('#page-output');"><i class="fa fa-fw fa-table"></i> <span class="d-none d-lg-inline">Results</span></a>
                <a class="nav-item btn btn-outline-light me-2" onclick="fnExport();"><i class="fa fa-fw fa-download"></i> <span class="d-none d-lg-inline">.csv</span></a>
            <?php endif; ?>
        </div>
    </div>
</div>

<div class="page" id="page-input">
    <div class="container my-3">

        <?php if ($strError !== null): ?>
            <div class="row">
                <div class="col-sm-12">
                    <div class="alert alert-danger">
                        <pre class="mb-0"><?= $strError; ?></pre>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <?php if ($varRows !== null && count($varRows) < 1): ?>
            <div class="row">
                <div class="col-sm-12">
                    <div class="alert alert-warning">
                        No rows returned.
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <div class="row">
            <div class="col-sm-4">
                <div class="mb-3">
                    <label>Choose Query</label>
                    <div class="input-group">
                        <span class="input-group-text"><i class="fa fa-fw fa-folder"></i></span>
                        <input type="text" class="form-control" name="query" placeholder="e.g. fsp_Test.sql" value="<?= $strSelection; ?>" id="query-search" />
                    </div>
                    <div class="query-search-results">
                        <?php foreach ($varFiles as $f): ?>
                            <div class="d-none border p-3">
                                    <a class="link-underline link-underline-opacity-0" href="/run/<?= $f; ?>">
                                        <i class="fa fa-fw fa-scroll me-2"></i>
                                        <?= $f; ?>
                                    </a>
                                </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>


        <form method="get">
            <?php if (count($varInputs[0]) > 0): ?>
                <?php for ($i = 0; $i < count($varInputs[0]); $i++): ?>
                    <?php
                        $strInputName = $varInputs[1][$i];
                        $strInputType = $varInputs[2][$i];
                    ?>

                    <div class="row">
                        <div class="col-sm-4">
                            <div class="mb-3">
                                <label><?= $strInputName; ?> <code><?= $strInputType; ?></code></label>

                                <div class="input-group">
                                    <span class="input-group-text"><i class="fa fa-fw fa-at"></i></span>
                                    <input type="text" class="form-control" name="<?= $strInputName; ?>" value="<?= Request::getParam($strInputName); ?>" />
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endfor; ?>
            <?php endif; ?>


            <div class="row">
                <div class="col-sm-4">
                    <div class="mb-3">
                        <label>Actions</label>
                        <div>
                            <a class="btn btn-outline-primary" onclick="fnSubmit(this);"><i class="fa fa-fw fa-server me-1"></i> Execute</a>
                        </div>
                    </div>
                </div>
            </div>

            <input type="hidden" name="run" value="1" />
        </form>
    </div>
</div>

<div class="page" id="page-output">
    <?php if ($varRows !== null && count($varRows) > 0): ?>

        <?php
            $varRow1    = $varRows[0];
            $varColumns = [];

            foreach ($varRow1 as $k => $v)
                $varColumns[] = $k;
        ?>

        <div class="table-responsive">
            <table class="table table-sm table-striped table-bordered w-100" id="table">
                <thead>
                    <tr>
                        <?php foreach ($varColumns as $col): ?>
                            <th class="text-nowrap sorting"><?= $col; ?> <?php DataTable::sortIcon(); ?></th>
                        <?php endforeach; ?>
                    </tr>
                </thead>

                <tbody>
                    <?php foreach ($varRows as $r): ?>
                        <tr>
                            <?php foreach ($varColumns as $col): ?>
                                <td><?= $r[$col]; ?></td>
                            <?php endforeach; ?>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

<script>
    $(function() {
        var fileSearch = $("#query-search").first();

        fileSearch.on("input", function() {
            var q = fileSearch.val();

            $(".query-search-results div").each(function(i, x) {
                x = $(x);
                x.addClass("d-none");

                if (q.length < 1)
                    return;

                var fileName = x.text();

                if (fileName.toLowerCase().includes(q.toLowerCase()))
                    x.removeClass("d-none");
            });
        });


        fnShowPage = function(id)
        {
            $("div.page").addClass("d-none");
            $(id).removeClass("d-none");
        };

        fnSubmit = function(x)
        {
            x = $(x);
            x.parents("form").first().submit();
        };

        fnExport = function()
        {
            fnShowPage("#page-output");
            $("#table").exportCSV({name: "<?= $strSelection; ?>"});
        };
    });
</script>

<?php if ($varRows !== null && count($varRows) > 0): ?>
    <script>
        $(function() {
            fnShowPage("#page-output");
        });
    </script>

    <?php DataTable::js("#table"); ?>
<?php endif; ?>
