<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class BusinessSettingController extends Controller
{
    public function __construct(protected \App\Services\BusinessSettingService $businessSettingService) {}

    public function index()
    {
        \Illuminate\Support\Facades\Gate::authorize(\App\Constants\Permissions::BUSINESS_BRANDING);

        return inertia('Admin/Business/Branding', [
            'settings' => $this->businessSettingService->getSettings([], true),
            'default_colors' => config('branding.colors'),
        ]);
    }

    public function update(Request $request)
    {
        \Illuminate\Support\Facades\Gate::authorize(\App\Constants\Permissions::BUSINESS_BRANDING);

        $validated = $request->validate([
            'business_name' => ['nullable', 'string', 'max:255'],
            'tagline' => ['nullable', 'string', 'max:255'],
            'industry' => ['nullable', 'string', 'max:255'],
            'primary' => ['nullable', 'string', 'max:20'],
            'primary_light' => ['nullable', 'string', 'max:20'],
            'primary_dark_text' => ['nullable', 'string', 'max:20'],
            'secondary' => ['nullable', 'string', 'max:20'],
            'sidebar_rail_bg' => ['nullable', 'string', 'max:20'],
            'sidebar_rail_bg_dark' => ['nullable', 'string', 'max:20'],
            'sidebar_icon_color' => ['nullable', 'string', 'max:20'],
            'sidebar_icon_color_dark' => ['nullable', 'string', 'max:20'],
            'contact_email' => ['nullable', 'string', 'max:255'],
            'contact_phone' => ['nullable', 'string', 'max:100'],
            'contact_address' => ['nullable', 'string', 'max:255'],
            'social_facebook' => ['nullable', 'string', 'max:255'],
            'social_twitter' => ['nullable', 'string', 'max:255'],
            'social_instagram' => ['nullable', 'string', 'max:255'],
            'logo_url' => ['nullable', 'image', 'max:5120'],
            'favicon_url' => ['nullable', 'image', 'max:2048'],
            'cover_url' => ['nullable', 'image', 'max:8192'],
        ]);

        $data = collect($validated)->except(['logo_url', 'favicon_url', 'cover_url'])->toArray();
        $files = [
            'logo_url' => $request->file('logo_url'),
            'favicon_url' => $request->file('favicon_url'),
            'cover_url' => $request->file('cover_url'),
        ];

        $this->businessSettingService->updateBranding($data, $files);

        return back()->with('success', 'Settings updated successfully.');
    }
}
