<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\JobFormSettings;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class JobFormSettingsController extends Controller
{
    public function show()
    {
        $settings = JobFormSettings::getOrCreate();
        return response()->json($settings);
    }

    public function update(Request $request)
    {
        $validated = $request->validate([
            'company_name'     => 'nullable|string|max:255',
            'company_address'  => 'nullable|string|max:1000',
            'company_phone'    => 'nullable|string|max:50',
            'company_email'    => 'nullable|email|max:255',
            'company_website'  => 'nullable|string|max:255',
            'form_footer_text' => 'nullable|string|max:2000',
            'primary_color'    => 'nullable|string|max:20',
            'company_logo'     => 'nullable|image|mimes:jpg,jpeg,png,webp|max:2048',
            'social_instagram' => 'nullable|string|max:255',
            'social_linkedin'  => 'nullable|string|max:255',
            'social_twitter'   => 'nullable|string|max:255',
            'social_youtube'   => 'nullable|string|max:255',
            'social_facebook'  => 'nullable|string|max:255',
            'application_url'  => 'nullable|string|max:500',
        ]);

        $settings = JobFormSettings::getOrCreate();

        $data = collect($validated)->except('company_logo')->toArray();

        if ($request->hasFile('company_logo')) {
            // Delete old logo if exists
            if ($settings->company_logo_path && Storage::disk('public')->exists($settings->company_logo_path)) {
                Storage::disk('public')->delete($settings->company_logo_path);
            }
            $path = $request->file('company_logo')->store('form-settings', 'public');
            $data['company_logo_path'] = $path;
        }

        $settings->update($data);

        return response()->json([
            'success'  => true,
            'message'  => 'Form ayarları kaydedildi.',
            'settings' => $settings->fresh(),
        ]);
    }
}