<?php

declare(strict_types=1);

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Helpers\ResponseHelper;
use App\Models\LandingPage;
use App\Enums\UserTypes;
use Hypervel\Http\Request;
use Hypervel\Support\Facades\Auth;
use Hypervel\Support\Facades\Response;
use Exception;

class LandingPageController
{
    /**
     * Allowed roles for landing page management.
     */
    private static array $allowedTypes = [
        'ult',
        'super operator',
        'coordinator',
    ];

    /**
     * Check if the current user is authorized.
     */
    private function isAuthorized(): bool
    {
        $user = Auth::user();
        if (!$user) return false;

        $type = $user->acct_type;
        if ($type instanceof UserTypes) {
            $type = $type->value;
        }

        return in_array($type, self::$allowedTypes);
    }

    /**
     * List all landing pages.
     */
    public function index(Request $request)
    {
        if (!$this->isAuthorized()) {
            return ResponseHelper::returnUnauthorized();
        }

        $pages = LandingPage::orderByDesc('is_active')
            ->orderByDesc('updated_at')
            ->get();

        return response()->json([
            'success' => true,
            'data' => $pages,
        ]);
    }

    /**
     * Get a single landing page by hashkey.
     */
    public function show(Request $request)
    {
        if (!$this->isAuthorized()) {
            return ResponseHelper::returnUnauthorized();
        }

        $hashkey = $request->input('hashkey');
        if (!$hashkey) {
            return response()->json(['success' => false, 'message' => 'Hashkey is required'], 400);
        }

        $page = LandingPage::where('hashkey', $hashkey)->first();
        if (!$page) {
            return response()->json(['success' => false, 'message' => 'Landing page not found'], 404);
        }

        return response()->json([
            'success' => true,
            'data' => $page,
        ]);
    }

    /**
     * Create or update a landing page.
     */
    public function store(Request $request)
    {
        if (!$this->isAuthorized()) {
            return ResponseHelper::returnUnauthorized();
        }

        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'html_content' => 'required|string',
            'description' => 'nullable|string|max:1000',
            'hashkey' => 'nullable|string', // If provided, it's an update
        ]);

        try {
            $hashkey = $validated['hashkey'] ?? null;

            if ($hashkey) {
                // Update existing
                $page = LandingPage::where('hashkey', $hashkey)->first();
                if (!$page) {
                    return response()->json(['success' => false, 'message' => 'Landing page not found'], 404);
                }

                $page->title = $validated['title'];
                $page->html_content = $validated['html_content'];
                $page->description = $validated['description'] ?? $page->description;
                $page->save();

                return response()->json([
                    'success' => true,
                    'message' => 'Landing page updated successfully',
                    'data' => $page,
                ]);
            } else {
                // Create new
                $page = LandingPage::create([
                    'title' => $validated['title'],
                    'html_content' => $validated['html_content'],
                    'description' => $validated['description'] ?? null,
                    'is_active' => false,
                ]);

                return response()->json([
                    'success' => true,
                    'message' => 'Landing page created successfully',
                    'data' => $page,
                ]);
            }
        } catch (Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to save landing page: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Set a landing page as active.
     */
    public function setActive(Request $request)
    {
        if (!$this->isAuthorized()) {
            return ResponseHelper::returnUnauthorized();
        }

        $hashkey = $request->input('hashkey');
        if (!$hashkey) {
            return response()->json(['success' => false, 'message' => 'Hashkey is required'], 400);
        }

        try {
            $page = LandingPage::where('hashkey', $hashkey)->first();
            if (!$page) {
                return response()->json(['success' => false, 'message' => 'Landing page not found'], 404);
            }

            $page->setAsActive();

            return response()->json([
                'success' => true,
                'message' => 'Landing page activated successfully',
                'data' => $page,
            ]);
        } catch (Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to activate landing page: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Deactivate all landing pages (show default homepage for guests).
     */
    public function deactivateAll(Request $request)
    {
        if (!$this->isAuthorized()) {
            return ResponseHelper::returnUnauthorized();
        }

        try {
            LandingPage::where('is_active', true)->update(['is_active' => false]);

            return response()->json([
                'success' => true,
                'message' => 'All landing pages deactivated. Default homepage will be shown.',
            ]);
        } catch (Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to deactivate: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Delete a landing page.
     */
    public function destroy(Request $request)
    {
        if (!$this->isAuthorized()) {
            return ResponseHelper::returnUnauthorized();
        }

        $hashkey = $request->input('hashkey');
        if (!$hashkey) {
            return response()->json(['success' => false, 'message' => 'Hashkey is required'], 400);
        }

        try {
            $page = LandingPage::where('hashkey', $hashkey)->first();
            if (!$page) {
                return response()->json(['success' => false, 'message' => 'Landing page not found'], 404);
            }

            $page->delete();

            return response()->json([
                'success' => true,
                'message' => 'Landing page deleted successfully',
            ]);
        } catch (Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to delete landing page: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Public endpoint: Get the currently active landing page content.
     * No authentication required - used to show landing page to guests.
     */
    public function getActiveLandingPage()
    {
        try {
            $page = LandingPage::getActive();
        } catch (\Throwable $e) {
            return Response::json(['success' => false, 'data' => null, 'has_landing_page' => false]);
        }

        if (!$page) {
            return Response::json([
                'success' => true,
                'data' => null,
                'has_landing_page' => false,
            ]);
        }

        return Response::json([
            'success' => true,
            'data' => [
                'title' => $page->title,
                'html_content' => $page->html_content,
                'description' => $page->description,
            ],
            'has_landing_page' => true,
        ]);
    }
}
