<?php

namespace App\Http\Controllers;

use App\Models\SalesPage;
use App\Models\Product;
use App\Models\SalesPageAnalytics;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class SalesPageController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $user = auth()->user();

        $query = SalesPage::where('user_id', $user->id)
            ->orderBy('created_at', 'desc');

        $salesPages = $query->paginate(25);

        // Get user's current usage
        $currentUsage = $salesPages->total();
        $limit = $user->sales_page_limit;

        return view('sales-pages.index', compact('salesPages', 'currentUsage', 'limit'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $user = auth()->user();

        // Check if user has reached limit
        $currentCount = SalesPage::where('user_id', $user->id)->count();
        if ($currentCount >= $user->sales_page_limit) {
            return redirect()->route('sales-pages.index')
                ->with('error', "You have reached your sales page limit ({$user->sales_page_limit} pages). Contact admin to increase your limit.");
        }

        // Get user's products (own products + global admin products)
        $products = Product::accessibleByUser($user->id)->get();

        return view('sales-pages.create', compact('products'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $user = auth()->user();

        // Check limit again
        $currentCount = SalesPage::where('user_id', $user->id)->count();
        if ($currentCount >= $user->sales_page_limit) {
            return redirect()->route('sales-pages.index')
                ->with('error', "You have reached your sales page limit ({$user->sales_page_limit} pages).");
        }

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'meta_description' => 'nullable|string|max:160',
            'slug' => 'nullable|string|max:255|unique:sales_pages,slug',
            'html_content' => 'nullable|string',
            'thumbnail_path' => 'nullable|string|max:500',
            'legal_content' => 'nullable|string',
            'faq_items' => 'nullable|array',
            'faq_items.*.question' => 'nullable|string|max:500',
            'faq_items.*.answer' => 'nullable|string',
            'order_bump_enabled' => 'nullable|boolean',
            'order_bump_product_id' => 'nullable|exists:products,id',
            'order_bump_text' => 'nullable|string',
            'order_bump_bg_color' => 'nullable|string|max:7',
            'order_bump_text_color' => 'nullable|string|max:7',
            'order_bump_border_style' => 'nullable|string|in:solid,dashed,dotted',
            'order_bump_border_color' => 'nullable|string|max:7',
            'available_products' => 'nullable|array',
            'available_products.*' => 'exists:products,id',
            'logo' => 'nullable|image|max:2048',
            'show_logo' => 'nullable|boolean',
            'favicon' => 'nullable|image|max:1024',
            'use_logo_as_favicon' => 'nullable|boolean',
            'primary_color' => 'nullable|string|max:7',
            'facebook_pixel_id' => 'nullable|string|max:50',
            'google_analytics_id' => 'nullable|string|max:50',
            'tiktok_pixel_id' => 'nullable|string|max:50',
        ]);

        $validated['user_id'] = $user->id;

        // Handle logo upload
        if ($request->hasFile('logo')) {
            $logoDir = public_path('images/sales-pages/logos');
            if (!file_exists($logoDir)) {
                mkdir($logoDir, 0755, true);
            }

            $file = $request->file('logo');
            $filename = time() . '_' . uniqid() . '.' . $file->getClientOriginalExtension();
            $file->move($logoDir, $filename);
            $validated['logo_path'] = 'images/sales-pages/logos/' . $filename;
        }

        // Handle favicon upload
        if ($request->hasFile('favicon')) {
            $faviconDir = public_path('images/sales-pages/favicons');
            if (!file_exists($faviconDir)) {
                mkdir($faviconDir, 0755, true);
            }

            $file = $request->file('favicon');
            $filename = time() . '_' . uniqid() . '.' . $file->getClientOriginalExtension();
            $file->move($faviconDir, $filename);
            $validated['favicon_path'] = 'images/sales-pages/favicons/' . $filename;
        }

        $salesPage = SalesPage::create($validated);

        return redirect()->route('sales-pages.edit', $salesPage)
            ->with('success', 'Sales page created successfully!');
    }

    /**
     * Display the specified resource (analytics view).
     */
    public function show(SalesPage $salesPage)
    {
        // Check ownership
        if ($salesPage->user_id !== auth()->id()) {
            abort(403);
        }

        // Get date range from request (default: last 30 days)
        $startDate = request('start_date', now()->subDays(30)->format('Y-m-d'));
        $endDate = request('end_date', now()->format('Y-m-d'));

        // Basic stats
        $totalViews = $salesPage->total_views;
        $totalOrders = $salesPage->total_orders;
        $conversionRate = $salesPage->getConversionRate();

        // Analytics in date range
        $analyticsQuery = $salesPage->analytics()
            ->whereBetween('created_at', [$startDate . ' 00:00:00', $endDate . ' 23:59:59']);

        $viewsInRange = (clone $analyticsQuery)->where('event_type', 'view')->count();
        $ordersInRange = (clone $analyticsQuery)->where('event_type', 'order')->count();

        // Traffic sources
        $trafficSources = (clone $analyticsQuery)
            ->where('event_type', 'view')
            ->selectRaw('
                COALESCE(utm_source, "Direct") as source,
                COUNT(*) as count
            ')
            ->groupBy('source')
            ->orderByDesc('count')
            ->limit(10)
            ->get();

        // Device breakdown
        $deviceBreakdown = (clone $analyticsQuery)
            ->where('event_type', 'view')
            ->selectRaw('
                COALESCE(device_type, "Unknown") as device,
                COUNT(*) as count
            ')
            ->groupBy('device')
            ->get();

        // Top UTM campaigns
        $topCampaigns = (clone $analyticsQuery)
            ->where('event_type', 'view')
            ->whereNotNull('utm_campaign')
            ->selectRaw('
                utm_campaign,
                COUNT(*) as views,
                SUM(CASE WHEN event_type = "order" THEN 1 ELSE 0 END) as orders
            ')
            ->groupBy('utm_campaign')
            ->orderByDesc('views')
            ->limit(10)
            ->get();

        return view('sales-pages.analytics', compact(
            'salesPage',
            'totalViews',
            'totalOrders',
            'conversionRate',
            'viewsInRange',
            'ordersInRange',
            'trafficSources',
            'deviceBreakdown',
            'topCampaigns',
            'startDate',
            'endDate'
        ));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(SalesPage $salesPage)
    {
        // Check ownership
        if ($salesPage->user_id !== auth()->id()) {
            abort(403);
        }

        $user = auth()->user();
        $products = Product::accessibleByUser($user->id)->get();

        return view('sales-pages.edit', compact('salesPage', 'products'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, SalesPage $salesPage)
    {
        // Check ownership
        if ($salesPage->user_id !== auth()->id()) {
            abort(403);
        }

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'meta_description' => 'nullable|string|max:160',
            'slug' => 'nullable|string|max:255|unique:sales_pages,slug,' . $salesPage->id,
            'html_content' => 'nullable|string',
            'thumbnail_path' => 'nullable|string|max:500',
            'legal_content' => 'nullable|string',
            'faq_items' => 'nullable|array',
            'faq_items.*.question' => 'nullable|string|max:500',
            'faq_items.*.answer' => 'nullable|string',
            'order_bump_enabled' => 'nullable|boolean',
            'order_bump_product_id' => 'nullable|exists:products,id',
            'order_bump_text' => 'nullable|string',
            'order_bump_bg_color' => 'nullable|string|max:7',
            'order_bump_text_color' => 'nullable|string|max:7',
            'order_bump_border_style' => 'nullable|string|in:solid,dashed,dotted',
            'order_bump_border_color' => 'nullable|string|max:7',
            'available_products' => 'nullable|array',
            'available_products.*' => 'exists:products,id',
            'logo' => 'nullable|image|max:2048',
            'show_logo' => 'nullable|boolean',
            'favicon' => 'nullable|image|max:1024',
            'use_logo_as_favicon' => 'nullable|boolean',
            'primary_color' => 'nullable|string|max:7',
            'facebook_pixel_id' => 'nullable|string|max:50',
            'google_analytics_id' => 'nullable|string|max:50',
            'tiktok_pixel_id' => 'nullable|string|max:50',
            'is_active' => 'nullable|boolean',
        ]);

        // Handle logo upload
        if ($request->hasFile('logo')) {
            // Delete old logo
            if ($salesPage->logo_path && file_exists(public_path($salesPage->logo_path))) {
                unlink(public_path($salesPage->logo_path));
            }

            $logoDir = public_path('images/sales-pages/logos');
            if (!file_exists($logoDir)) {
                mkdir($logoDir, 0755, true);
            }

            $file = $request->file('logo');
            $filename = time() . '_' . uniqid() . '.' . $file->getClientOriginalExtension();
            $file->move($logoDir, $filename);
            $validated['logo_path'] = 'images/sales-pages/logos/' . $filename;
        }

        // Handle favicon upload
        if ($request->hasFile('favicon')) {
            // Delete old favicon
            if ($salesPage->favicon_path && file_exists(public_path($salesPage->favicon_path))) {
                unlink(public_path($salesPage->favicon_path));
            }

            $faviconDir = public_path('images/sales-pages/favicons');
            if (!file_exists($faviconDir)) {
                mkdir($faviconDir, 0755, true);
            }

            $file = $request->file('favicon');
            $filename = time() . '_' . uniqid() . '.' . $file->getClientOriginalExtension();
            $file->move($faviconDir, $filename);
            $validated['favicon_path'] = 'images/sales-pages/favicons/' . $filename;
        }

        $salesPage->update($validated);

        return redirect()->route('sales-pages.edit', $salesPage)
            ->with('success', 'Sales page updated successfully!');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(SalesPage $salesPage)
    {
        // Check ownership
        if ($salesPage->user_id !== auth()->id()) {
            abort(403);
        }

        // Delete logo if exists
        if ($salesPage->logo_path && file_exists(public_path($salesPage->logo_path))) {
            unlink(public_path($salesPage->logo_path));
        }

        // Delete favicon if exists
        if ($salesPage->favicon_path && file_exists(public_path($salesPage->favicon_path))) {
            unlink(public_path($salesPage->favicon_path));
        }

        $salesPage->delete();

        return redirect()->route('sales-pages.index')
            ->with('success', 'Sales page deleted successfully!');
    }

    /**
     * Duplicate a sales page
     */
    public function duplicate(SalesPage $salesPage)
    {
        // Check ownership
        if ($salesPage->user_id !== auth()->id()) {
            abort(403);
        }

        $user = auth()->user();

        // Check limit
        $currentCount = SalesPage::where('user_id', $user->id)->count();
        if ($currentCount >= $user->sales_page_limit) {
            return redirect()->route('sales-pages.index')
                ->with('error', "You have reached your sales page limit ({$user->sales_page_limit} pages).");
        }

        $newPage = $salesPage->replicate();
        $newPage->name = $salesPage->name . ' (Copy)';
        $newPage->slug = null; // Will be auto-generated
        $newPage->total_views = 0;
        $newPage->total_orders = 0;
        $newPage->save();

        return redirect()->route('sales-pages.edit', $newPage)
            ->with('success', 'Sales page duplicated successfully!');
    }

}
