<?php

namespace App\Services;

use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class CompanyEmailDetails
{

    public static function getCompanyEmailDetails($customer_id = null, $workspace_id = null)
    {   
        Log::info('getCompanyEmailDetails: Method called', [
            'customer_id' => $customer_id ?? 'NULL',
            'workspace_id' => $workspace_id ?? 'NULL'
        ]);
        
        // Default values
        $defaults = [
            'logoPath' => null,
            'companyName' => env('APP_NAME', 'WMS'),
            'companyAddress' => '',
            'companyCity' => '',
            'companyState' => '',
            'companyPostCode' => '',
            'companyCountry' => '',
            'companyPhone' => 'Contact Information',
            'companyEmail' => env('EMAIL_ADDRESS', 'support@example.com'),
        ];

        $settingsData = [];
        if($customer_id){
            $authUser = User::where('id', $customer_id)->first();
            Log::info('getCompanyEmailDetails: Using customer_id', ['customer_id' => $customer_id, 'user_found' => !is_null($authUser)]);
            
            if (!$authUser) {
                Log::warning('getCompanyEmailDetails: Customer not found, using defaults', ['customer_id' => $customer_id]);
                return $defaults; // Return defaults if customer not found
            }
        }else{
            $authUser = Auth::user();
            Log::info('getCompanyEmailDetails: Using Auth::user()', ['user_found' => !is_null($authUser)]);
        }

        if (!$authUser) {
            Log::warning('getCompanyEmailDetails: No authenticated user found, using defaults');
            return $defaults; // Return defaults if no authenticated user
        }

        // Add debug logging for user type and ID
        Log::info('getCompanyEmailDetails: User details', [
            'user_id' => $authUser->id,
            'user_type' => $authUser->user_type,
            'admin_constant' => config('constants.user_types.admin'),
            'current_workspace_id' => $authUser->current_workspace_id ?? 'N/A',
            'passed_workspace_id' => $workspace_id ?? 'N/A'
        ]);

        // Check if auth user is admin (user_type 1)
        if ($authUser->user_type == config('constants.user_types.admin')) {
            Log::info('getCompanyEmailDetails: Querying admin settings for admin user', ['customer_id' => $authUser->id]);
            // Get admin settings for super admin
            $settings = DB::table('adminsettings')
                ->where('customer_id', $authUser->id)
                ->get();
        } else {
            Log::info('getCompanyEmailDetails: User is not admin, checking workspace settings');
            
            // For non-admin users, use the passed workspace_id or the user's workspace
            if ($customer_id && $authUser) {
                // Use the passed workspace_id if provided, otherwise use the user's current_workspace_id
                $final_workspace_id = $workspace_id ?? $authUser->current_workspace_id;
                
                Log::info('getCompanyEmailDetails: Using customer details', [
                    'customer_id' => $customer_id,
                    'final_workspace_id' => $final_workspace_id,
                    'passed_workspace_id' => $workspace_id ?? 'NULL',
                    'user_workspace_id' => $authUser->current_workspace_id ?? 'NULL'
                ]);
                
                if ($final_workspace_id) {
                    $settings = DB::table('adminsettings')
                        ->where('customer_id', $customer_id)
                        ->where('workspace', $final_workspace_id)
                        ->get();
                    
                    Log::info('getCompanyEmailDetails: Query executed with workspace filter', [
                        'settings_count' => $settings->count(),
                        'query_params' => [
                            'customer_id' => $customer_id,
                            'workspace' => $final_workspace_id
                        ]
                    ]);
                } else {
                    // If no workspace_id available, try without workspace filter
                    Log::warning('getCompanyEmailDetails: No workspace_id available, querying without workspace filter');
                    $settings = DB::table('adminsettings')
                        ->where('customer_id', $customer_id)
                        ->get();
                    Log::info('getCompanyEmailDetails: Query without workspace filter', [
                        'settings_count' => $settings->count()
                    ]);
                }
            } else {
                // Fallback to original method for authenticated users
                $customerWorkspaceIds = self::getUserCustomerAndWorkspaceIds();
                if ($customerWorkspaceIds) {
                    Log::info('getCompanyEmailDetails: Using Auth user workspace details', $customerWorkspaceIds);
                    // Get customer-specific admin settings
                    $settings = DB::table('adminsettings')
                        ->where('customer_id', $customerWorkspaceIds['customer_id'])
                        ->where('workspace', $customerWorkspaceIds['workspace_id'])
                        ->get();
                } else {
                    Log::warning('getCompanyEmailDetails: No customer/workspace IDs found');
                    $settings = collect(); // Empty collection if no IDs found
                }
            }
        }

        Log::info('getCompanyEmailDetails: Settings query result', ['settings_count' => $settings->count()]);

        // Transform settings into key-value pairs
        foreach ($settings as $setting) {
            $settingsData[$setting->key] = $setting->value;
        }

        Log::info('getCompanyEmailDetails: Settings data retrieved', [
            'settings_keys' => array_keys($settingsData),
            'company_name' => $settingsData['company_company_name'] ?? 'NOT_FOUND',
            'brand_logo' => $settingsData['brand_logo_dark'] ?? 'NOT_FOUND'
        ]);

        // Return company details with fallback to defaults
        $result = [
            'logoPath' => $settingsData['brand_logo_dark'] ?? $defaults['logoPath'],
            'companyName' => $settingsData['company_company_name'] ?? $defaults['companyName'],
            'companyAddress' => $settingsData['company_company_address'] ?? $defaults['companyAddress'],
            'companyCity' => $settingsData['company_company_city'] ?? $defaults['companyCity'],
            'companyState' => $settingsData['company_company_state'] ?? $defaults['companyState'],
            'companyPostCode' => $settingsData['company_company_post_code'] ?? $defaults['companyPostCode'],
            'companyCountry' => $settingsData['company_company_country'] ?? $defaults['companyCountry'],
            'companyPhone' => $settingsData['company_company_telephone'] ?? $defaults['companyPhone'],
            'companyEmail' => $settingsData['company_company_email'] ?? $defaults['companyEmail'],
            'companyAddressFull' => trim(
                ($settingsData['company_company_address'] ?? $defaults['companyAddress']) . ', ' .
                ($settingsData['company_company_city'] ?? $defaults['companyCity']) . ', ' .
                ($settingsData['company_company_state'] ?? $defaults['companyState']) . ', ' .
                ($settingsData['company_company_post_code'] ?? $defaults['companyPostCode']) . ', ' .
                ($settingsData['company_company_country'] ?? $defaults['companyCountry'])
            ),
            'systemDateFormte' => $settingsData['system_date_format'] ?? '',
        ];

        Log::info('getCompanyEmailDetails: Final result', [
            'companyName' => $result['companyName'],
            'logoPath' => $result['logoPath'],
            'logoPath_exists' => !empty($result['logoPath']) ? (file_exists(public_path($result['logoPath'])) ? 'YES' : 'NO') : 'EMPTY',
            'logoPath_full_path' => !empty($result['logoPath']) ? public_path($result['logoPath']) : 'N/A'
        ]);

        return $result;
    }

    /**
     * Helper function to get customer and workspace IDs for authenticated user
     */
    public static function getUserCustomerAndWorkspaceIds()
    {
        $user = Auth::user();
        if (!$user) {
            return null;
        }

        if ($user instanceof \App\Models\User) {
            return [
                'customer_id' => $user->id,
                'workspace_id' => $user->current_workspace_id,
            ];
        } elseif ($user instanceof \App\Models\EmpCompanyDetails) {
            return [
                'customer_id' => $user->customer_id,
                'workspace_id' => $user->workspace_id,
            ];
        }
        return null;
    }
}
