<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\HelpPage;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class HelpPageController extends Controller
{
    public function index()
    {
        $helpPages = HelpPage::ordered()->paginate(20);
        return view('admin.help-pages.index', compact('helpPages'));
    }

    public function create()
    {
        return view('admin.help-pages.create');
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'title' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:help_pages',
            'content' => 'nullable|string',
            'category' => 'nullable|string|max:100',
            'meta_title' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string',
            'is_active' => 'nullable|boolean',
            'order' => 'nullable|integer|min:0',
        ]);

        $data['slug'] = $data['slug'] ?? Str::slug($data['title']);
        $data['is_active'] = $request->boolean('is_active', true);

        HelpPage::create($data);
        return redirect()->route('admin.help-pages.index')->with('success', 'Help page created successfully.');
    }

    public function edit(HelpPage $helpPage)
    {
        return view('admin.help-pages.edit', compact('helpPage'));
    }

    public function update(Request $request, HelpPage $helpPage)
    {
        $data = $request->validate([
            'title' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:help_pages,slug,' . $helpPage->id,
            'content' => 'nullable|string',
            'category' => 'nullable|string|max:100',
            'meta_title' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string',
            'is_active' => 'nullable|boolean',
            'order' => 'nullable|integer|min:0',
        ]);

        $data['slug'] = $data['slug'] ?? Str::slug($data['title']);
        $data['is_active'] = $request->boolean('is_active', true);

        $helpPage->update($data);
        return redirect()->route('admin.help-pages.index')->with('success', 'Help page updated successfully.');
    }

    public function destroy(HelpPage $helpPage)
    {
        $helpPage->delete();
        return redirect()->route('admin.help-pages.index')->with('success', 'Help page deleted successfully.');
    }

    public function import(Request $request)
    {
        $opts = [
            'http' => ['method' => 'GET', 'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\r\n"],
            'ssl' => ['verify_peer' => false, 'verify_peer_name' => false],
        ];
        $ctx = stream_context_create($opts);
        
        try {
            $xml = file_get_contents('https://mecaprograms.com/sitemap.xml', false, $ctx);
            
            if (!$xml) {
                return redirect()->back()->with('error', 'Failed to fetch sitemap');
            }
            
            // Simple XML parsing to extract URLs
            $matches = [];
            preg_match_all('/<loc>(.*?)<\/loc>/', $xml, $matches);
            $urls = $matches[1] ?? [];
            
            $imported = 0;
            $skipped = 0;
            
            foreach ($urls as $url) {
                // Filter for help/support pages (you may want to adjust this filter)
                if (strpos($url, '/about/frequent-questions') !== false || 
                    strpos($url, '/about/how-to-buy') !== false ||
                    strpos($url, '/about/bills-and-invoices') !== false ||
                    strpos($url, '/about/terms-and-conditions') !== false ||
                    strpos($url, '/about/privacy-policy') !== false) {
                    
                    try {
                        $pageContent = file_get_contents($url, false, $ctx);
                        
                        if ($pageContent) {
                            // Extract title from HTML
                            $title = 'Untitled';
                            if (preg_match('/<title>(.*?)<\/title>/is', $pageContent, $titleMatches)) {
                                $title = trim($titleMatches[1]);
                                // Remove site name if present
                                $title = str_replace('- Mecaprograms', '', $title);
                                $title = str_replace('| Mecaprograms', '', $title);
                                $title = trim($title);
                            }
                            
                            // Extract main content (simplified)
                            $content = '';
                            if (preg_match('/<main[^>]*>(.*?)<\/main>/is', $pageContent, $contentMatches)) {
                                $content = strip_tags($contentMatches[1], '<p><br><ul><ol><li><h1><h2><h3><h4><h5><h6>');
                            } elseif (preg_match('/<article[^>]*>(.*?)<\/article>/is', $pageContent, $contentMatches)) {
                                $content = strip_tags($contentMatches[1], '<p><br><ul><ol><li><h1><h2><h3><h4><h5><h6>');
                            } elseif (preg_match('/<div[^>]*class=["\']content["\'][^>]*>(.*?)<\/div>/is', $pageContent, $contentMatches)) {
                                $content = strip_tags($contentMatches[1], '<p><br><ul><ol><li><h1><h2><h3><h4><h5><h6>');
                            } else {
                                // Fallback: get body content
                                if (preg_match('/<body[^>]*>(.*?)<\/body>/is', $pageContent, $bodyMatches)) {
                                    $content = strip_tags($bodyMatches[1], '<p><br><ul><ol><li><h1><h2><h3><h4><h5><h6>');
                                }
                            }
                            
                            // Clean up content
                            $content = trim(preg_replace('/\s+/', ' ', $content));
                            
                            if (!empty($title) && !empty($content)) {
                                // Check if page already exists
                                $existing = HelpPage::where('title', $title)->first();
                                if (!$existing) {
                                    HelpPage::create([
                                        'title' => $title,
                                        'slug' => Str::slug($title),
                                        'content' => $content,
                                        'category' => 'Imported from Mecaprograms',
                                        'is_active' => true,
                                        'order' => 0,
                                    ]);
                                    $imported++;
                                } else {
                                    $skipped++;
                                }
                            }
                        }
                    } catch (\Exception $e) {
                        // Skip problematic URLs
                        continue;
                    }
                }
            }
            
            $message = "Imported {$imported} help pages";
            if ($skipped > 0) {
                $message .= ", skipped {$skipped} duplicates";
            }
            
            return redirect()->route('admin.help-pages.index')->with('success', $message);
            
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Import failed: ' . $e->getMessage());
        }
    }
}
