Your IP : 216.73.216.79


Current Path : /var/www/html/ukas/backend/modules/aidynaweb/widgets/
Upload File :
Current File : /var/www/html/ukas/backend/modules/aidynaweb/widgets/AiCodeGenerator.php

<?php

namespace backend\modules\aidynaweb\widgets;

use yii\base\Widget;
use yii\helpers\Html;
use yii\helpers\Url;

class AiCodeGenerator extends Widget
{
    public static $assetInit = true;

    public string $editor_object ='';

    public string $width = '900';

    public string $height = '500';

    public string $padding = '20';

    public string $margin = '10';

    public $baseUrl = 'https://ai.dynaweb4.work/api/json/query_open_context';

    public function init()
    {
        parent::init();
    }

    public function run()
    {   
        /** url **/
        $urlgettoken = Url::to(['/aidynaweb/ai-dynaweb/get-bearer']);

        /** request **/
        $request = \Yii::$app->request;

        /** render once **/
        $render_once = null;

        // if(self::$assetInit) {self::$assetInit = false;}

        /**extra asset **/
    
        /** javascript **/
        $this->view->registerJs(
        <<<JS
            //ai assisted
            const ai = (editor) => {
                $('#ai-assisted-{$this->getId()}').click(function() {
                    Swal.fire({
                        title: "AI ASSISTED CODE",
                        width: '{$this->width}',
                        height: '{$this->height}',
                        padding: '{$this->padding}',
                        margin: '{$this->margin}',
                        html: `
                            <div style="text-align:left">
                                <p>Put your prompt here.</p>
                            <textarea id="swal-input1" class="form-control" rows="5" class="form-control"></textarea>
                            </div>

                        `,
                        focusConfirm: false,
                        showLoaderOnConfirm: true,
                        preConfirm: async (login) => {
                            try {

                                prompt = document.getElementById("swal-input1").value

                                if (!prompt || prompt.length < 20) {
                                    return Swal.showValidationMessage(`Please input some valid prompt at leaset 20 char`);
                                }

                                // get bearer token
                                let system = 'You are as a HTML5, CSS3 ,JS developer, that will write excellent code that supports bootstrap with fully responsive web design. Please only reply with code only and omitted markdown for the code. The reply also must does not include any html, body, script, link=ref tag only pure code for the requested part, No explanation of the code is needed.'

                                let formData = new FormData();
                                const nonce = Math.floor(new Date().getTime() / 1000);
                                formData.append('payload', system + document.getElementById("swal-input1").value);
                                formData.append('nonce', nonce);
                                formData.append('$request->csrfParam', '$request->csrfToken');

                                const urltoken = `$urlgettoken`;
                                const token = await fetch(urltoken, {
                                    method: 'post',
                                    body: formData
                                });

                                const bearertoken = await token.json();

                                const url = `{$this->baseUrl}`;
                                // const url =  'http://father-mediawiki.gl.at.ply.gg:6625/api/json/query_open_context'
                                const response = await fetch(url, {
                                    method: 'post',
                                    headers: {
                                        "Content-Type": "application/json",
                                        "Authorization": "Bearer " + bearertoken.token
                                    },
                                    body: JSON.stringify({
                                        system: system,
                                        human: document.getElementById("swal-input1").value,
                                        nonce: nonce
                                    })
                                });

                                if (!response.ok) {
                                    console.log(response)
                                    return Swal.showValidationMessage(`error occured with status \${response.status} :- \${JSON.stringify(await response.json())}`);
                                }

                                resp = await response.json();

                                let oldvalue = editor.getSession().getValue()

                                if (typeof resp?.answer?.content != "undefined") {
                                    if (oldvalue) {
                                        editor.getSession().setValue(oldvalue + '\\n' + resp.answer.content);
                                    } else {
                                        editor.getSession().setValue(resp.answer.content);
                                    }
                                }

                                return;
                            } catch (error) {
                                Swal.showValidationMessage(`Request failed: \${error}`);
                            }
                        },
                        allowOutsideClick: () => !Swal.isLoading()
                    });
                });
            }

            if({$this->editor_object}) {
                ai({$this->editor_object});
            }
        JS
        );
        
        return 
        <<<HTML
            <style type="text/css">
                .swal2-container{
                    z-index: 3060;
                }

                .swal2-validation-message {
                    background:#ffffff;
                }

                .swal2-popup {
                    width:{$this->width} !important;
                }
            </style>
            <button type="button" id="ai-assisted-{$this->getId()}" class="btn btn-success" aria-label="Ai Assist">Ai Assisted</button>
        HTML;
    }
}