<?php

namespace Dashboard\Controllers\AI;

use Dashboard\Core\Controller;
use Dashboard\Services\AiService;
use Exception;

class AiController extends Controller
{
    public function __construct()
    {
        abort_perm('MANAGE_AI');
    }

    public function index()
    {
				try {
					$subscription = AiService::getSubscription();
				} catch (Exception $e) {
					return view('ai.error', ['error' => $e->getMessage()]);
				}
				
				if (!$subscription) {
					return view('ai.subscribe');
				}
				
        return view('ai.index', compact('subscription'));
    }
		
		public function generateWithAi()
		{
			$data = file_get_contents('php://input');
			$data = json_decode($data, true);
			
			if (!$data || !isset($data['type']) || !isset($data['prompt'])) {
				response()->json([
					'status' => false,
				]);
			}
			
			try {
				$content = AiService::generateWithAI($data['type'], $data['prompt']);
				
				response()->json([
					'status' => true,
					'content' => $content
				]);
			} catch (Exception $e) {
				response()->json([
					'status' => false,
					'error' => $e->getMessage(),
				]);
			}
		}
}