<?php

namespace Dashboard\Controllers;

use Curl\Curl;
use Dashboard\Core\Controller;
use PDO;

class ModuleController extends Controller
{
    public function __construct()
    {
        abort_perm('MANAGE_SETTINGS');
    }

    public function index()
    {
        $modules = db()->query("SELECT * FROM Modules");
        $modules = $modules->fetchAll(PDO::FETCH_ASSOC);

        $moduleSettingsLinks = [
            'blog' => url('dashboard.settings.blog.index'),
            'store' => url('dashboard.settings.store.index'),
            'vote' => url('dashboard.settings.vote.index'),
            'chest' => url('dashboard.settings.chest.index'),
            'credit' => url('dashboard.settings.credit.index'),
            'support' => url('dashboard.settings.support.index'),
            'bazaar' => url('dashboard.settings.bazaar.index'),
            'gaming_night' => url('dashboard.gaming-night.index'),
            'popup' => url('dashboard.popup.edit'),
            'tebex_store' => url('dashboard.tebex-store.settings.index'),
            'birfatura' => url('dashboard.settings.birfatura.index'),
            'parasut' => url('dashboard.settings.parasut.index'),
            'punishments' => url('dashboard.settings.punishments.index'),
            'discord' => url('dashboard.settings.discord-bot-legacy.index'),
            'discord_bot' => url('dashboard.settings.discord-bot.index'),
            'account_linking' => url('dashboard.settings.account-linking.index'),
            'recaptcha' => url('dashboard.settings.recaptcha.index'),
            'tawkto' => url('dashboard.settings.tawkto.index'),
            'google_analytics' => url('dashboard.settings.google-analytics.index'),
            'ai' => url('dashboard.ai.settings.index'),
        ];

        $modules = array_map(function ($module) use ($moduleSettingsLinks) {
            $module['settingsUrl'] = $moduleSettingsLinks[$module['slug']] ?? null;

            return $module;
        }, $modules);

        return view('modules.index', compact('modules'));
    }

    public function toggle($id)
    {
        $module = db()->prepare("SELECT * FROM Modules WHERE id = ?");
        $module->execute(array($id));
        $module = $module->fetch();

        $updateModules = db()->prepare("UPDATE Modules SET isEnabled = ? WHERE id = ?");
        $updateModules->execute(array($module['isEnabled'] == '0' ? '1' : '0', $id));

        createLog("MODULES_UPDATED");

        response()->json([
          'status' => 'success',
          'message' => $module['isEnabled'] == '0' ? t__('Module enabled successfully!') : t__('Module disabled successfully!')
        ]);
    }
}