<?php

namespace App\Http\Controllers\Shop;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\SiteSetting;
use Illuminate\Http\JsonResponse;

class HomeController extends Controller
{
    public function index(): JsonResponse
    {
        /** @var \App\Models\Tenant $tenant */
        $tenant   = app('tenant');
        $settings = SiteSetting::where('tenant_id', $tenant->id)->first();
        if (!$settings) {
            $settings = new SiteSetting();
        }

        // Fallback to Super Admin's global branding if tenant hasn't updated theirs
        $globalBrand = \Illuminate\Support\Facades\DB::table('global_settings')
            ->whereIn('setting_key', ['logo_url', 'favicon_url'])
            ->pluck('setting_value', 'setting_key');
            
        if (empty($settings->logo)) {
            $settings->logo = $globalBrand['logo_url'] ?? '';
            // If they haven't set footer/promise, we can use the same fallback just in case
            if (empty($settings->footerLogo)) $settings->footerLogo = $globalBrand['logo_url'] ?? '';
            if (empty($settings->promiseImage)) $settings->promiseImage = $globalBrand['logo_url'] ?? '';
        }
        if (empty($settings->favicon)) {
            $settings->favicon = $globalBrand['favicon_url'] ?? '';
        }

        $products = Product::where('tenant_id', $tenant->id)
                           ->where('is_active', true)
                           ->latest()->limit(20)->get();

        return response()->json([
            'success'  => true,
            'tenant'   => $tenant->only(['business_name', 'business_slug', 'business_category']),
            'settings' => $settings,
            'products' => $products,
        ]);
    }
}
