<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Cache;

class SeoSettingsController extends Controller
{
    /**
     * Get all SEO settings
     */
    public function index(): JsonResponse
    {
        $settings = Setting::where('group', 'seo')
            ->pluck('value', 'key')
            ->toArray();

        return response()->json($settings);
    }

    /**
     * Update SEO settings (Text + Files)
     */
    public function update(Request $request): JsonResponse
    {
        $request->validate([
            'site_name'        => 'nullable|string|max:255',
            'meta_description' => 'nullable|string|max:500',
            'meta_keywords'    => 'nullable|string|max:255',
            'og_title'         => 'nullable|string|max:255',
            'og_description'   => 'nullable|string|max:500',
            'site_logo_light'  => 'nullable|image|max:2048', // 2MB Max (Light Theme)
            'site_logo_dark'   => 'nullable|image|max:2048', // 2MB Max (Dark Theme)
            'site_favicon'     => 'nullable|image|mimes:ico,png,jpg,svg|max:1024',
            'og_image'         => 'nullable|image|max:4096', // 4MB Max for high res social
        ]);

        $inputs = $request->except(['site_logo_light', 'site_logo_dark', 'site_favicon', 'og_image', 'site_logo']);

        // 1. Save Text Fields
        foreach ($inputs as $key => $value) {
            Setting::updateOrCreate(['group' => 'seo', 'key' => $key],
                ['value' => $value]
            );
        }

        // 2. Handle File Uploads
        $this->handleFileUpload($request, 'site_logo_light', 'seo');
        $this->handleFileUpload($request, 'site_logo_dark', 'seo');
        $this->handleFileUpload($request, 'site_favicon', 'seo');
        $this->handleFileUpload($request, 'og_image', 'seo');

        // Clear cache so frontend sees changes immediately
        Cache::forget('seo_settings');

        return response()->json(['message' => 'SEO Settings updated successfully.']);
    }

    private function handleFileUpload(Request $request, string $key, string $group)
    {
        if ($request->hasFile($key)) {
            // Delete old file if exists
            $oldSetting = Setting::where('group', $group)->where('key', $key)->first();
            if ($oldSetting && $oldSetting->value) {
                // Strip '/storage/' to get relative path
                $relativePath = str_replace('/storage/', '', $oldSetting->value);
                Storage::disk('public')->delete($relativePath);
            }

            // Upload new file
            $path = $request->file($key)->store('uploads/seo', 'public');
            
            // Save path to DB
            Setting::updateOrCreate(
                ['group' => $group, 'key' => $key],
                ['value' => '/storage/' . $path]
            );
        }
    }
}