<?php

namespace App\Http\Controllers;

use App\Http\Common\Util;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Exception;

class AIController extends Controller
{
    public $aiConfigSet = [];

    public function __construct()
    {
        // Set required key set based on model group.
        $this->aiConfigSet = [
            'openai' => ['openai_access_key', 'openai_enable', 'prompt_details'],
            'google' => ['google_search_api_key', 'google_search_enable',
                         'google_engine_id' , 'prompt_details'],
            'gemini' => ['gemini_api_key', 'gemini_enable', 'prompt_details'],
        ];
    }


    /**
     * Get 'ai' credentials.
     */
    public function get(Request $request)
    {
        try{
            $result = null;
            $request = Util::FilterRequests($request->all());
            if(empty($request['cmp'])){
                throw new Exception("Missing company.");
            }

            if(empty($request['slug'])){
                throw new Exception("Missing parameter 'slug'.");
            }

            // Get company & model wise 'ai' configuration.
            $dataconfig = $this->getAIConfigFor($request['cmp'], $request['slug']);

            $result = ['status' => 1, 'result' => $dataconfig, 'errorcode' => null, 'msg' => null];
            return Util::responseop(response(), $result); 
        }catch(Exception $e){
            Util::wlog('ai_config',$e->getMessage());
            $result = ['status' => 0, 'result' => null, 'errorcode' => null, 'msg' => $e->getMessage()];
            return Util::responseop(response(), $result);   
        }
    }


    /**
     * OpenAi prompt search api.
     */
    public function generateDescription(Request $request){
        try{
            $request = Util::FilterRequests($request->all());
            $model = $request['model'] ?? 'openai';

            if(empty($request['cmp'])){
                throw new Exception("Missing company/accountid.");
            }    
            
            if(empty($request['prompt'])){
                throw new Exception("Missing parameter prompt.");
            }

            $this->addCounts($request['cmp'], 'generate_api');

            // Get company & model wise 'ai' configuration.
            $dataconfig = $this->getAIConfigFor($request['cmp'], $model, true);

            if ($model == 'openai') {

                $prompt = $dataconfig['prompt_details']; // from database
                $openAiKey = $dataconfig['openai_access_key']; //from database

                $productInfo = $request['prompt'];
                $prompt = str_replace('{productContent}', $productInfo, $prompt);

                if(isset($request['doing']) && $request['doing']=='testing'){
                    $prompt = $request['prompt'];
                }
                
                $ch = curl_init('https://api.openai.com/v1/chat/completions');
                $data = [
                    'model' => 'gpt-4.1-mini',
                    'messages' => [
                        [
                            'role' => 'system',
                            'content' => 'You are a helpful assistant that generates product descriptions.'
                        ],
                        [
                            'role' => 'user',
                            'content' => $prompt
                        ]
                    ]
                ];

                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
                curl_setopt($ch, CURLOPT_HTTPHEADER, [
                    'Authorization: Bearer ' . $openAiKey,
                    'Content-Type: application/json'
                ]);

                $response = curl_exec($ch);

                if (curl_errno($ch)) {
                    $error = curl_error($ch);
                    curl_close($ch);
                    return $this->createResponse(null, 'cURL error: ' . $error, 500);
                }

                $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                curl_close($ch);

                if ($httpCode !== 200) {
                    return $this->createResponse(null, 'OpenAI API request failed with status ' . $httpCode . ': ' . $response, $httpCode);
                }

                $data = json_decode($response, true);
                if (isset($data['choices'][0]['message']['content'])) {
                    return $this->createResponse($data['choices'][0]['message']['content']);
                }
                return $this->createResponse(null, 'Unexpected OpenAI response structure', 500);
            }
            return $this->createResponse(null, 'Invalid model company specified', 400);
            
        }catch(Exception $e){
            Util::wlog('ai_config',$e->getMessage());
            return $this->createResponse(null, $e->getMessage(), 400);
        }
    }


    /**
     * Google image search.
     */
    public function imageSearch(Request $request){
        try {

            $model = $request['model'] ?? 'google';
            if(empty($request->get('cmp'))){
                throw new Exception("Missing company/accountid.");
            }    

            $this->addCounts($request['cmp'], 'image_search_api');

            // Get company & model wise 'ai' configuration.
            $dataconfig = $this->getAIConfigFor($request->get('cmp'), $model, true);

            // Prepare parameters.
            $googleApiKey = $dataconfig['google_search_api_key'];
            $searchEngineId = $dataconfig['google_engine_id'];
            $imagesPerPage = 10;
            $page = $request->get('page',1);
            $query = $request->get('query'); // any search text.
            $startIndex = ($page - 1) * $imagesPerPage + 1;

            $searchUrl = sprintf(
                'https://www.googleapis.com/customsearch/v1?key=%s&cx=%s&q=%s&searchType=image&num=%d&start=%d',
                $googleApiKey,
                $searchEngineId,
                urlencode($query),
                $imagesPerPage,
                $startIndex
            );

            // Initialize cURL session
            $ch = curl_init($searchUrl);

            // Set cURL options
            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_SSL_VERIFYPEER => true,
                CURLOPT_HTTPHEADER => ['Accept: application/json']
            ]);

            // Execute the request
            $response = curl_exec($ch);

            // Check for cURL errors
            if (curl_errno($ch)) {
                throw new Exception('cURL Error: ' . curl_error($ch));
            }

            // Get HTTP status code
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            if ($httpCode !== 200) {
                $error = json_decode($response, true);
                throw new Exception(
                    'API Error: ' .
                    ($error['error']['message'] ?? 'Unknown error') .
                    ' (Status: ' . $httpCode . ')'
                );
            }

            $data = json_decode($response, true);

            if (!isset($data['items'])) {
                return [
                    'success' => true,
                    'data' => [
                        'items' => [],
                        'totalResults' => 0
                    ],
                    'message' => 'No results found'
                ];
            }

            $items = array_map(function($item) {
                return [
                    'title' => $item['title'] ?? '',
                    'link' => $item['link'] ?? '',
                    'thumbnail' => $item['image']['thumbnailLink'] ?? '',
                    'width' => $item['image']['width'] ?? 0,
                    'height' => $item['image']['height'] ?? 0
                ];
            }, $data['items']);

            return [
                'success' => true,
                'data' => [
                    'items' => $items,
                    'totalResults' => $data['searchInformation']['totalResults'] ?? 0
                ],
                'message' => 'Success'
            ];

        } catch (\Exception $e) {
            return [
                'success' => false,
                'data' => null,
                'message' => $e->getMessage()
            ];
        }
    }


    /**
     * Get 'ai' group configuration base on company.
     * Also check validation (e.g. $validate = true).
     */
    public function getAIConfigFor($cmp, $model, $validate = false){

        $dataconfig = [];

        if(!in_array($model, array_keys($this->aiConfigSet))){
            throw new Exception("Invalid parameter model.");
        }

        $dataconfig = [];
        $avlConfig = DB::table('sys.company_metadata')
                        ->where(['company_id' => $cmp])->where('group_name', 'ai')
                        ->whereIn('module', $this->aiConfigSet[$model])
                        ->get();
        if ($avlConfig->count() == 0) {
            throw new Exception("No records found.");
        }

        $salt = Util::salt();
        foreach ($avlConfig as $cnf) {
            $val = $cnf->value;
            if($cnf->is_encrypted == true){
                $val = Util::Decrypt($salt, $val);
            }
            if($cnf->input_type == 'checkbox'){
                $val = $val ? true : false;
            }
            if($cnf->input_type == 'textarea'){
                $val = strip_tags($val);
            }
            $dataconfig[$cnf->module] = $val;
        }

        if(empty($dataconfig)){
            throw new Exception("No records found.");
        }

        if($validate){
            foreach ($this->aiConfigSet[$model] as $key) {
                if(str_contains($key, "_enable")){
                    if(empty($dataconfig[$key])){
                        throw new Exception($model." model is disable.");
                    }
                }
                if(empty($dataconfig[$key])){
                    throw new Exception("Invalid/missing ".$key);
                }
            }
        }
        return $dataconfig;
    }

    public function createResponse($data = null, $error = null, $code = 200) {
        return response()->json([
            'data' => $data,
            'response_code' => $code,
            'error' => $error
        ], $code);
    }


    /**
     * Company wise Api call counts. especially for Generate description & Image search apis.
     */
    private function addCounts($cmp, $apiName){

        $cmpId = Util::getCmpId($cmp);
        if(!in_array($apiName, ['generate_api', 'image_search_api'])){
            throw new Exception("Invalid api name, for log couting.");
        }

        $avlCounts = DB::table('sys.ai_api_counts')->where(['company_id' => $cmpId])->first();
        if(empty($avlCounts->id)){
            // Create new
            DB::table('sys.ai_api_counts')->insert([
                'company_id' => $cmpId,
                $apiName => 1,
                'createdon'=>now()
            ]);

        }else{
            // Update counts
            DB::table("sys.ai_api_counts")->where('company_id', $cmpId)->update([
                $apiName => ($avlCounts->$apiName + 1),
                'updatedon' => now()
            ]); 
        }
    }
}
