<?php
class Aihandler extends CI_Controller {
    
    public function process() {
        $prompt = $this->input->post('prompt', true);
        $field  = $this->input->post('field', true); // e.g., 'Title' or 'Description'

        $lang   = $this->input->post('lang', true); // response language
        
        $this->load->library('ai_gateway');
        
        // Contextual Prompting logic
        $instructions = [
            'Title' => "Act as a restaurant menu expert. Generate a catchy and professional menu item Title based on the following context. Keep it under 50 characters. Result only.",
            'Description' => "Act as a restaurant menu expert. Generate a short, appetizing small description (overview) for a menu item. Max 150 characters. Result only.",
            'Details' => "Act as a restaurant menu expert. Generate a detailed description of a menu item, describing taste, ingredients, and why customers love it. Result only.",
            'Image' => "Act as an AI image prompt engineer. Generate a highly detailed, photorealistic prompt for an food photography image based on the item title. Return only the prompt string."
        ];

        $instruct = isset($instructions[$field]) ? $instructions[$field] : "Act as a menu expert. Generate a $field for: ";
        
        if (!empty($lang) && $field !== 'Image') {
            $instruct .= " The response MUST be in $lang language.";
        }
        
        $final_prompt = "$instruct context: $prompt";
        
        $response = $this->ai_gateway->generate($final_prompt, $field);
        
        if ($field === 'Image' && strpos($response, 'Error') === false && $response !== "No Image Found" && !empty($response)) {
            // Check if it's already a URL (e.g., from Unsplash fallback or direct AI image generation)
            if (preg_match('~^https?://~i', trim($response))) {
                $result = ['status' => 'success', 'data' => trim($response), 'is_image' => true, 'raw_prompt' => 'URL from AI'];
            } else {
                // Clean up the prompt: strip markdown, "Prompt:", quotes, etc.
                $clean_response = preg_replace('/^(Prompt|Result|Output|Here is your prompt|Image Prompt|Generated Prompt):\s*/i', '', trim($response));
                $clean_response = trim($clean_response, '"\'` \t\n\r\0\x0B');
                // Remove markdown code blocks if present
                $clean_response = preg_replace('/^```[\w]*\n?|```$/', '', $clean_response);
                
                // Use Pollinations.ai for instant image generation via URL
                $image_url = "https://image.pollinations.ai/prompt/" . rawurlencode(trim($clean_response)) . "?width=1000&height=1000&nologo=true&seed=" . random_string('numeric', 10);
                $result = ['status' => 'success', 'data' => $image_url, 'is_image' => true, 'raw_prompt' => $clean_response];
            }
        } else if (strpos($response, 'Error') !== false || strpos($response, 'cURL') !== false || $response === "No Image Found" || empty($response)) {
             $result = ['status' => 'error', 'message' => empty($response) ? "AI service returned empty response" : $response];
        } else {
             $result = ['status' => 'success', 'data' => $response];
        }
        
        echo json_encode($result);
    }

    public function save_image() {
        $url = $this->input->post('url', true);
        if (empty($url)) {
            echo json_encode(['status' => 'error', 'message' => 'No URL provided']);
            return;
        }

        $this->load->helper('string');
        $this->load->library('image_lib');

        try {
            $client = new \GuzzleHttp\Client(['timeout' => 45, 'verify' => false]);
            $response = $client->get($url);
            
            if ($response->getStatusCode() != 200) {
                echo json_encode(['status' => 'error', 'message' => 'Failed to download image. Status Code: ' . $response->getStatusCode()]);
                return;
            }

            $img_data = $response->getBody()->getContents();
        } catch (\Exception $e) {
            echo json_encode(['status' => 'error', 'message' => 'Guzzle Error: ' . $e->getMessage()]);
            return;
        }

        if (empty($img_data)) {
            echo json_encode(['status' => 'error', 'message' => 'Image data is empty']);
            return;
        }

        $filename = 'ai_' . random_string('alnum', 16) . '.jpg';
        $temp_dir = 'uploads/ai_images/';
        $full_temp_dir = FCPATH . $temp_dir;

        if (!is_dir($full_temp_dir)) {
            mkdir($full_temp_dir, 0777, true);
        }

        $temp_path = $temp_dir . $filename;
        file_put_contents(FCPATH . $temp_path, $img_data);

        // Run cleanup for old AI images (files older than 1 hour)
        $this->cleanup_ai_images($full_temp_dir);

        echo json_encode([
            'status' => 'success',
            'thumb' => $temp_path,
            'image' => $temp_path
        ]);
    }

    private function cleanup_ai_images($dir) {
        $files = glob($dir . '*');
        $now = time();
        foreach ($files as $file) {
            if (is_file($file)) {
                if ($now - filemtime($file) >= 3600) { // 1 hour
                    unlink($file);
                }
            }
        }
    }
}