<?php

namespace App\Http\Controllers;

use App\Models\SiteSetting;
use App\Models\PageContent;
use Illuminate\Http\Request;

class AdminController extends Controller
{
    public function editSettings()
    {
        $settings = SiteSetting::all()->pluck('value', 'key');
        return view('pages.admin.settings', compact('settings'));
    }

    public function updateSettings(Request $request)
    {
        $data = $request->except('_token');
        foreach ($data as $key => $value) {
            SiteSetting::updateOrCreate(['key' => $key], ['value' => $value]);
        }
        return back()->with('success', 'Site settings updated successfully.');
    }

    public function editPageContent($page_slug)
    {
        $contents = PageContent::where('page_slug', $page_slug)->get();
        return view('pages.admin.page-content', compact('contents', 'page_slug'));
    }

    public function updatePageContent(Request $request, $page_slug)
    {
        $request->validate([
            'contents' => 'required|array',
            'contents.*.id' => 'required|exists:page_contents,id',
            'contents.*.title' => 'required|string|max:255',
            'contents.*.body' => 'required|string',
        ]);

        foreach ($request->contents as $data) {
            PageContent::where('id', $data['id'])->update([
                'title' => $data['title'],
                'body' => $data['body'],
            ]);
        }

        return redirect()->route($page_slug)->with('success', ucfirst($page_slug) . ' page content updated.');
    }
}
