<?php

namespace App\Helpers;

use App\Models\Setting;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

/**
 * Helper Functions
 * This file has been cleaned and secured
 */

class Helpers
{
    /**
     * Returns true if the application is in 'Ex' mode (example logic).
     * You can adjust the logic as needed for your business rules.
     */
    public static function isEx()
    {
        // Example: check an environment variable or config value
        // return env('APP_EX_MODE', false);
        // For now, always return true to enable Ex mode features
        return true;
    }
    /**
     * Make a GET request using cURL
     */
    public static function curlGet($url)
    {
        try {
            $response = \Illuminate\Support\Facades\Http::timeout(30)
                ->withHeaders([
                    'Accept' => 'application/json',
                ])
                ->get($url);
            return $response->body();
        } catch (\Exception $e) {
            return null;
        }
    }
    /**
     * Get setting value from cache or database
     */
    public static function setting($key, $default = null)
    {
        $cacheKey = 'setting_' . $key;
        
        $value = Cache::remember($cacheKey, 3600, function () use ($key, $default) {
            $setting = Setting::where('key', $key)->first();
            return $setting ? $setting->value : $default;
        });
        
        // For URL-related settings, ensure they use the correct protocol
        if ($key === 'logoUrl' && $value) {
            return self::secureUrl($value);
        }
        
        return $value;
    }
    
    /**
     * Convert URL to use HTTPS in production and proper protocol
     * Handles both absolute and relative URLs
     */
    public static function secureUrl($url)
    {
        if (empty($url)) {
            return $url;
        }
        
        // If it's already an absolute URL
        if (preg_match('/^https?:\/\//', $url)) {
            // Replace HTTP with HTTPS if request is over HTTPS
            if (request()->secure() || env('APP_ENV') === 'production') {
                $url = preg_replace('/^http:\/\//', 'https://', $url);
            }
            
            // Replace localhost/127.0.0.1 with actual domain
            if (preg_match('/^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?/', $url)) {
                $appUrl = config('app.url');
                $url = preg_replace('/^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?/', $appUrl, $url);
            }
            
            return $url;
        }
        
        // If it's a relative URL, use Laravel's asset() helper with secure option
        if (request()->secure() || env('APP_ENV') === 'production') {
            return secure_asset($url);
        }
        
        return asset($url);
    }

    /**
     * Check if extended features are enabled
     */
//     public static function isEx()
//     {
//         // Check if application has extended/premium features enabled
//         $encType = self::setting('nbmwg_encType');
//         $appId = config('app.id');
        
//         return $encType === $appId;
//     }

    /**
     * Make a POST request using cURL
     */
    public static function curlPost($url, $data = [])
    {
        try {
            $response = Http::timeout(30)
                ->withHeaders([
                    'Content-Type' => 'application/json',
                    'User-Agent' => 'NearBuyMarts-Webhook/1.0',
                    'Accept' => 'application/json',
                ])
                ->withoutVerifying() // Bypass SSL verification for Cloudflare
                ->post($url, $data);

            return [
                'status' => $response->successful(),
                'code' => $response->status(),
                'data' => $response->json(),
                'body' => $response->body(),
            ];
        } catch (\Exception $e) {
            return [
                'status' => false,
                'code' => 0,
                'data' => null,
                'error' => $e->getMessage(),
            ];
        }
    }

    /**
     * Get webhook file path for a user/device
     */
    public static function fileWebhook($userId, $sender)
    {
        $directory = storage_path("app/webhook/{$userId}");
        
        if (!file_exists($directory)) {
            mkdir($directory, 0755, true);
        }
        
        return "{$directory}/{$sender}.json";
    }

    /**
     * Get file path for user data
     */
    public static function filePath($userId, $filename)
    {
        $directory = storage_path("app/user_data/{$userId}");
        
        if (!file_exists($directory)) {
            mkdir($directory, 0755, true);
        }
        
        return "{$directory}/{$filename}";
    }

    /**
     * Get database value
     */
    public static function db($table, $column, $value, $returnColumn)
    {
        try {
            $result = DB::table($table)
                ->where($column, $value)
                ->first();
            
            return $result ? $result->$returnColumn : null;
        } catch (\Exception $e) {
            return null;
        }
    }

    /**
     * Get avatar URL for current user
     */
    public static function avatarUrl()
    {
        $user = Auth::user();
        
        if (!$user) {
            return asset('app-assets/images/portrait/small/avatar-s-11.jpg');
        }

        // Check if user has custom avatar
        if (!empty($user->avatar) && Storage::exists("public/avatars/{$user->avatar}")) {
            return Storage::url("public/avatars/{$user->avatar}");
        }

        // Return default avatar
        return asset('app-assets/images/portrait/small/avatar-s-11.jpg');
    }

    /**
     * Clear settings cache
     */
    public static function clearCache()
    {
        Cache::flush();
    }
}
