<?php
  
use App\Models\User;
use App\Models\OneSignalPushNotification;
use App\Models\GeneralSetting;
use App\Models\Product;
use App\Models\Country;
use App\Models\PaymentGatewaySettings;
use App\Models\Payment;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

if (!function_exists('toUserTimezone')) {
    function toUserTimezone($date, $format = 'd-m-Y h:i A')
    {
        if (!$date) return null;

        $timezone = config('app.user_timezone', 'UTC');

        // echo $timezone = config('app.user_timezone', 'UTC'); die();

        return Carbon::parse($date, 'UTC')
            ->setTimezone($timezone)
            ->format($format);
    }
}

if (! function_exists('getCountrydetailsById')) {
    function getCountrydetailsById($country_id = null){
        if(isset($country_id)){
            return Country::where('id', $country_id)->first();
        } else {
            return Country::select('id', 'country_name', 'top_level_domain', 'phone_code', 'phone_number_length_min', 'phone_number_length_max', 'currency', 'is_seller_flag')->get();    
        }
    }
}

if (! function_exists('getEnvironmentData')) {
    function getEnvironmentData(){
        $payment_gateway_config = PaymentGatewaySettings::first();
        $api_tap_payment_key = $payment_gateway_config->type == 'live' ? $payment_gateway_config->tap_payment_key_live : $payment_gateway_config->tap_payment_key_test;

        $payment_deadline_for_auction_winner_days = getGeneralSettingData('payment_deadline_for_auction_winner_(days)');
        $product_receipt_notification_time = getGeneralSettingData('product_receipt_notification_time_(Hours)');
        $id_verification_section = getGeneralSettingData('id_verification_section');
        $auction_starting_soon_notification_time_hours = getGeneralSettingData('auction_starting_soon_—_notification_time_(Hours)');
        $auction_ending_soon_notification_time_hours = getGeneralSettingData('auction_ending_soon_—_ notification_time_(Hours)');
        $payment_options = getGeneralSettingData('payment_option');
        $payment_options = $payment_options ? json_decode($payment_options, true) : [];
        $wait_for_cash_payment_days = getGeneralSettingData('wait_for_cash_payment_(Days)');
        $current_app_version = getGeneralSettingData('current_app_version');
        
        $data['API_TAP_COMPANY'] = "Bearer $api_tap_payment_key";

        $data['PAYMENT_DEADLINE_FOR_AUCTION_WINNER_DAYS'] = $payment_deadline_for_auction_winner_days; // Days

        $data['PRODUCT_RECEIPT_NOTIFICATION_TIME'] = $product_receipt_notification_time;
        $data['ID_VERIFICATION_SECTION'] = $id_verification_section;
        $data['AUCTION_STARTING_SOON_NOTIFICATION_TIME'] = $auction_starting_soon_notification_time_hours;
        $data['AUCTION_ENDING_SOON_NOTIFICATION_TIME'] = $auction_ending_soon_notification_time_hours;
        $data['PAYMENT_OPTIONS'] = $payment_options;
        $data['WAIT_FOR_CASH_PAYMENT_DAYS'] = $wait_for_cash_payment_days;
        $data['CURRENT_APP_VERSION'] = $current_app_version;

        return $data; 
    }    
}

if (! function_exists('getExchangePrice')) {
    function getExchangePrice($currency_code = null, $price = null){
        // $rates  = [
        //     "AED" => 4.243136,
        //     "AFN" => 80.397285,
        //     "ALL" => 98.116693,
        //     "AMD" => 441.361302,
        //     "ANG" => 2.06778,
        //     "AOA" => 1058.371547,
        //     "ARS" => 1365.963379,
        //     "AUD" => 1.778786,
        //     "AWG" => 2.082659,
        //     "AZN" => 1.963055,
        //     "BAM" => 1.959179,
        //     "BBD" => 2.326833,
        //     "BDT" => 140.832922,
        //     "BGN" => 1.958763,
        //     "BHD" => 0.435667,
        //     "BIF" => 3431.359337,
        //     "BMD" => 1.155428,
        //     "BND" => 1.480127,
        //     "BOB" => 7.963737,
        //     "BRL" => 6.411583,
        //     "BSD" => 1.152458,
        //     "BTC" => 1.0823225e-5,
        //     "BTN" => 99.167621,
        //     "BWP" => 15.490317,
        //     "BYN" => 3.771342,
        //     "BYR" => 22646.388631,
        //     "BZD" => 2.314913,
        //     "CAD" => 1.570192,
        //     "CDF" => 3324.166575,
        //     "CHF" => 0.938468,
        //     "CLF" => 0.02823,
        //     "CLP" => 1083.32861,
        //     "CNY" => 8.297824,
        //     "CNH" => 8.300647,
        //     "COP" => 4775.950048,
        //     "CRC" => 580.891922,
        //     "CUC" => 1.155428,
        //     "CUP" => 30.618842,
        //     "CVE" => 110.455524,
        //     "CZK" => 24.794216,
        //     "DJF" => 205.216873,
        //     "DKK" => 7.459004,
        //     "DOP" => 68.066229,
        //     "DZD" => 150.328673,
        //     "EGP" => 58.476456,
        //     "ERN" => 17.33142,
        //     "ETB" => 155.476389,
        //     "EUR" => 1,
        //     "FJD" => 2.597691,
        //     "FKP" => 0.850723,
        //     "GBP" => 0.851418,
        //     "GEL" => 3.165977,
        //     "GGP" => 0.850723,
        //     "GHS" => 11.870475,
        //     "GIP" => 0.850723,
        //     "GMD" => 81.483471,
        //     "GNF" => 9986.052032,
        //     "GTQ" => 8.856276,
        //     "GYD" => 241.115899,
        //     "HKD" => 9.069665,
        //     "HNL" => 30.078361,
        //     "HRK" => 7.539629,
        //     "HTG" => 151.138081,
        //     "HUF" => 402.19872,
        //     "IDR" => 18830.876547,
        //     "ILS" => 4.105207,
        //     "IMP" => 0.850723,
        //     "INR" => 99.434748,
        //     "IQD" => 1509.690992,
        //     "IRR" => 48643.518683,
        //     "ISK" => 144.023853,
        //     "JEP" => 0.850723,
        //     "JMD" => 184.518275,
        //     "JOD" => 0.819169,
        //     "JPY" => 166.576868,
        //     "KES" => 149.119776,
        //     "KGS" => 101.042248,
        //     "KHR" => 4620.930625,
        //     "KMF" => 492.768931,
        //     "KPW" => 1039.885192,
        //     "KRW" => 1574.559828,
        //     "KWD" => 0.353618,
        //     "KYD" => 0.96034,
        //     "KZT" => 591.104245,
        //     "LAK" => 24865.244312,
        //     "LBP" => 103256.237806,
        //     "LKR" => 345.066243,
        //     "LRD" => 230.489591,
        //     "LSL" => 20.739836,
        //     "LTL" => 3.411678,
        //     "LVL" => 0.698907,
        //     "LYD" => 6.296643,
        //     "MAD" => 10.537276,
        //     "MDL" => 19.735187,
        //     "MGA" => 5203.840962,
        //     "MKD" => 61.510785,
        //     "MMK" => 2426.292238,
        //     "MNT" => 4137.87408,
        //     "MOP" => 9.317191,
        //     "MRU" => 45.752126,
        //     "MUR" => 52.548431,
        //     "MVR" => 17.799344,
        //     "MWK" => 1998.294963,
        //     "MXN" => 21.864396,
        //     "MYR" => 4.904807,
        //     "MZN" => 73.889297,
        //     "NAD" => 20.739836,
        //     "NGN" => 1785.70242,
        //     "NIO" => 42.412423,
        //     "NOK" => 11.440314,
        //     "NPR" => 158.670944,
        //     "NZD" => 1.919137,
        //     "OMR" => 0.444252,
        //     "PAB" => 1.152488,
        //     "PEN" => 4.159775,
        //     "PGK" => 4.814221,
        //     "PHP" => 65.229725,
        //     "PKR" => 326.714766,
        //     "PLN" => 4.265606,
        //     "PYG" => 9195.542999,
        //     "QAR" => 4.204052,
        //     "RON" => 5.025308,
        //     "RSD" => 117.241242,
        //     "RUB" => 91.275291,
        //     "RWF" => 1664.156091,
        //     "SAR" => 4.336647,
        //     "SBD" => 9.644809,
        //     "SCR" => 16.695858,
        //     "SDG" => 693.841718,
        //     "SEK" => 10.980754,
        //     "SGD" => 1.480959,
        //     "SHP" => 0.907985,
        //     "SLE" => 25.476865,
        //     "SLL" => 24228.7515,
        //     "SOS" => 658.636078,
        //     "SRD" => 43.360934,
        //     "STD" => 23915.026622,
        //     "SVC" => 10.08422,
        //     "SYP" => 15022.763593,
        //     "SZL" => 20.726212,
        //     "THB" => 37.524893,
        //     "TJS" => 11.639777,
        //     "TMT" => 4.043998,
        //     "TND" => 3.410082,
        //     "TOP" => 2.706129,
        //     "TRY" => 45.518781,
        //     "TTD" => 7.815278,
        //     "TWD" => 34.113433,
        //     "TZS" => 2988.724825,
        //     "UAH" => 47.803014,
        //     "UGX" => 4153.163769,
        //     "USD" => 1.155428,
        //     "UYU" => 47.381728,
        //     "UZS" => 14643.194599,
        //     "VES" => 118.046575,
        //     "VND" => 30145.69401,
        //     "VUV" => 137.614333,
        //     "WST" => 3.026283,
        //     "XAF" => 657.084715,
        //     "XAG" => 0.031725,
        //     "XAU" => 0.000338,
        //     "XCD" => 3.122602,
        //     "XDR" => 0.817188,
        //     "XOF" => 657.084715,
        //     "XPF" => 119.331742,
        //     "YER" => 281.172916,
        //     "ZAR" => 20.66379,
        //     "ZMK" => 10400.236947,
        //     "ZMW" => 27.860091,
        //     "ZWL" => 372.047342
        // ];

        // $from = 'BHD';
        // $to = $currency_code;
        // $amount = $price;

        // Default currency when blank
        $to = $currency_code && trim($currency_code) !== '' ? strtoupper($currency_code) : 'BHD';
        $from = 'BHD'; // base currency

        // Fetch all rates from DB
        $rates = Country::pluck('rates', 'currency')->toArray(); // ['AED' => 4.24, 'BHD' => 0.43, ...]
            
        $conversionRate = $rates[$to] / $rates[$from];
        $convertedAmount = $price * $conversionRate;

        $fixedPrice = ($convertedAmount - floor($convertedAmount)) >= 0.5
            ? ceil($convertedAmount)     // round up
            : floor($convertedAmount);   // round down

        return $fixedPrice.' '.$to;
    }
}

if (! function_exists('pushNotification')) {
    function pushNotification($userId, $msg){
        $one_signal_push_notification = OneSignalPushNotification::first();
        if ($one_signal_push_notification->enable_notifications != 1) {
            return false; // Notification Disabled
        }

        $curl = curl_init();

        // "app_id": "ab34c8b0-6e01-41b9-bdd4-65a81e741631",
        // 'Authorization: os_v2_app_vm2mrmdoafa3tpoumwub45awggn5opjnnxnublmavumt3h5hn6gruy7tz2ppbf5qrtg4hwyvw7q4qjpl3g64gt5l2dlivlfbjeyz77a',

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://api.onesignal.com/notifications?c=push',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS =>json_encode([
                "app_id" => $one_signal_push_notification->app_id,
                "contents" => ["en" => $msg],
                "headings" => ["en" => "Torathy"],
                "include_aliases" => [
                    "external_id" => ["torathy_mobile_app_" . $userId]
                ],
                "target_channel" => "push"
            ]),
            CURLOPT_HTTPHEADER => array(
                "Authorization: $one_signal_push_notification->authorization_token",
                'accept: application/json',
                'content-type: application/json',
            )
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        return json_decode($response, true);
    }
}

if (! function_exists('getUserKYCPendingCount')) {
    function getUserKYCPendingCount(){
        return User::whereHas('roles')->whereIn('kyc_status', [0,1])->orwhere('seller_status', 1)->count();    
    }
}

if (! function_exists('getProductPendingCount')) {
    function getProductPendingCount(){
        return Product::whereIn('status', ['Draft', 'Pending'])->count();    
    }
}

if (! function_exists('getCashPaymentPendingRequestCount')) {
    function getCashPaymentPendingRequestCount(){
        return Payment::where('payment_status', 'pending')->count();  
    }
}

if (! function_exists('generateSKU')) {
    function generateSKU()
    {
        // return sprintf(
        //     '%04d-%04d-%04d-%04d',
        //     mt_rand(1000, 9999),
        //     mt_rand(1000, 9999),
        //     mt_rand(1000, 9999),
        //     mt_rand(1000, 9999)
        // );

        // Get next auto-increment ID for products table
        // $statement = DB::select("SHOW TABLE STATUS LIKE 'products'");
        // $nextId = $statement[0]->Auto_increment + 2 ?? 1;
        
        $statement = Product::select('id')->orderBy('id', 'desc')->limit(1)->first();
        $nextId = $statement?->id ? ($statement->id + 1) : 1;
 
        // Calculate prefix (AA, AB, ..., ZZ)
        $batch = floor(($nextId - 1) / 9999);
        $prefix = chr(65 + floor($batch / 26)) . chr(65 + ($batch % 26));
 
        // 4-digit number part
        $number = str_pad(($nextId - ($batch * 9999)), 4, '0', STR_PAD_LEFT);
 
        return $prefix . $number;
    }
}

if (! function_exists('getGeneralSettingData')) {
    function getGeneralSettingData($filed = null)
    {
        // return GeneralSetting::getValue($filed);

        $query = GeneralSetting::query();

        if ($filed) {
            return optional($query->where('key', $filed)->first())->value;
        }

        return $query->pluck('value', 'key')->toArray();
    }
}

// if (! function_exists('pushNotification')) {
//     function pushNotification($usrrId,$msg){
//         $curl = curl_init();

//         curl_setopt_array($curl, array(
//             CURLOPT_URL => 'https://api.onesignal.com/notifications?c=push',
//             CURLOPT_RETURNTRANSFER => true,
//             CURLOPT_ENCODING => '',
//             CURLOPT_MAXREDIRS => 10,
//             CURLOPT_TIMEOUT => 0,
//             CURLOPT_FOLLOWLOCATION => true,
//             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
//             CURLOPT_CUSTOMREQUEST => 'POST',
//             CURLOPT_POSTFIELDS =>'{
//                 "app_id": "ab34c8b0-6e01-41b9-bdd4-65a81e741631",
//                 "contents": {
//                     "en": "'.$msg.'"
//                 },
//                 "headings": {
//                     "en": "Auto service"
//                 },
//                 "include_aliases": {
//                     "external_id": [
//                         "auto_service_'.$usrrId.'"
//                     ]
//                 },
//                 "target_channel": "push"
//             }',
//             CURLOPT_HTTPHEADER => array(
//                 'Authorization: os_v2_app_vm2mrmdoafa3tpoumwub45awggn5opjnnxnublmavumt3h5hn6gruy7tz2ppbf5qrtg4hwyvw7q4qjpl3g64gt5l2dlivlfbjeyz77a',
//                 'accept: application/json',
//                 'content-type: application/json',
//                 'Cookie: __cf_bm=3silgPN2soKX2cFpa85frcEb1bRRRJoUr1LE6ik7Gw0-1740029998-1.0.1.1-iRx93kdno9m.e8dTaoweUrje4klZ9YtPo67GXLfAMIw_woYQ8fYjR6G1NoTuX7W_G9dV2UDKFpWetWn3zHEpuQ'
//             ),
//         ));

//         $response = curl_exec($curl);

//         curl_close($curl);
        
//         return json_decode($response);
//     }
// }
