<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ShareReportSetting;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;

class ShareReportSettingController extends Controller
{
    public function index(): View
    {
        return view('admin.share-report-settings.index', [
            'settings' => ShareReportSetting::current(),
        ]);
    }

    public function update(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'share_reports_enabled' => ['nullable', 'boolean'],
            'branding_text' => ['required', 'string', 'max:255'],
            'report_logo' => ['nullable', 'image', 'mimes:png,jpg,jpeg,webp', 'max:2048'],
            'watermark' => ['required', 'string', 'max:255'],
            'brand_color' => ['required', 'regex:/^#[0-9A-Fa-f]{6}$/'],
            'allow_profit_display' => ['nullable', 'boolean'],
            'show_badges' => ['nullable', 'boolean'],
            'show_motivational_line' => ['nullable', 'boolean'],
            'motivational_line' => ['required', 'string', 'max:255'],
            'default_template' => ['required', 'string', 'max:100'],
        ]);

        $settings = ShareReportSetting::current();

        if ($request->hasFile('report_logo')) {
            if ($settings->report_logo_path) {
                Storage::disk('public')->delete($settings->report_logo_path);
            }

            $data['report_logo_path'] = $request->file('report_logo')->store('share-report-logos', 'public');
        }

        unset($data['report_logo']);
        $data['share_reports_enabled'] = $request->boolean('share_reports_enabled');
        $data['allow_profit_display'] = $request->boolean('allow_profit_display');
        $data['show_badges'] = $request->boolean('show_badges');
        $data['show_motivational_line'] = $request->boolean('show_motivational_line');
        $settings->update($data);

        return back()->with('success', 'Share report settings updated.');
    }
}
