<?php

namespace App\Http\Controllers;

use App\Models\SellerDomain;
use App\Models\SalesPage;
use App\Models\SystemSetting;
use App\Services\CloudflareService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class SellerDomainController extends Controller
{
    /**
     * Display a listing of the seller's custom domains.
     */
    public function index()
    {
        $user = auth()->user();

        $domains = SellerDomain::where('user_id', $user->id)
            ->with('defaultSalesPage')
            ->orderBy('is_primary', 'desc')
            ->orderBy('created_at', 'desc')
            ->get();

        return view('seller-domains.index', compact('domains'));
    }

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

        // Get seller's sales pages for default page selection
        $salesPages = SalesPage::where('user_id', $user->id)
            ->orderBy('name')
            ->get();

        return view('seller-domains.create', compact('salesPages'));
    }

    /**
     * Store a newly created domain in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'domain' => 'required|string|max:255|unique:seller_domains,domain',
            'default_sales_page_id' => 'nullable|exists:sales_pages,id',
            'is_primary' => 'boolean',
        ]);

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

        // If setting as primary, unset other primary domains
        if ($request->is_primary) {
            SellerDomain::where('user_id', $user->id)
                ->update(['is_primary' => false]);
        }

        // Clean domain name (remove http://, https://, trailing slashes)
        $domain = $this->cleanDomainName($request->domain);

        // Check if domain already exists
        if (SellerDomain::where('domain', $domain)->exists()) {
            return back()->withErrors(['domain' => 'This domain is already registered in the system.'])->withInput();
        }

        $sellerDomain = SellerDomain::create([
            'user_id' => $user->id,
            'domain' => $domain,
            'is_primary' => $request->is_primary ?? false,
            'default_sales_page_id' => $request->default_sales_page_id,
            'is_active' => false, // Not active until verified
        ]);

        // Attempt automatic DNS creation if enabled
        $message = 'Custom domain added successfully!';
        if (SystemSetting::isAutoDnsEnabled() && SystemSetting::isCloudflareEnabled()) {
            $serverIp = SystemSetting::getServerIp();

            if ($serverIp) {
                $cloudflare = new CloudflareService();
                $result = $cloudflare->createDnsRecord($domain, $serverIp, true);

                if ($result['success']) {
                    // Store Cloudflare record IDs
                    $recordIds = json_encode([
                        'root' => $result['root_record_id'] ?? null,
                        'www' => $result['www_record_id'] ?? null,
                    ]);
                    $sellerDomain->update(['cloudflare_record_id' => $recordIds]);

                    $message .= ' DNS records created automatically in Cloudflare.';

                    // Attempt automatic verification if enabled
                    if (SystemSetting::isAutoVerificationEnabled()) {
                        sleep(2); // Wait a moment for DNS to start propagating
                        $verifyResult = $cloudflare->verifyDnsPropagation($domain, $serverIp);

                        if ($verifyResult['verified']) {
                            $sellerDomain->markAsVerified();
                            $message .= ' Domain verified automatically!';
                        } else {
                            $message .= ' Please wait for DNS propagation and verify manually.';
                        }
                    }
                } else {
                    Log::warning('Automatic DNS creation failed for domain: ' . $domain, ['error' => $result['message']]);
                    $message .= ' However, automatic DNS creation failed: ' . $result['message'] . '. Please configure DNS manually.';
                }
            } else {
                $message .= ' Please configure server IP in Cloudflare settings for automatic DNS creation.';
            }
        } else {
            $message .= ' Please follow the verification steps.';
        }

        return redirect()->route('seller-domains.show', $sellerDomain)
            ->with('success', $message);
    }

    /**
     * Display the specified domain with verification instructions.
     */
    public function show(SellerDomain $sellerDomain)
    {
        // Check ownership
        if ($sellerDomain->user_id !== auth()->id()) {
            abort(403, 'Unauthorized access to this domain.');
        }

        $sellerDomain->load('defaultSalesPage');

        return view('seller-domains.show', compact('sellerDomain'));
    }

    /**
     * Show the form for editing the specified domain.
     */
    public function edit(SellerDomain $sellerDomain)
    {
        // Check ownership
        if ($sellerDomain->user_id !== auth()->id()) {
            abort(403, 'Unauthorized access to this domain.');
        }

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

        $salesPages = SalesPage::where('user_id', $user->id)
            ->orderBy('name')
            ->get();

        return view('seller-domains.edit', compact('sellerDomain', 'salesPages'));
    }

    /**
     * Update the specified domain in storage.
     */
    public function update(Request $request, SellerDomain $sellerDomain)
    {
        // Check ownership
        if ($sellerDomain->user_id !== auth()->id()) {
            abort(403, 'Unauthorized access to this domain.');
        }

        $request->validate([
            'domain' => 'required|string|max:255|unique:seller_domains,domain,' . $sellerDomain->id,
            'default_sales_page_id' => 'nullable|exists:sales_pages,id',
            'is_primary' => 'boolean',
        ]);

        // If setting as primary, unset other primary domains
        if ($request->is_primary) {
            SellerDomain::where('user_id', auth()->id())
                ->where('id', '!=', $sellerDomain->id)
                ->update(['is_primary' => false]);
        }

        $domain = $this->cleanDomainName($request->domain);

        $sellerDomain->update([
            'domain' => $domain,
            'is_primary' => $request->is_primary ?? false,
            'default_sales_page_id' => $request->default_sales_page_id,
        ]);

        return redirect()->route('seller-domains.index')
            ->with('success', 'Domain updated successfully!');
    }

    /**
     * Remove the specified domain from storage.
     */
    public function destroy(SellerDomain $sellerDomain)
    {
        // Check ownership
        if ($sellerDomain->user_id !== auth()->id()) {
            abort(403, 'Unauthorized access to this domain.');
        }

        $message = 'Domain removed successfully!';

        // Delete Cloudflare DNS records if they exist
        if (SystemSetting::isCloudflareEnabled() && $sellerDomain->cloudflare_record_id) {
            try {
                $recordIds = json_decode($sellerDomain->cloudflare_record_id, true);
                $cloudflare = new CloudflareService();

                // Delete root record
                if (!empty($recordIds['root'])) {
                    $cloudflare->deleteDnsRecord($recordIds['root']);
                }

                // Delete www record
                if (!empty($recordIds['www'])) {
                    $cloudflare->deleteDnsRecord($recordIds['www']);
                }

                $message .= ' DNS records removed from Cloudflare.';
            } catch (\Exception $e) {
                Log::error('Failed to delete Cloudflare DNS records: ' . $e->getMessage());
                $message .= ' However, DNS records may need to be removed manually from Cloudflare.';
            }
        }

        $sellerDomain->delete();

        return redirect()->route('seller-domains.index')
            ->with('success', $message);
    }

    /**
     * Verify domain ownership.
     */
    public function verify(SellerDomain $sellerDomain)
    {
        // Check ownership
        if ($sellerDomain->user_id !== auth()->id()) {
            abort(403, 'Unauthorized access to this domain.');
        }

        // Check if automatic verification is possible
        if (SystemSetting::isCloudflareEnabled()) {
            $serverIp = SystemSetting::getServerIp();

            if ($serverIp) {
                $cloudflare = new CloudflareService();
                $result = $cloudflare->verifyDnsPropagation($sellerDomain->domain, $serverIp);

                if ($result['verified']) {
                    $sellerDomain->markAsVerified();
                    return back()->with('success', 'Domain verified successfully! DNS is pointing to the correct server.');
                } else {
                    return back()->with('error', 'Domain verification failed: ' . $result['message'] . '. Please ensure DNS is configured correctly and wait for propagation.');
                }
            }
        }

        // Fallback to manual verification
        $sellerDomain->markAsVerified();

        return back()->with('success', 'Domain verified successfully!');
    }

    /**
     * Clean domain name by removing protocol and trailing slashes.
     */
    private function cleanDomainName($domain)
    {
        // Remove http://, https://
        $domain = preg_replace('#^https?://#', '', $domain);

        // Remove trailing slashes
        $domain = rtrim($domain, '/');

        // Remove www. if present (we'll handle www separately in routing)
        // $domain = preg_replace('#^www\.#', '', $domain);

        return strtolower($domain);
    }
}
