<?php

namespace Dashboard\Controllers\AI;

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

class SettingController 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.settings');
    }
		public function update()
		{
			$module = db()->prepare("SELECT * FROM Modules WHERE slug = ?");
			$module->execute(['ai']);
			$module = $module->fetch();
			if (!$module) {
				abort_404();
			}
			
			foreach ($_POST as $key => $value) {
				$updateSettings = db()->prepare("UPDATE ModuleSettings SET value = ? WHERE name = ? AND moduleID = ?");
				$updateSettings->execute([input($key), $key, $module['id']]);
			}
			createLog("AI_SETTINGS_UPDATED");
			
			return back()->flash("success", t__('Changes has been saved successfully!'));
		}
}