<?php

namespace Modules\LandingPage\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Modules\LandingPage\Entities\LpPage;
use Modules\LandingPage\Entities\LpPageSection;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\View;
use Modules\LandingPage\Http\Controllers\Admin\PageSectionController; // Added this line
use Modules\LandingPage\Services\GoogleAnalyticsService;

class LpPageController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return \Illuminate\Contracts\View\View
     */
    public function index(Request $request, GoogleAnalyticsService $gaService)
    {
        $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}%");
            });
        }

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

        $pages = $query->paginate(15)->withQueryString();

        // Prepare stats for the dashboard view
        $stats = [
            'total_pages'     => LpPage::count(),
            'published_pages' => LpPage::where('is_published', true)->count(),
            'draft_pages'     => LpPage::where('is_published', false)->count(),
        ];

        // Fetch recent pages for the dashboard view
        $recentPages = LpPage::orderBy('updated_at', 'desc')->take(5)->get();

        // Fetch Google Analytics data
        $gaStats = $gaService->getBasicStats('7daysAgo', 'today');
        $gaTopPages = $gaService->getTopPages('7daysAgo', 'today', 5);

        // If this 'index' method serves as both the listing and the dashboard,
        // pass all necessary data.
        return view('landingpage::admin.pages.index', compact('pages', 'stats', 'recentPages', 'gaStats', 'gaTopPages'));
    }

    /**
     * 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',
            // Add validation for hero fields if they are direct columns on lp_pages
            // These are now less relevant if the hero section is managed via LpPageSection
            // but can serve as fallbacks or for pages without dynamic sections.
            'hero_title' => 'nullable|string|max:255',
            'hero_subtitle' => 'nullable|string',
            'hero_cta_text' => 'nullable|string|max:100',
            'hero_cta_link' => 'nullable|string|max:255',

            // Sections validation will be handled in the update method more directly
        ]);

        $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++;
        }

        $page = 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();
        $page->load('sections'); // Eager load sections

        $pageSectionCtrl = new PageSectionController();
        // Define section types directly in LpPageController to ensure all admin fields are covered
        $sectionTypes = [
            'hero' => 'Hero Section',
            'custom_html' => 'Custom HTML',
            'featured-projects' => 'Featured Projects (General Portfolio)',
            'services' => 'Services Overview',
            'testimonials' => 'Testimonials',
            'team' => 'Team Members',
            'contact' => 'Contact CTA',
            'job-listings' => 'Job Listings (BD)',
            'featured-products' => 'Featured Products (BD)',
            'latest-tenders' => 'Latest Tenders (BD)',
            'featured-companies' => 'Featured Companies (BD)',
            'company-projects' => 'Company Projects (BD)', // From edit.blade.php group
            'portfolio-projects' => 'Portfolio Projects (General)', // From edit.blade.php group
            'support-cta' => 'Support CTA',
            'search_form' => 'Search Form',
            'news_listing' => 'News Listing',
            // AI Theme Specific
            'how_it_works_ai' => 'How It Works (AI Theme)',
            'features_ai' => 'Features Showcase (AI Theme)',
            'pricing_plans_ai' => 'Pricing Plans (AI Theme)',
            'faq_ai' => 'FAQ (AI Theme)',
            // Add other specific types if needed by edit.blade.php
            // 'our_portfolio' => 'Our Portfolio (DigitalVocano)', // Example if you have this type
        ];

        // Fetch pages that could be projects (e.g., all published, non-core pages, or based on a specific template/type)
        // Consider adding a filter here if projects have a specific 'page_type' or 'theme_template'
        $availableProjects = LpPage::where('is_published', true)
                                // ->where('page_type', 'project') // Example: Filter by a 'project' page_type
                                ->orderBy('title')->pluck('title', 'slug')->all();

        // Fetch available layouts for sections
        $availableLayouts = $pageSectionCtrl->getAvailableLayouts();

        return view('landingpage::admin.pages.edit', compact('page', 'themeTemplates', 'sectionTypes', 'availableProjects', 'availableLayouts'));
    }

    /**
     * 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',
            // Hero fields (optional fallbacks)
            'hero_title' => 'nullable|string|max:255',
            'hero_subtitle' => 'nullable|string',
            'hero_cta_text' => 'nullable|string|max:100',
            'hero_cta_link' => 'nullable|string|max:255',
            'sections' => 'nullable|array', // Expecting an array of sections
        ]);

        $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);

        // Handle Sections
        $existingSectionIds = $page->sections->pluck('id')->toArray();
        $submittedSectionIds = [];
        $currentSortOrder = 0;

        if ($request->has('sections')) {
            foreach ($request->input('sections', []) as $sectionKey => $sectionData) {
                // Basic validation for required fields like type
                if (empty($sectionData['type'])) {
                    // Optionally, add a validation error or log this
                    continue;
                }

                $content = $sectionData['content'] ?? [];
                // Ensure content is always an array
                if (!is_array($content)) {
                    $content = [];
                }

                // Handle image uploads specifically for 'services' section type
                if ($sectionData['type'] === 'services' && isset($content['services_list']) && is_array($content['services_list'])) {
                    $processedServicesList = [];
                    foreach ($content['services_list'] as $serviceItemKey => $serviceItemData) {
                        $imageFileRequestPath = "sections.{$sectionKey}.content.services_list.{$serviceItemKey}.image_file";
                        $existingImageUrlRequestPath = "sections.{$sectionKey}.content.services_list.{$serviceItemKey}.existing_image_url";
                        $removeImageRequestPath = "sections.{$sectionKey}.content.services_list.{$serviceItemKey}.remove_image";

                        $currentImageUrl = $request->input($existingImageUrlRequestPath, $serviceItemData['image_url'] ?? null);

                        // Handle image removal
                        if ($request->input($removeImageRequestPath) == '1' && $currentImageUrl) {
                            Storage::disk('public')->delete($currentImageUrl);
                            $currentImageUrl = null;
                        }

                        // Handle new image upload
                        if ($request->hasFile($imageFileRequestPath)) {
                            // Delete old image if a new one is uploaded
                            if ($currentImageUrl) {
                                Storage::disk('public')->delete($currentImageUrl);
                            }
                            $file = $request->file($imageFileRequestPath);
                            // Validate the file (optional, but recommended)
                            // $request->validate(["{$imageFileRequestPath}" => 'image|mimes:jpeg,png,jpg,gif,svg,webp|max:2048']);
                            $path = $file->store('landingpage/services_images', 'public');
                            $currentImageUrl = $path;
                        }

                        $serviceItemData['image_url'] = $currentImageUrl;

                        // Remove temporary/helper fields from being saved in JSON
                        unset($serviceItemData['image_file']);
                        unset($serviceItemData['existing_image_url']);
                        unset($serviceItemData['remove_image']);

                        $processedServicesList[$serviceItemKey] = $serviceItemData;
                    }
                    $content['services_list'] = $processedServicesList;
                }

                // Handle image uploads for 'hero' section slides
                if ($sectionData['type'] === 'hero' && isset($content['slides']) && is_array($content['slides'])) {
                    $processedSlides = [];
                    foreach ($content['slides'] as $slideKey => $slideData) {
                        $imageFileRequestPath = "sections.{$sectionKey}.content.slides.{$slideKey}.image_file";
                        $existingImageUrlRequestPath = "sections.{$sectionKey}.content.slides.{$slideKey}.existing_image_url";
                        $removeImageRequestPath = "sections.{$sectionKey}.content.slides.{$slideKey}.remove_image";

                        $currentImageUrl = $request->input($existingImageUrlRequestPath, $slideData['image_url'] ?? null);

                        if ($request->input($removeImageRequestPath) == '1' && $currentImageUrl) {
                            Storage::disk('public')->delete($currentImageUrl);
                            $currentImageUrl = null;
                        }

                        if ($request->hasFile($imageFileRequestPath)) {
                            if ($currentImageUrl) Storage::disk('public')->delete($currentImageUrl);
                            $file = $request->file($imageFileRequestPath);
                            $path = $file->store('landingpage/hero_slides_images', 'public');
                            $currentImageUrl = $path;
                        }
                        $slideData['image_url'] = $currentImageUrl;
                        unset($slideData['image_file'], $slideData['existing_image_url'], $slideData['remove_image']);
                        $processedSlides[$slideKey] = $slideData;
                    }
                    $content['slides'] = $processedSlides;
                }

                // Handle image uploads for 'team' section members
                if ($sectionData['type'] === 'team' && isset($content['team_members']) && is_array($content['team_members'])) {
                    $processedMembers = [];
                    foreach ($content['team_members'] as $memberKey => $memberData) {
                        $imageFileRequestPath = "sections.{$sectionKey}.content.team_members.{$memberKey}.image_file";
                        $existingImageUrlRequestPath = "sections.{$sectionKey}.content.team_members.{$memberKey}.existing_image_url";
                        $removeImageRequestPath = "sections.{$sectionKey}.content.team_members.{$memberKey}.remove_image";

                        $currentImageUrl = $request->input($existingImageUrlRequestPath, $memberData['image_url'] ?? null);

                        if ($request->input($removeImageRequestPath) == '1' && $currentImageUrl) {
                            Storage::disk('public')->delete($currentImageUrl);
                            $currentImageUrl = null;
                        }

                        if ($request->hasFile($imageFileRequestPath)) {
                            if ($currentImageUrl) Storage::disk('public')->delete($currentImageUrl);
                            $file = $request->file($imageFileRequestPath);
                            $path = $file->store('landingpage/team_images', 'public');
                            $currentImageUrl = $path;
                        }
                        $memberData['image_url'] = $currentImageUrl;
                        unset($memberData['image_file'], $memberData['existing_image_url'], $memberData['remove_image']);
                        $processedMembers[$memberKey] = $memberData;
                    }
                    $content['team_members'] = $processedMembers;
                }

                // Handle 'pricing_plans_ai' section features (textarea to array)
                if ($sectionData['type'] === 'pricing_plans_ai' && isset($content['plans']) && is_array($content['plans'])) {
                    $processedPlans = [];
                    foreach ($content['plans'] as $planKey => $planData) {
                        if (isset($planData['features_textarea'])) {
                            // Split textarea content by newline, trim whitespace, and filter out empty lines
                            $planData['features'] = array_filter(array_map('trim', explode("\n", $planData['features_textarea'])));
                            unset($planData['features_textarea']); // Remove the textarea field from being saved
                        } else {
                            $planData['features'] = $planData['features'] ?? []; // Ensure features key exists
                        }
                        $planData['highlighted'] = isset($planData['highlighted']) && $planData['highlighted'] == '1'; // Convert checkbox value
                        $processedPlans[$planKey] = $planData;
                    }
                    $content['plans'] = $processedPlans;
                }

                // Handle image uploads for 'testimonials' section author images
                if ($sectionData['type'] === 'testimonials' && isset($content['testimonials_list']) && is_array($content['testimonials_list'])) {
                    $processedTestimonials = [];
                    foreach ($content['testimonials_list'] as $testimonialKey => $testimonialData) {
                        $imageFileRequestPath = "sections.{$sectionKey}.content.testimonials_list.{$testimonialKey}.author_image_file";
                        $existingImageUrlRequestPath = "sections.{$sectionKey}.content.testimonials_list.{$testimonialKey}.existing_author_image_url";
                        $removeImageRequestPath = "sections.{$sectionKey}.content.testimonials_list.{$testimonialKey}.remove_author_image";

                        $currentImageUrl = $request->input($existingImageUrlRequestPath, $testimonialData['author_image_url'] ?? null);

                        if ($request->input($removeImageRequestPath) == '1' && $currentImageUrl) {
                            Storage::disk('public')->delete($currentImageUrl);
                            $currentImageUrl = null;
                        }

                        if ($request->hasFile($imageFileRequestPath)) {
                            if ($currentImageUrl) Storage::disk('public')->delete($currentImageUrl);
                            $file = $request->file($imageFileRequestPath);
                            $path = $file->store('landingpage/testimonial_author_images', 'public');
                            $currentImageUrl = $path;
                        }
                        $testimonialData['author_image_url'] = $currentImageUrl;
                        unset($testimonialData['author_image_file'], $testimonialData['existing_author_image_url'], $testimonialData['remove_author_image']);
                        $processedTestimonials[$testimonialKey] = $testimonialData;
                    }
                    $content['testimonials_list'] = $processedTestimonials;
                }

                // Basic HTML sanitization for custom-html (consider a more robust library like HTMLPurifier)
                // if ($sectionData['type'] === 'custom-html' && isset($content['html'])) {
                //     // $content['html'] = strip_tags($content['html'], '<p><a><img><h1><h2><h3><h4><h5><h6><ul><ol><li><br><strong><em><blockquote><code><pre><iframe><div><span>');
                // }

                $sectionPayload = [
                    'lp_page_id' => $page->id,
                    'type' => $sectionData['type'],
                    'title' => $sectionData['title'] ?? null,
                    'content' => $content, // LpPageSection model should cast this to JSON
                    'sort_order' => $currentSortOrder, // Assign the correct integer sort order
                ];

                $sectionIdFromRequest = $sectionData['id'] ?? null;

                if ($sectionIdFromRequest && !empty($sectionIdFromRequest) && !Str::startsWith($sectionIdFromRequest, 'new_')) {
                    // Existing section: update it
                    $section = LpPageSection::find($sectionIdFromRequest);
                    if ($section && $section->lp_page_id == $page->id) { // Ensure it belongs to the current page
                        $section->update($sectionPayload);
                        $submittedSectionIds[] = $section->id;
                    }
                } else {
                    // New section: create it
                    $newSection = LpPageSection::create($sectionPayload);
                    $submittedSectionIds[] = $newSection->id;
                }
                $currentSortOrder++;
            }
        }

        // Delete sections that were removed
        $sectionsToDelete = array_diff($existingSectionIds, $submittedSectionIds);
        if (!empty($sectionsToDelete)) {
            LpPageSection::whereIn('id', $sectionsToDelete)->where('lp_page_id', $page->id)->delete();
        }

        return redirect()->route('admin.landingpage.pages.edit', $page->id)
                         ->with('success', 'Page and sections 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(); // e.g., 'my-template.blade'
                    // Remove .blade part to get the clean template name
                    if (Str::endsWith($templateName, '.blade')) {
                        $templateName = Str::before($templateName, '.blade');
                    }
                    $templates[$templateName] = Str::title(str_replace(['_', '-'], ' ', $templateName));
                }
            }
        }
        return $templates;
    }
}
