<?php

namespace Modules\WebPilotAI\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
// Illuminate\Http\Response; // Not strictly needed if not returning raw Response objects
use Modules\WebPilotAI\Models\AITemplate;
use Illuminate\Support\Str; // For slug generation
use Illuminate\Support\Facades\Storage; // For file storage

class AITemplateController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $aiTemplates = AITemplate::orderBy('name')->paginate(15);
        return view('webpilotai::admin.ai_templates.index', compact('aiTemplates'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('webpilotai::admin.ai_templates.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request): RedirectResponse
    {
        $validatedData = $request->validate([
            'name' => 'required|string|max:255|unique:ai_templates,name',
            'description' => 'nullable|string',
            'preview_image_path' => 'nullable|image|mimes:jpg,jpeg,png,gif,webp|max:2048', // Max 2MB
            'prompt_structure' => ['required', 'string', function ($attribute, $value, $fail) {
                if (!empty($value)) {
                    json_decode($value);
                    if (json_last_error() !== JSON_ERROR_NONE) {
                        $fail('The ' . $attribute . ' must be a valid JSON string.');
                    }
                }
            }],
            'is_active' => 'nullable|boolean',
            'is_premium' => 'nullable|boolean',
            // 'sort_order' => 'nullable|integer', // Defaulted below
        ]);

        $data = $validatedData;
        $data['slug'] = Str::slug($validatedData['name']);
        $data['is_active'] = $request->has('is_active');
        $data['is_premium'] = $request->has('is_premium');

        if ($request->hasFile('preview_image_path')) {
            $data['preview_image_path'] = $request->file('preview_image_path')->store('webpilotai/template_previews', 'public');
        }

        $data['sort_order'] = $request->input('sort_order', 0); // Default sort_order if not provided
        $data['prompt_modifications'] = !empty($validatedData['prompt_structure']) ? json_decode($validatedData['prompt_structure'], true) : null;

        AITemplate::create($data);

        return redirect()->route('admin.webpilotai.ai-templates.index')->with('success', 'AI Template created successfully.');
    }

    /**
     * Show the specified resource.
     */
    public function show(AITemplate $aiTemplate) // Using Route Model Binding
    {
        // Typically not needed for admin CRUD, redirect to edit or index.
        return redirect()->route('admin.webpilotai.ai-templates.edit', $aiTemplate->id);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(AITemplate $aiTemplate) // Using Route Model Binding
    {
        return view('webpilotai::admin.ai_templates.edit', compact('aiTemplate'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, AITemplate $aiTemplate): RedirectResponse // Using Route Model Binding
    {
        $validatedData = $request->validate([
            'name' => 'required|string|max:255|unique:ai_templates,name,' . $aiTemplate->id,
            'description' => 'nullable|string',
            'preview_image_path' => 'nullable|image|mimes:jpg,jpeg,png,gif,webp|max:2048',
            'prompt_structure' => ['required', 'string', function ($attribute, $value, $fail) {
                if (!empty($value)) {
                    json_decode($value);
                    if (json_last_error() !== JSON_ERROR_NONE) {
                        $fail('The ' . $attribute . ' must be a valid JSON string.');
                    }
                }
            }],
            'is_active' => 'nullable|boolean',
            'is_premium' => 'nullable|boolean',
            // 'sort_order' => 'nullable|integer', // Handled below
        ]);

        $data = $validatedData;
        $data['slug'] = Str::slug($validatedData['name']);
        $data['is_active'] = $request->has('is_active');
        $data['is_premium'] = $request->has('is_premium');

        if ($request->hasFile('preview_image_path')) {
            // Delete old image if it exists
            if ($aiTemplate->preview_image_path) {
                Storage::disk('public')->delete($aiTemplate->preview_image_path);
            }
            $data['preview_image_path'] = $request->file('preview_image_path')->store('webpilotai/template_previews', 'public');
        } elseif ($request->has('remove_preview_image') && $aiTemplate->preview_image_path) {
            // Handle removal of preview image
            Storage::disk('public')->delete($aiTemplate->preview_image_path);
            $data['preview_image_path'] = null;
        }

        $data['sort_order'] = $request->input('sort_order', $aiTemplate->sort_order); // Keep existing or update
        $data['prompt_modifications'] = !empty($validatedData['prompt_structure']) ? json_decode($validatedData['prompt_structure'], true) : null;

        $aiTemplate->update($data);

        return redirect()->route('admin.webpilotai.ai-templates.index')->with('success', 'AI Template updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(AITemplate $aiTemplate): RedirectResponse // Using Route Model Binding
    {
        if ($aiTemplate->preview_image_path) {
            Storage::disk('public')->delete($aiTemplate->preview_image_path);
        }
        $aiTemplate->delete();

        return redirect()->route('admin.webpilotai.ai-templates.index')->with('success', 'AI Template deleted successfully.');
    }
}
