<?php

namespace App\Http\Controllers\Settings;

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

class BrandingController extends Controller
{
    public function edit(): View
    {
        $dealer = $this->currentDealer();

        return view('settings.branding.edit', [
            'dealer' => $dealer,
            'branding' => [
                'nav_color' => $dealer->nav_color,
                'accent_color' => $dealer->accent_color,
                'accent_color_2' => $dealer->accent_color_2,
                'background_color' => $dealer->background_color,
                'topbar_color' => $dealer->topbar_color,
            ],
        ]);
    }

    public function update(Request $request): RedirectResponse
    {
        $dealer = $this->currentDealer();

        $data = $request->validate([
            'nav_color' => ['nullable', 'string', 'regex:/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/'],
            'accent_color' => ['nullable', 'string', 'regex:/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/'],
            'accent_color_2' => ['nullable', 'string', 'regex:/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/'],
            'background_color' => ['nullable', 'string', 'regex:/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/'],
            'topbar_color' => ['nullable', 'string', 'regex:/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/'],
            'logo_reset' => ['sometimes', 'boolean'],
            'logo' => ['nullable', 'image', 'max:2048'],
            'favicon_reset' => ['sometimes', 'boolean'],
            'favicon' => [
                'nullable',
                'file',
                // Allow common favicon formats.
                'mimetypes:image/x-icon,image/vnd.microsoft.icon,image/png,image/svg+xml',
                'max:512',
            ],
            'login_background' => ['nullable', 'image', 'max:3072'],
            'login_logo' => ['nullable', 'image', 'max:2048'],
            'login_accent_color' => ['nullable', 'string', 'regex:/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/'],
        ]);

        if (! empty($data['nav_color'])) {
            $dealer->nav_color = $data['nav_color'];
        }
        if (! empty($data['accent_color'])) {
            $dealer->accent_color = $data['accent_color'];
        }
        if (! empty($data['accent_color_2'])) {
            $dealer->accent_color_2 = $data['accent_color_2'];
        }
        if (! empty($data['background_color'])) {
            $dealer->background_color = $data['background_color'];
        }
        if (! empty($data['topbar_color'])) {
            $dealer->topbar_color = $data['topbar_color'];
        }

        // Handle logo upload / reset.
        if (! empty($data['logo_reset'])) {
            $dealer->logo_path = null;
        }

        if ($request->hasFile('logo')) {
            $disk = 'public';

            // Optionally clean up the previous logo file when replacing.
            if ($dealer->logo_path) {
                Storage::disk($disk)->delete($dealer->logo_path);
            }

            $path = $request->file('logo')->store('dealer-logos', ['disk' => $disk]);
            $dealer->logo_path = $path;
        }

        // Handle login background / logo uploads.
        if ($request->hasFile('login_background')) {
            $disk = 'public';
            if ($dealer->login_background_path) {
                Storage::disk($disk)->delete($dealer->login_background_path);
            }
            $path = $request->file('login_background')->store('dealer-login-backgrounds', ['disk' => $disk]);
            $dealer->login_background_path = $path;
        }

        if ($request->hasFile('login_logo')) {
            $disk = 'public';
            if ($dealer->login_logo_path) {
                Storage::disk($disk)->delete($dealer->login_logo_path);
            }
            $path = $request->file('login_logo')->store('dealer-login-logos', ['disk' => $disk]);
            $dealer->login_logo_path = $path;
        }

        if (! empty($data['login_accent_color'])) {
            $dealer->login_accent_color = $data['login_accent_color'];
        }

        // Handle favicon upload / reset (same pattern as logo).
        if (! empty($data['favicon_reset'])) {
            $dealer->favicon_path = null;
        }

        if ($request->hasFile('favicon')) {
            $disk = 'public';

            if ($dealer->favicon_path) {
                Storage::disk($disk)->delete($dealer->favicon_path);
            }

            $path = $request->file('favicon')->store('dealer-favicons', ['disk' => $disk]);
            $dealer->favicon_path = $path;
        }

        $dealer->save();

        return redirect()
            ->route('settings.branding.edit')
            ->with('status', 'Branding updated successfully.');
    }

    private function currentDealer(): Dealer
    {
        $user = auth()->user();
        $dealerId = session('current_dealer_id') ?: $user->dealer_id;

        /** @var Dealer $dealer */
        $dealer = Dealer::query()->findOrFail($dealerId);

        return $dealer;
    }
}

