<?php

namespace Modules\LandingPage\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Modules\LandingPage\Entities\LpPage;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\View;

class LpPageController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return \Illuminate\Contracts\View\View
     */
    public function index(Request $request)
    {
        $query = LpPage::orderBy('sort_order', 'asc')->orderBy('title', 'asc');

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

        $pages = $query->paginate(15)->withQueryString();
        return view('landingpage::admin.pages.index', compact('pages'));
    }

    /**
     * Show the form for creating a new resource.
     * @return \Illuminate\Contracts\View\View
     */
    public function create()
    {
        $page = new LpPage(); // For form model binding
        $themeTemplates = $this->getAvailablePageTemplates();
        return view('landingpage::admin.pages.create', compact('page', 'themeTemplates'));
    }

    /**
     * Store a newly created resource in storage.
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:lp_pages,slug',
            'content' => 'nullable|string',
            'meta_title' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string|max:500',
            'meta_keywords' => 'nullable|string|max:255',
            'theme_template' => 'nullable|string|max:255',
            'is_published' => 'boolean',
            'sort_order' => 'nullable|integer',
        ]);

        $data = $request->all();
        $data['slug'] = $request->input('slug') ?: Str::slug($request->input('title'));
        $data['is_published'] = $request->has('is_published');
        $data['sort_order'] = $request->input('sort_order', 0);

        // Ensure slug uniqueness
        $originalSlug = $data['slug'];
        $count = 1;
        while (LpPage::where('slug', $data['slug'])->exists()) {
            $data['slug'] = $originalSlug . '-' . $count++;
        }

        LpPage::create($data);

        return redirect()->route('admin.landingpage.pages.index')
                         ->with('success', 'Page created successfully.');
    }

    /**
     * Display the specified resource.
     * @param LpPage $page
     * @return \Illuminate\Contracts\View\View
     */
    public function show(LpPage $page)
    {
        // For admin, 'edit' is usually more practical than 'show' for a page.
        // Redirecting to edit or providing a simple view.
        return view('landingpage::admin.pages.show', compact('page'));
    }

    /**
     * Show the form for editing the specified resource.
     * @param LpPage $page
     * @return \Illuminate\Contracts\View\View
     */
    public function edit(LpPage $page)
    {
        $themeTemplates = $this->getAvailablePageTemplates();
        return view('landingpage::admin.pages.edit', compact('page', 'themeTemplates'));
    }

    /**
     * Update the specified resource in storage.
     * @param Request $request
     * @param LpPage $page
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request, LpPage $page)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:lp_pages,slug,' . $page->id,
            'content' => 'nullable|string',
            'meta_title' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string|max:500',
            'meta_keywords' => 'nullable|string|max:255',
            'theme_template' => 'nullable|string|max:255',
            'is_published' => 'boolean',
            'sort_order' => 'nullable|integer',
        ]);

        $data = $request->all();
        $data['slug'] = $request->input('slug') ?: Str::slug($request->input('title'));
        $data['is_published'] = $request->has('is_published');
        $data['sort_order'] = $request->input('sort_order', $page->sort_order);

        // Ensure slug uniqueness if changed
        if ($page->slug !== $data['slug']) {
            $originalSlug = $data['slug'];
            $count = 1;
            while (LpPage::where('slug', $data['slug'])->where('id', '!=', $page->id)->exists()) {
                $data['slug'] = $originalSlug . '-' . $count++;
            }
        }

        $page->update($data);

        return redirect()->route('admin.landingpage.pages.index')
                         ->with('success', 'Page updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     * @param LpPage $page
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy(LpPage $page)
    {
        // Prevent deletion of 'home' page if it's critical
        if ($page->slug === setting('landingpage_homepage_slug', 'home')) {
            return redirect()->route('admin.landingpage.pages.index')
                             ->with('error', 'The homepage cannot be deleted.');
        }

        $page->delete();
        return redirect()->route('admin.landingpage.pages.index')
                         ->with('success', 'Page deleted successfully.');
    }

    /**
     * Get available page templates from the active theme.
     * @return array
     */
    protected function getAvailablePageTemplates(): array
    {
        $templates = ['' => 'Default Page Template']; // Default option
        $activeTheme = setting('landingpage_active_theme', 'general');
        $themeTemplatesPath = module_path('LandingPage', "Resources/views/themes/{$activeTheme}/templates");

        if (File::isDirectory($themeTemplatesPath)) {
            $files = File::files($themeTemplatesPath);
            foreach ($files as $file) {
                if ($file->getExtension() === 'php') { // blade.php files
                    $templateName = $file->getFilenameWithoutExtension();
                    // Check if it's a Blade file by looking for .blade.php
                    if (Str::endsWith($templateName, '.blade')) {
                        $templateName = Str::before($templateName, '.blade');
                    }
                    $templates[$templateName] = Str::title(str_replace(['_', '-'], ' ', $templateName));
                }
            }
        }
        return $templates;
    }
}
