<?php

/*
    Created by Mohamed.
*/


namespace App\Http\Controllers\API\Dashboard;

use App\Models\StaticPage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use App\Http\Resources\StaticPageResource;

class StaticPageController extends Controller
{
    public function index(Request $request)
    {
        $key = $request->query('key');

        if (!$key) {
            return response()->json([
                'message' => 'Key is required'
            ], 400);
        }

        $page = StaticPage::where('key', $key)->first();

        if (!$page) {
            return response()->json([
                'message' => 'Static page not found'
            ], 404);
        }

        return new StaticPageResource($page);
    }

    // POST /dashboard/static-pages/{id}


    public function update(Request $request)
    {
        try {
            $page = StaticPage::where('key', $request->key)->first();

            if (!$page) {
                return response()->json([
                    'message' => 'Static page not found'
                ], 404);
            }

            $request->validate([
                'title_ar' => 'nullable|string',
                'title_en' => 'nullable|string',
                'content_ar' => 'nullable|string',
                'content_en' => 'nullable|string',
                'image' => 'nullable|image|mimes:jpg,jpeg,png,webp|max:2048'
            ]);

            $data = $request->only([
                'title_ar',
                'title_en',
                'content_ar',
                'content_en',
            ]);

            if ($request->hasFile('image')) {
                $imagePath = $request->file('image')->store('static_pages', 'public');
                $data['image'] = Storage::url($imagePath);
            }

            $page->update($data);

            return response()->json([
                'message' => 'Static page updated successfully',
                'data' => new StaticPageResource($page)
            ]);
        } catch (\Exception $e) {
            // Log error for debugging
            Log::error('StaticPage update error: ' . $e->getMessage());

            return response()->json([
                'message' => 'Something went wrong while updating the static page',
                'error' => $e->getMessage(), // يمكنك حذف هذا في الإنتاج
            ], 500);
        }
    }

}