<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\PromptLibrary;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\View\View;

class PromptLibraryController extends Controller
{
    public function index(): View
    {
        $prompts = PromptLibrary::query()->latest()->paginate(20);
        return view('admin.prompts.index', compact('prompts'));
    }

    public function create(): View
    {
        return view('admin.prompts.create');
    }

    public function store(Request $request): RedirectResponse
    {
        $validated = $this->validatePrompt($request);
        $normalized = $this->normalizePrompt($validated['prompt_text']);

        PromptLibrary::create([
            'title' => $validated['title'],
            'slug' => Str::slug($validated['title']).'-'.Str::lower(Str::random(6)),
            'category' => $validated['category'] ?? 'general',
            'prompt_text' => $validated['prompt_text'],
            'normalized_prompt_text' => $normalized,
            'status' => $validated['status'] ?? 'active',
            'sort_order' => (int) ($validated['sort_order'] ?? 0),
            'notes' => $validated['notes'] ?? null,
            'created_by' => (string) $request->session()->get('admin_email', 'admin'),
        ]);

        return redirect()->route('admin.prompts')->with('success', 'নতুন prompt save হয়েছে। এখন থেকে chatbot এই active prompt-গুলো context হিসেবে ব্যবহার করবে।');
    }

    public function edit(PromptLibrary $prompt): View
    {
        return view('admin.prompts.edit', compact('prompt'));
    }

    public function update(Request $request, PromptLibrary $prompt): RedirectResponse
    {
        $validated = $this->validatePrompt($request, $prompt->id);
        $normalized = $this->normalizePrompt($validated['prompt_text']);

        $prompt->update([
            'title' => $validated['title'],
            'category' => $validated['category'] ?? 'general',
            'prompt_text' => $validated['prompt_text'],
            'normalized_prompt_text' => $normalized,
            'status' => $validated['status'] ?? 'active',
            'sort_order' => (int) ($validated['sort_order'] ?? 0),
            'notes' => $validated['notes'] ?? null,
        ]);

        return redirect()->route('admin.prompts')->with('success', 'Prompt update হয়েছে।');
    }

    public function destroy(PromptLibrary $prompt): RedirectResponse
    {
        $prompt->delete();
        return redirect()->route('admin.prompts')->with('success', 'Prompt delete হয়েছে।');
    }

    private function validatePrompt(Request $request, ?int $id = null): array
    {
        return $request->validate([
            'title' => ['required', 'string', 'max:180'],
            'category' => ['nullable', 'string', 'max:100'],
            'prompt_text' => ['required', 'string'],
            'status' => ['required', 'in:active,draft,archived'],
            'sort_order' => ['nullable', 'integer', 'min:0'],
            'notes' => ['nullable', 'string'],
        ]);
    }

    private function normalizePrompt(string $text): string
    {
        $replacements = [
            'Facebook marketing service business in Bangladesh' => 'digital marketing and course support brand in Bangladesh',
            'Facebook marketing service business' => 'digital marketing and course support brand',
            'Facebook marketing' => 'digital marketing',
            'facebook marketing' => 'digital marketing',
            'Meta' => 'Meta',
        ];

        $normalized = preg_replace('/\b(?:[A-Z][A-Za-z&.-]*(?:\s+[A-Z][A-Za-z&.-]*){0,4})\b/u', '$0', $text) ?? $text;

        foreach ($replacements as $find => $replace) {
            $normalized = str_ireplace($find, $replace, $normalized);
        }

        $companyPatterns = [
            '/\b(?:SEF\s*Solution|SEF\s*Solutions)\b/i',
            '/\b(?:[A-Z][A-Za-z0-9&.-]+(?:\s+[A-Z][A-Za-z0-9&.-]+){0,3})\b/u',
        ];

        $normalized = preg_replace($companyPatterns[0], 'SEF Solution', $normalized) ?? $normalized;
        $normalized = preg_replace_callback($companyPatterns[1], function ($matches) {
            $value = trim($matches[0]);
            $safeWords = ['Bangla','English','Meta','Pixel','PageView','ViewContent','AddToCart','Purchase','InitiateCheckout','Server-side','Client-side','GCP','GTM','GA4','Cloud','App','Engine','Google','Facebook','API','JSON','BDT','SEF','Solution'];
            foreach ($safeWords as $word) {
                if (stripos($value, $word) !== false) {
                    return $value;
                }
            }
            if (preg_match('/^[A-Z][A-Za-z0-9&.-]+(?:\s+[A-Z][A-Za-z0-9&.-]+){0,3}$/', $value) && !preg_match('/^(You|Goals|Language|Knowledge|Response|Chat|Important|Form|Phone|Brand|Course|Module|Server|Meta|Google|Facebook)$/', $value)) {
                return 'SEF Solution';
            }
            return $value;
        }, $normalized) ?? $normalized;

        return trim($normalized);
    }
}
