<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SiteSetting;
use Illuminate\Http\Request;

class HomepageContentController extends Controller
{
    public function edit()
    {
        $settings = SiteSetting::where('key', 'like', 'home_%')->pluck('value', 'key')->toArray();
        return view('admin.homepage.edit', compact('settings'));
    }

    public function update(Request $request)
    {
        $data = $request->except('_token', '_method', 'home_hero_bg_images', 'home_why_image_1', 'home_why_image_2');
        
        $imageFields = ['home_why_image_1', 'home_why_image_2'];
        
        foreach ($imageFields as $field) {
            if ($request->hasFile($field)) {
                $imageName = time() . '_' . $field . '.' . $request->file($field)->extension();
                $request->file($field)->move(public_path('uploads/hero'), $imageName);
                SiteSetting::updateOrCreate(['key' => $field], ['value' => 'uploads/hero/' . $imageName]);
            }
        }

        $existingImages = json_decode(SiteSetting::where('key', 'home_hero_bg_images')->value('value') ?? '[]', true);
        if (!is_array($existingImages)) {
            $existingImages = [];
        }

        if ($request->has('remove_hero_images')) {
            $existingImages = array_diff($existingImages, $request->input('remove_hero_images'));
        }

        if ($request->hasFile('home_hero_bg_images')) {
            foreach ($request->file('home_hero_bg_images') as $file) {
                $imageName = time() . '_' . uniqid() . '.' . $file->extension();
                $file->move(public_path('uploads/hero'), $imageName);
                $existingImages[] = 'uploads/hero/' . $imageName;
            }
        }
        
        if ($request->hasFile('home_hero_bg_images') || $request->has('remove_hero_images')) {
            $existingImages = array_values($existingImages); // Reindex array
            SiteSetting::updateOrCreate(['key' => 'home_hero_bg_images'], ['value' => json_encode($existingImages)]);
        }
        
        foreach ($data as $key => $value) {
            SiteSetting::updateOrCreate(['key' => $key], ['value' => $value]);
        }

        return redirect()->route('admin.homepage.edit')->with('success', 'Homepage content updated successfully.');
    }
}
