<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\LandingPage;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Auth;

class LandingPageController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $query = LandingPage::query();

        // Căutare
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('title', 'like', "%{$search}%")
                  ->orWhere('slug', 'like', "%{$search}%");
            });
        }

        // Filtru status
        if ($request->filled('status')) {
            if ($request->status === 'published') {
                $query->where('is_published', true);
            } elseif ($request->status === 'draft') {
                $query->where('is_published', false);
            }
        }

        // Filtru template
        if ($request->filled('template')) {
            $query->where('template', $request->template);
        }

        $pages = $query->orderBy('created_at', 'desc')->paginate(15);

        return view('admin.landing-pages.index', [
            'pages' => $pages,
            'templates' => LandingPage::getTemplates(),
        ]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('admin.landing-pages.create', [
            'templates' => LandingPage::getTemplates(),
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:landing_pages,slug',
            'content' => 'nullable|string',
            'template' => 'required|string|in:' . implode(',', array_keys(LandingPage::getTemplates())),
            'meta_title' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string|max:500',
            'meta_keywords' => 'nullable|string|max:255',
            'featured_image' => 'nullable|string|max:255',
            'is_published' => 'boolean',
        ]);

        // Generează slug dacă nu e furnizat
        if (empty($validated['slug'])) {
            $validated['slug'] = LandingPage::generateUniqueSlug($validated['title']);
        }

        $validated['created_by'] = Auth::id();
        $validated['is_published'] = $request->boolean('is_published');

        if ($validated['is_published']) {
            $validated['published_at'] = now();
        }

        $page = LandingPage::create($validated);

        return redirect()
            ->route('admin.landing-pages.index')
            ->with('success', 'Pagina "' . $page->title . '" a fost creată cu succes!');
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(LandingPage $landingPage)
    {
        return view('admin.landing-pages.edit', [
            'page' => $landingPage,
            'templates' => LandingPage::getTemplates(),
        ]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, LandingPage $landingPage)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:landing_pages,slug,' . $landingPage->id,
            'content' => 'nullable|string',
            'template' => 'required|string|in:' . implode(',', array_keys(LandingPage::getTemplates())),
            'meta_title' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string|max:500',
            'meta_keywords' => 'nullable|string|max:255',
            'featured_image' => 'nullable|string|max:255',
            'is_published' => 'boolean',
        ]);

        // Regenerează slug dacă e gol
        if (empty($validated['slug'])) {
            $validated['slug'] = LandingPage::generateUniqueSlug($validated['title'], $landingPage->id);
        }

        $validated['updated_by'] = Auth::id();
        $validated['is_published'] = $request->boolean('is_published');

        // Setează published_at dacă e prima publicare
        if ($validated['is_published'] && !$landingPage->is_published) {
            $validated['published_at'] = now();
        }

        $landingPage->update($validated);

        return redirect()
            ->route('admin.landing-pages.index')
            ->with('success', 'Pagina "' . $landingPage->title . '" a fost actualizată!');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(LandingPage $landingPage)
    {
        $title = $landingPage->title;

        // Verifică dacă pagina e folosită în meniu
        if ($landingPage->menus()->count() > 0) {
            return redirect()
                ->route('admin.landing-pages.index')
                ->with('error', 'Pagina "' . $title . '" este folosită în meniu și nu poate fi ștearsă!');
        }

        $landingPage->delete();

        return redirect()
            ->route('admin.landing-pages.index')
            ->with('success', 'Pagina "' . $title . '" a fost ștearsă!');
    }

    /**
     * Generează slug din titlu (AJAX)
     */
    public function generateSlug(Request $request)
    {
        $title = $request->input('title', '');
        $excludeId = $request->input('exclude_id');

        $slug = LandingPage::generateUniqueSlug($title, $excludeId);

        return response()->json(['slug' => $slug]);
    }

    /**
     * Toggle publish status
     */
    public function togglePublish(LandingPage $landingPage)
    {
        $landingPage->is_published = !$landingPage->is_published;

        if ($landingPage->is_published && !$landingPage->published_at) {
            $landingPage->published_at = now();
        }

        $landingPage->save();

        $status = $landingPage->is_published ? 'publicată' : 'dezactivată';

        return redirect()
            ->back()
            ->with('success', 'Pagina "' . $landingPage->title . '" a fost ' . $status . '!');
    }

    /**
     * Duplicate a page
     */
    public function duplicate(LandingPage $landingPage)
    {
        $newPage = $landingPage->replicate();
        $newPage->title = $landingPage->title . ' (Copie)';
        $newPage->slug = LandingPage::generateUniqueSlug($newPage->title);
        $newPage->is_published = false;
        $newPage->published_at = null;
        $newPage->created_by = Auth::id();
        $newPage->save();

        return redirect()
            ->route('admin.landing-pages.edit', $newPage)
            ->with('success', 'Pagina a fost duplicată! Editează noua copie.');
    }
}
