<?php

use App\Models\Company;
use App\Scopes\CompanyScope;

// Get App Type
if (!function_exists('app_type')) {

    function app_type()
    {
        if (env('APP_TYPE')) {
            return env('APP_TYPE');
        } else {
            return "non-saas";
        }
    }
}

// Website Landing settings Language Key
// Returns slug-based language key (e.g., "mywebsite_en" or "default_en")
if (!function_exists('website_lang_key')) {

    function website_lang_key()
    {
        if (session()->has('website_lang_key')) {
            return session('website_lang_key');
        }

        // Default to 'default_en' if not set
        session(['website_lang_key' => 'default_en']);
        return session('website_lang_key');
    }
}

// This is app setting for logged in company
if (!function_exists('company')) {

    function company($reset = false)
    {
        if (session()->has('company') && $reset == false) {
            return session('company');
        }

        // If it is non-saas
        if (app_type() == 'non-saas') {
            $company = Company::select('*')->with(['currency' => function ($query) {
                return $query->withoutGlobalScope(CompanyScope::class);
            }, 'subscriptionPlan', 'pdfFont', 'lang'])->first();

            if ($company) {
                session(['company' => $company]);
                return session('company');
            }

            return null;
        } else {
            $user = user();

            if ($user && $user->company_id != "") {
                $company = Company::withoutGlobalScope('company')->with(['currency' => function ($query) use ($user) {
                    return $query->withoutGlobalScope(CompanyScope::class)
                        ->where('company_id', $user->company_id);
                }, 'subscriptionPlan' => function ($query) use ($user) {
                    return $query->select('id', 'modules', 'max_users', 'monthly_price', 'annual_price');
                }, 'pdfFont', 'lang'])->where('id', $user->company_id)->first();

                session(['company' => $company]);
                return session('company');
            }

            return null;
        }
    }
}

if (!function_exists('super_admin')) {

    /**
     * Return currently logged in user
     */
    function super_admin()
    {
        if (session()->has('super_admin')) {
            return session('super_admin');
        }

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

        if ($user) {

            session(['super_admin' => $user]);
            return session('super_admin');
        }

        return null;
    }
}

// Get Website Route Prefix from company settings
if (!function_exists('website_route_prefix')) {

    function website_route_prefix()
    {
        try {
            // For SAAS: get prefix from company where is_global is true
            // For non-SAAS: get prefix from first company
            if (app_type() == 'saas') {
                $globalCompany = Company::withoutGlobalScope('company')
                    ->where('is_global', true)
                    ->first();
                return $globalCompany?->website_route_prefix ?? 'w';
            } else {
                $company = Company::first();
                return $company?->website_route_prefix ?? 'w';
            }
        } catch (\Exception $e) {
            // Table doesn't exist yet (during migrations), return default
            return 'w';
        }
    }
}

/**
 * Generate landing home URL based on website is_primary and app_type
 * For primary website in non-saas mode, returns root URL
 * Otherwise returns the website-specific URL with prefix
 *
 * @param \App\Models\Website|null $website The website object (must have is_primary and slug)
 * @param string|null $slug Optional slug override
 * @return string The landing page URL
 */
if (!function_exists('landing_home_url')) {

    function landing_home_url($website = null, ?string $slug = null)
    {
        // Check if we're currently on the root URL (primary website accessed via root)
        $currentPath = request()->path();
        $websitePrefix = website_route_prefix();
        $isOnRootUrl = !str_starts_with($currentPath, $websitePrefix . '/');

        // If website is primary in non-saas mode AND we're on root URL, return root URL
        if ($website && $website->is_primary && app_type() == 'non-saas' && $isOnRootUrl) {
            return url('/');
        }

        // Otherwise return the website-specific URL
        $websiteSlug = $slug ?? ($website ? $website->slug : null);

        if (!$websiteSlug) {
            return url('/');
        }

        return route('landing.home', ['slug' => $websiteSlug]);
    }
}

/**
 * Generate landing page URL based on website is_primary and app_type
 * For primary website in non-saas mode, returns root page URL
 * Otherwise returns the website-specific page URL with prefix
 *
 * @param string $pageSlug The page slug
 * @param \App\Models\Website|null $website The website object (must have is_primary and slug)
 * @param string|null $slug Optional website slug override
 * @return string The landing page URL
 */
if (!function_exists('landing_page_url')) {

    function landing_page_url(string $pageSlug, $website = null, ?string $slug = null)
    {
        // Check if we're currently on the root URL (primary website accessed via root)
        $currentPath = request()->path();
        $websitePrefix = website_route_prefix();
        $isOnRootUrl = !str_starts_with($currentPath, $websitePrefix . '/');

        // If website is primary in non-saas mode AND we're on root URL, return root page URL
        if ($website && $website->is_primary && app_type() == 'non-saas' && $isOnRootUrl) {
            return route('landing.root.page', ['pageSlug' => $pageSlug]);
        }

        // Otherwise return the website-specific page URL
        $websiteSlug = $slug ?? ($website ? $website->slug : null);

        if (!$websiteSlug) {
            return url('/page/' . $pageSlug);
        }

        return route('landing.page', ['slug' => $websiteSlug, 'pageSlug' => $pageSlug]);
    }
}

if (!function_exists('user')) {

    /**
     * Return currently logged in user
     */
    function user()
    {
        if (session()->has('user')) {
            return session('user');
        }

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

        if ($user) {
            $user = $user->load(['role' => function ($query) use ($user) {
                return $query->withoutGlobalScope(CompanyScope::class)
                    ->where('company_id', $user->company_id);
            }, 'role.perms']);

            session(['user' => $user]);
            return session('user');
        }

        return null;
    }
}
