<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Config;
use App\Models\Language;
use App\Models\Movie;
use App\Traits\ImageTrait;
use Illuminate\Http\Request;

class WebsiteSettingController extends Controller
{
    use ImageTrait;

    public function themeOptions()
    {
        $page_data['movies'] = Movie::where('status', 1)->latest()->get();
        return view('admin.website.theme_options', $page_data);
    }

    public function updateThemesOptions(Request $request): \Illuminate\Http\JsonResponse
    {
        if (isDemoMode()) {
            $data = [
                'status'    => 'error',
                'message'   => 'This action is disabled in demo mode.',
                'title'     => __('error'),
                'is_reload' => false,
            ];
            return response()->json($data);
        }
        try {
            foreach ($request->all() as $key => $value) {
                if ($key === '_token') {
                    continue;
                }

                if ($request->hasFile($key)) {
                    // Delete old image if exists
                    if (!blank(get_config($key))) {
                        $this->deleteImage(json_decode(get_config($key), true));
                    }
                    // Save the new image
                    $response = $this->saveImage($request->file($key), $key);
                    $value = json_encode($response['images']);
                }

                // Update or create the config entry
                Config::updateOrCreate(
                    ['title' => $key],
                    ['value' => $value]
                );
            }


            $data = [
                'status' => 'success',
                'message' => __('setting_updated_successfully'),
                'title' => __('success'),
                'is_reload' => false,
            ];
            return response()->json($data);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => __('setting_updated_unsuccessfull'),
                'title' => __('error'),
                'is_reload' => false,
            ]);
        }
    }

    public function websiteSeo()
    {
        $page_data['languages'] = Language::get();
        $page_data['seo'] = Config::where('title', 'website_seo')->first();
        return view('admin.website.seo', $page_data);
    }

}
