<?php

/*

File: king-include/king-ajax-click-wall.php
Description: Server-side response to Ajax single clicks on wall posts

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

More about this license: LICENCE.html
 */

require_once QA_INCLUDE_DIR . 'king-app/users.php';
require_once QA_INCLUDE_DIR . 'king-app/limits.php';
require_once QA_INCLUDE_DIR . 'king-db/selects.php';
require_once QA_INCLUDE_DIR . 'king-app-video.php';
require_once QA_INCLUDE_DIR . 'king-app/cookies.php';
require_once QA_INCLUDE_DIR.'king-db/metas.php';
if (qa_is_logged_in()) {
    $userid = qa_get_logged_in_userid();
} else {
    $userid = qa_remote_ip_address();
}

$input = qa_post_text('input');
$genre = qa_post_text('genre');


$chkk = true;
$error = '';
if (qa_opt('enable_membership') && qa_opt('aimsc_limits') && qa_get_logged_in_level() <= QA_USER_LEVEL_ADMIN) {
    $chkk = kingaim_check();
}
if (qa_opt('enable_credits') && qa_opt('post_aimusic')) {
    $chkk = king_spend_credit(qa_opt('post_aimusic'));
}
if ($input && $chkk) {

    $api_url = "https://kingstudio.io/api/king-aimusic"; //change it !!!!
    $api_key = qa_opt('king_sd_api');

    $request_data = [
        "prompt" => $input . ($genre ? " Genre: $genre." : ""),
    ];



    $ch = curl_init($api_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer $api_key",
        "Accept: application/json",
        "Content-Type: application/json",

    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($request_data));
    curl_setopt($ch, CURLOPT_TIMEOUT, 400);
    $response = curl_exec($ch);


    $out = json_decode($response, true);
    if (isset($out['error'])) {
        $error = $out['error'];
    }
    $videourl = $out['out'] ?? [];
    $thumb = null;
    if ( qa_opt('aimsc_athumb') && qa_opt('king_sd_api') ) {
        $sdapi = qa_opt('king_sd_api');

        $URL = "https://kingstudio.io/api/king-text2img"; //change it !!!!
        $cleanLyrics = preg_replace('/\s*\[.*?\]\s*/s', '', $input);

        // Also clean up extra blank lines left behind
        $cleanLyrics = preg_replace('/\n{3,}/', "\n\n", $cleanLyrics);
        $cleanLyrics = trim($cleanLyrics);
        $lines = explode("\n", $cleanLyrics);
        $lines = array_filter($lines, function($line) {
            $banned = ['lyrics', 'song', 'chorus', 'verse', 'words', 'text', 'says', 'sings'];
            foreach ($banned as $word) {
                if (stripos($line, $word) !== false) return false;
            }
            return true;
        });
        $cleanLyrics = implode("\n", $lines);
        $request_data = [
            "prompt" => "Create an image about no Text on the image, Abstract "  ." about " . $cleanLyrics,
            "size" => 1,
            "steps" => 10,
            "aisize" => '1152x896',
            "model" => 'flux_pro',
        ];

        $ch = curl_init($URL);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "Authorization: Bearer $sdapi",
            "Accept: application/json",
            "Content-Type: application/json",
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($request_data));
        curl_setopt($ch, CURLOPT_TIMEOUT, 400);
        $response = curl_exec($ch);

        $out = json_decode($response, true);
        if (isset($out['error'])) {
            $error = 'Image generation failed: ' . $out['error'];
        }else{
            $image_urls = $out['out'] ?? [];
            if (!empty($image_urls) && isset($image_urls[0])) {
                $imageUrl = $image_urls[0];

                $thumb = king_urlupload($imageUrl, false, 600);
            } else {
                $error = 'No image returned from Kings API.';
            }
        }
    }

    if (isset($error) && $error) {
        $output = json_encode(array('success' => false, 'message' => $error));
    } else {
        require_once QA_INCLUDE_DIR . 'king-app/post-create.php';
        $extra = king_urlupload($videourl, null, null, true);

        $cookieid = isset($userid) ? qa_cookie_get() : qa_cookie_get_create();
        $postid = qa_question_create(null, $userid, qa_get_logged_in_handle(), $cookieid, null, $thumb, '', null, null, null, null, null, $extra, 'NOTE', null, 'aimsc', $input, null);
        qa_db_postmeta_set($postid, 'wai', true);

        if ( qa_opt('enable_membership') && qa_opt('aimsc_limits') ) {
            $query  = (INT)qa_db_usermeta_get( $userid, 'aimslmt' );
            $total = $query+1;
            qa_db_usermeta_set( $userid, 'aimslmt', $total );
		}

        $output = json_encode(array(
            'success' => true,
            'postid' => $postid,
            'videourl' => $videourl
        ));
    }
    echo "QA_AJAX_RESPONSE\n1\n";

    echo $output."\n";

    echo king_ai_posts($userid, 'aimsc');


} else {
    $outputz = json_encode(array('success' => false, 'message' => qa_lang_html('misc/nocredits')));

    echo "QA_AJAX_RESPONSE\n0\n";

    echo $outputz."\n";
}
