<?php

namespace App\Http\Controllers;

use App\Models\CrmSetting;
use Illuminate\Http\Request;

class SettingsController extends Controller
{
    public function index()
    {
        $settings = CrmSetting::query()->firstOrCreate(
            ['id' => 1],
            [
                'company_name' => config('app.name', 'HIGHRA CRM'),
                'currency' => 'INR',
                'timezone' => 'Asia/Kolkata'
            ]
        );

        $systemInfo = [
            'php_version' => PHP_VERSION,
            'laravel_version' => app()->version(),
            'app_env' => config('app.env'),
            'app_debug' => config('app.debug') ? 'Enabled' : 'Disabled',
            'database' => config('database.default'),
            'cache_driver' => config('cache.default'),
            'session_driver' => config('session.driver'),
        ];

        return view('settings.index', compact('settings', 'systemInfo'));
    }

    public function update(Request $request)
    {
        $data = $request->validate([
            'company_name' => 'required|string|max:120',
            'company_email' => 'nullable|email|max:160',
            'company_phone' => 'nullable|string|max:40',
            'company_address' => 'nullable|string|max:1000',
            'currency' => 'required|string|max:10',
            'timezone' => 'required|string|max:80',
        ]);

        CrmSetting::query()->updateOrCreate(['id' => 1], $data);

        return redirect()->route('settings.index')->with('success', 'System and Company settings saved successfully.');
    }
}
