<?php

namespace App\Http\Controllers\Admin;

use App\Helpers\ApiResponse;
use App\Helpers\CacheHelper;
use App\Http\Controllers\Controller;
use App\Models\PageTemplate;
use App\Services\PageTranslationSyncService;
use Exception;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;

class PageTemplateController extends Controller
{
    public function __construct(
        private readonly PageTranslationSyncService $pageTranslationSyncService,
    ) {
    }

    public function getPageallTemplate()
    {
        try {
            $user = Auth::user();
            $template = CacheHelper::remember('templates', function () use ($user) {

                if ($user->role === 'franchise_admin' || $user->role === 'franchise_editor') {
                    return PageTemplate::where('is_franchise_template', true)->get();
                } else {
                    return PageTemplate::all();
                }
            });
            return ApiResponse::success($template, 'All pages template retrieved successfully.');
        } catch (\Throwable $e) {
            return ApiResponse::exception($e);
        }
    }

    public function addTemplate(Request $request)
    {
        $user = Auth::user();
        try {
            // Validate input
            $validator = Validator::make($request->all(), [
                'name' => 'required|string|max:255',
            ]);

            if ($validator->fails()) {
                return ApiResponse::error($validator->errors()->first(), 422);
            }

            // Generate slug from name
            $slug = Str::slug($request->name);

            // Check uniqueness of slug
            if (PageTemplate::where('slug', $slug)->exists()) {
                return ApiResponse::error('A template with this name/slug already exists.', 422);
            }

            // Create template
            $template = PageTemplate::create([
                'name' => $request->name,
                'slug' => $slug,
                'content' => json_encode(["title" => $request->name])
            ]);
            CacheHelper::forget('templates');
            return ApiResponse::success($template, 'Template created successfully.');

        } catch (\Throwable $e) {
            return ApiResponse::exception($e);
        }
    }

    public function getTemplate(int $id)
    {
        try {
            $template = PageTemplate::find($id);

            if (!$template) {
                return response()->json([
                    'message' => 'Page not found.',
                ], 404);
            }
            return ApiResponse::success($template, 'Page retrieved successfully.');

        } catch (\Throwable $e) {
            return ApiResponse::exception($e);
        }
    }

    public function updateTemplate(Request $request, string $id)
    {
        $user = Auth::user();
        try {
            // Validate
            $validator = Validator::make($request->all(), [
                'name' => 'required|string|max:255',
            ]);

            if ($validator->fails()) {
                return ApiResponse::error($validator->errors()->first(), 422);
            }

            // Find the template
            $template = PageTemplate::find($id);
            if (!$template) {
                return ApiResponse::error('Template not found.', 404);
            }

            // Generate new slug
            $slug = Str::slug($request->name);

            // Check slug uniqueness (excluding current template)
            if (PageTemplate::where('slug', $slug)->where('id', '!=', $id)->exists()) {
                return ApiResponse::error('A template with this name/slug already exists.', 422);
            }

            // Update fields
            $template->update([
                'name' => $request->name,
                'slug' => $slug,
                'content' => json_encode(["title" => $request->name]),
            ]);
            if ($template->wasChanged(['name', 'slug', 'content'])) {
                $this->pageTranslationSyncService->bumpGlobalTranslationVersionsForPagesUsingTemplate($template->id);
            }
            CacheHelper::forget('templates');
            return ApiResponse::success($template, 'Template updated successfully.');
        } catch (\Throwable $e) {
            return ApiResponse::exception($e);
        }
    }
    public function deleteTemplateById(string $id)
    {
        try {
            $user = Auth::user();
            // Attempt to find the template by its ID
            $template = PageTemplate::find($id);

            // If the page does not exist, return a 404 response
            if (!$template) {
                return response()->json([
                    'error' => true,
                    'message' => 'Template not found.'
                ], 404);
            }

            // Delete the template from the database
            $template->delete();
            CacheHelper::forget('templates');
            // Return a successful deletion response
            return ApiResponse::success(null, 'Template deleted successfully.');
        } catch (\Throwable $e) {
            return ApiResponse::exception($e);
        }
    }
}
