<?php

namespace App\Http\Controllers;

use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class SettingsController extends Controller
{
    public function modules()
    {
        // Define available modules and their default states
        $modules = [
            'module_crm' => ['name' => 'CRM & Sales', 'description' => 'Customer management, pipelines, and sales team commissions.', 'default' => true],
            'module_accounting' => ['name' => 'Advanced Accounting', 'description' => 'Journals, Treasuries, and Financial Reports.', 'default' => true],
            'module_hr' => ['name' => 'HR & Payroll', 'description' => 'Employee management, attendance, and payroll (Coming Soon).', 'default' => false],
            'module_inventory' => ['name' => 'Inventory & Warehouses', 'description' => 'Stock management, product variants, and warehouses.', 'default' => false], // Disabled by default for service business
            'module_projects' => ['name' => 'Project Management', 'description' => 'Track project progress, tasks, and budgets.', 'default' => true],
            'module_quotations' => ['name' => 'Quotations & Offers', 'description' => 'Create and manage price offers.', 'default' => true],
            'module_subscriptions' => ['name' => 'Subscriptions', 'description' => 'Manage recurring services and WHMCS sync.', 'default' => true],
            'module_ai' => ['name' => 'AI Features', 'description' => 'AI Auditor, Forecasting, and Smart Insights.', 'default' => true],
        ];

        // Fetch settings specifically for the 'modules' group
        $settings = Setting::where('group', 'modules')
            ->whereIn('key', array_keys($modules))
            ->pluck('value', 'key');

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

    public function updateModules(Request $request)
    {
        $modules = [
            'module_crm',
            'module_accounting',
            'module_hr',
            'module_inventory',
            'module_projects',
            'module_quotations',
            'module_subscriptions',
            'module_ai'
        ];

        foreach ($modules as $module) {
            Setting::setValue('modules', $module, $request->has($module) ? '1' : '0');
        }

        // Clear general cache
        Cache::forget('app_settings');

        return redirect()->back()->with('success', __('Module settings updated successfully.'));
    }
}
