<?php

namespace App\Http\Controllers;

use App\Models\SiteInfo;
use Illuminate\Http\Request;
use Inertia\Inertia;

class SiteInfoController extends Controller
{

    public function editContact()
    {
        $contact = SiteInfo::firstOrCreate(
            ['key' => 'contact_details'],
            ['value' => [
                'email' => '',
                'phone' => '',
                'address' => '',
                'openCloseTime' => '',
                'mapSrc' => '',
            ]]
        );

        return Inertia::render('dashboard/site-info/contact', [
            'contacts' => $contact->value
        ]);
    }

    public function updateContact(Request $request)
    {
        $data = $request->validate([
            'title' => 'nullable|string|max:255',
            'description' => 'nullable|string',
            'email' => 'nullable|email|max:255',
            'phone' => 'nullable|string|max:40',
            'address' => 'nullable|string|max:255',
            'openCloseTime' => 'nullable|string|max:50',
            'mapSrc' => 'nullable|string|max:500'
        ]);

        $contact = SiteInfo::updateOrCreate(
            ['key' => 'contact_details'],
            ['value' => $data]
        );

        return redirect()->back()->with('success', 'Contact details updated.');
    }

    public function editSocialLinks()
    {
        $social_links = SiteInfo::firstOrCreate(
            ['key' => 'social_links'],
            ['value' => []]
        );

        return Inertia::render('dashboard/site-info/social-links', [
            'social_links' => $social_links->value
        ]);
    }

    public function updateSocialLinks(Request $request)
    {
        $validated = $request->validate([
            '*.id' => 'nullable|integer',
            '*.icon' => 'required|string|max:50',
            '*.label' => 'required|string|max:100',
            '*.link' => 'nullable|string|max:255',
            '*.color' => 'nullable|string|max:50',
        ]);

        // Save into site_infos table as JSON
        SiteInfo::updateOrCreate(
            ['key' => 'social_links'],
            ['value' => $validated]
        );

        return redirect()->back()->with('success', 'Social links updated successfully.');
    }
}
