<?php

namespace App\Http\Controllers\Admin;

use App\Models\ServiceCategory;
use App\Models\ServiceCategoryDetail;
use App\Models\ServiceCategoryItem;
use App\Models\Image;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ServiceCategoryDetailController extends Controller
{
    public function edit($category_id)
    {
        $category = ServiceCategory::findOrFail($category_id);
        $detail = ServiceCategoryDetail::firstOrCreate(['service_category_id' => $category_id]);
        $detail->load('items.image', 'heroImage', 'section1Image1', 'section1Image2', 'section1Image3', 'section2Image');
        
        return view('admin.service-categories.details', compact('category', 'detail'));
    }

    public function update(Request $request, $category_id)
    {
        $category = ServiceCategory::findOrFail($category_id);
        $detail = ServiceCategoryDetail::firstOrCreate(['service_category_id' => $category_id]);

        $data = $request->except('items');
        $detail->update($data);

        // Handle items (Cards/Steps)
        $detail->items()->delete();
        if ($request->has('items')) {
            foreach ($request->items as $type => $items) {
                foreach ($items as $item) {
                    if (!empty($item['title'])) {
                        $detail->items()->create(array_merge($item, ['type' => $type]));
                    }
                }
            }
        }

        return back()->with('success', 'Service category details updated successfully.');
    }
}
