<?php

namespace Modules\Admin\app\Http\Controllers;

use App\Helper\Cache\SettingCacheHelper;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Storage;
use Modules\Admin\app\Http\Requests\SettingRequest;
use Modules\Admin\app\Models\Setting;

class SettingController extends Controller
{
    public function index()
    {
        return response()->json([
            'data' => Setting::first(),
            'status' => true
        ]);
    }

    public function updateOrCreate(SettingRequest $request)
    {
        if ($request->has('logo')) {
            $file = $request->file('logo');
            $path = 'setting/logo.' . $file->getClientOriginalExtension();
            // save to local
            Storage::disk('public')->put(
                path: $path,
                contents: $file->getContent()
            );
            $request->request->set('logo', $path);
        }

        if ($request->has('favicon')) {
            $file = $request->file('favicon');
            $path = 'setting/favicon.' . $file->getClientOriginalExtension();
            // save to local
            Storage::disk('public')->put(
                path: $path,
                contents: $file->getContent()
            );
            $request->request->set('favicon', $path);
        }

        try {
            // Only 1 row
            Setting::updateOrCreate([
                'id' => 1
            ], $request->request->all());

            return response()->json([
                'data' => Setting::first(),
                'status' => true
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'message' => $e->getMessage(),
                'code' => $e->getCode(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'status' => false
            ]);
        }
    }

    public function clearCache()
    {
        Artisan::call('key:generate');
        Artisan::call('cache:clear');
        return response()->json([
            'status' => true
        ]);
    }
}
