<?php

namespace App\Http\Controllers;

use App\Models\Campaign;
use App\Models\User;
use App\Services\ContactFieldRegistry;
use App\Services\MediaUploadService;
use App\Services\RecurringScheduleCalculator;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

/**
 * All sections are stored in a single global_settings JSON column on the
 * user, keyed by section (e.g. global_settings['business']['name']) - a
 * section is saved independently of the others via the `section` param.
 */
class SettingsController extends Controller
{
    public function index(): Response
    {
        return Inertia::render('Settings/Index', [
            'settings'      => auth()->user()->global_settings ?? [],
            'builtinFields' => array_column(ContactFieldRegistry::FIELDS, 'label'),
        ]);
    }

    public function update(Request $request): JsonResponse
    {
        $data = $request->validate([
            'section' => 'required|string|max:64',
            'data'    => 'required|array',
        ]);

        $user     = auth()->user();
        $settings = $user->global_settings ?? [];

        $previousTimezone = $settings['general']['timezone'] ?? null;

        $settings[$data['section']] = $data['data'];
        $user->update(['global_settings' => $settings]);

        // Timezone drives every recurring campaign's next_run_at (see
        // RecurringScheduleCalculator)  when it changes, reschedule all of
        // this tenant's active recurring campaigns immediately rather than
        // waiting for their next dispatch check to pick up the new offset.
        if ($data['section'] === 'general') {
            $newTimezone = $data['data']['timezone'] ?? null;
            if ($newTimezone && $newTimezone !== $previousTimezone) {
                $this->rescheduleRecurringCampaigns($user);
            }
        }

        return response()->json(['success' => true, 'settings' => $settings]);
    }

    public function uploadLogo(Request $request, MediaUploadService $uploads): JsonResponse
    {
        $request->validate([
            'logo' => 'required|image|mimes:jpg,jpeg,png,gif,webp,svg|max:2048',
        ]);

        $media = $uploads->replaceLatestInCollection($request->user(), 'business-logo', $request->file('logo'));

        return response()->json(['url' => $media->url]);
    }

    private function rescheduleRecurringCampaigns(User $user): void
    {
        Campaign::where('user_id', $user->id)
            ->where('type', 'recurring')
            ->where('status', 'active')
            ->get()
            ->each(function (Campaign $template) {
                $template->update(['next_run_at' => RecurringScheduleCalculator::nextRunAt($template)]);
            });
    }
}
