<?php

namespace App\Http\Controllers\Api\V2;

use App\CentralLogics\Helpers;
use App\Http\Controllers\Controller;
use App\Models\BusinessSetting;
use App\Models\CustomerAddress;
use App\Models\Module;
use App\Models\Order;
use App\Models\User;
use App\Models\Version;
use App\Models\Zone;
use Grimzy\LaravelMysqlSpatial\Types\Point;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Validator;

class ConfigController extends Controller
{
    public $isLive = true;

    public function configuration(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'cm_firebase_token' => 'required',
            'platform' => 'required|string',
            'app_version' => 'required|string|max:50',
            'lat' => 'required',
            'lng' => 'required',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => Helpers::error_processor($validator)], 403);
        }

        /*
        if($this->isLive == true && $request->platform != 'Android'){
            try {
                $queryParams = [
                    'cm_firebase_token' => $request->cm_firebase_token,
                    'platform' => $request->platform,
                    'app_version' => $request->app_version,
                    'lat' => $request->lat,
                    'lng' => $request->lng,
                ];

                $headers = [];
                if ($request->hasHeader('X-localization')) {
                    $headers['X-localization'] = $request->header('X-localization');
                }

                if ($request->bearerToken()) {
                    $headers['Authorization'] = 'Bearer ' . $request->bearerToken();
                }

                $response = Http::withHeaders($headers)
                    ->timeout(8) // قيمة معقولة للتايم آوت
                    ->get('https://postajji.com/api/v2/config', $queryParams);

                if ($response->successful()) {
                    if ($response->header('Content-Type') && str_contains($response->header('Content-Type'), 'application/json')) {
                        return response()->json($response->json(), $response->status());
                    }
                    return response($response->body(), $response->status())
                        ->header('Content-Type', $response->header('Content-Type') ?? 'text/plain');
                }

                $body = null;
                try { $body = $response->json(); } catch (\Exception $ex) { $body = $response->body(); }

                return response()->json([
                    'errors' => [
                        'code' => 'remote_config_error',
                        'message' => 'Failed to fetch remote configuration.',
                        'remote_status' => $response->status(),
                        'remote_body' => $body
                    ]
                ], 502);

            } catch (\Exception $e) {
                return response()->json([
                    'errors' => [
                        'code' => 'remote_config_exception',
                        'message' => 'Exception while fetching remote configuration: ' . $e->getMessage()
                    ]
                ], 502);
            }
        }
        */

        $user = $request->user('api');
        $userData = null;
        $currentOrders = [];

        if ($user) {
            if (!$request->hasHeader('X-localization')) {
                return response()->json([
                    'errors' => [
                        'code' => 'current_language_key',
                        'message' => translate('messages.current_language_key_required')
                    ]
                ], 405);
            }

            $this->updateUserInfo($user, $request);
            $currentOrders = $this->getCurrentOrders($user);
            $userData = $this->getUserData($user);
        }

        $settings = $this->getSettings();
        $zoneInfo = $this->getZoneInfo($request->lat, $request->lng);

        return response()->json(
            $this->buildResponse($settings, $zoneInfo, $request, $currentOrders, $userData, (bool)$user)
        );
    }

    private function updateUserInfo($user, $request): void
    {
        $user->update([
            'platform' => $request->platform,
            'app_version' => $request->app_version,
            'last_login' => now(),
            'cm_firebase_token' => $request->cm_firebase_token,
            'current_language_key' => $request->header('X-localization'),
        ]);
    }

    private function getCurrentOrders($user)
    {
        return Order::with(['store', 'delivery_man.rating', 'parcel_category'])
            ->withCount('details')
            ->where('user_id', $user->id)
            ->whereNotIn('order_status', ['delivered', 'canceled', 'refund_requested', 'refund_request_canceled', 'refunded', 'failed'])
            ->Notpos()
            ->latest()
            ->take(10)
            ->get()
            ->map(function ($order) {
                $order['delivery_address'] = $order['delivery_address'] ? json_decode($order['delivery_address']) : null;
                $order['store'] = $order['store'] ? Helpers::store_data_formatting($order['store']) : null;
                $order['delivery_man'] = $order['delivery_man'] ? Helpers::deliverymen_data_formatting([$order['delivery_man']])[0] : null;
                return $order;
            });
    }

    private function getUserData($user)
    {
        $user['userinfo'] = $user->userinfo;
        $user['order_count'] = $user->orders()->count();
        $user['member_since_days'] = $user->created_at->diffInDays();

        $addresses = CustomerAddress::where('user_id', $user->id)->latest()->get();
        $user['addresses'] = Helpers::address_data_formatting($addresses);

        unset($user['orders']);

        return $user;
    }

    private function getSettings()
    {
        $settingKeys = BusinessSetting::AppConfigKeys;

        return Cache::remember('app_configuration', now()->addDays(7), function () use ($settingKeys) {
            return array_column(
                BusinessSetting::whereIn('key', $settingKeys)->get()->toArray(),
                'value',
                'key'
            );
        });
    }

    private function getZoneInfo($lat, $lng)
    {
        $point = new Point($lat, $lng);
        $zones = Zone::with('modules')->contains('coordinates', $point)->latest()->get(['id', 'status', 'cash_on_delivery', 'digital_payment']);

        if (count($zones) < 1) {
            response()->json([
                'errors' => [
                    ['code' => 'coordinates', 'message' => translate('messages.service_not_available_in_this_area')]
                ]
            ], 404)->send();
            exit;
        }

        $zoneInfo = array_filter($zones->toArray(), function ($zone) {
            return $zone['status'] == 1;
        });

        return count($zoneInfo) > 0
            ? ['zone_id' => json_encode(array_column($zoneInfo, 'id')), 'zone_data' => array_values($zoneInfo)]
            : null;
    }

    private function buildResponse($settings, $zoneInfo, $request, $currentOrders, $userData, $isLoggedIn): array
    {
        $default_location = json_decode($settings['default_location'] ?? '{}', true);
        $cod = json_decode($settings['cash_on_delivery'] ?? '[]', true);
        $digital_payment = json_decode($settings['digital_payment'] ?? '[]', true);
        $landing = json_decode($settings['landing_page_text'] ?? '{}', false);

        // Prepare base URLs
        $baseUrl = url('/');
        $assetPath = fn($path) => asset("storage/app/public/{$path}");

        // Languages
        $languages = json_decode($settings['language'] ?? '[]', true);
        $lang_array = array_map(fn($lang) => ['key' => $lang, 'value' => Helpers::get_language_name($lang)], $languages);

        // Social logins
        $socials = json_decode($settings['social_login'] ?? '[]', true);
        $social_login = array_map(fn($s) => [
            'login_medium' => $s['login_medium'],
            'status' => (bool) $s['status']
        ], $socials);

        $apples = json_decode($settings['apple_login'] ?? '[]', true);
        $apple_login = array_map(fn($a) => [
            'login_medium' => $a['login_medium'],
            'status' => (bool) $a['status'],
            'client_id' => $a['client_id']
        ], $apples);

        $module = Module::active()->take(2)->get();
        $module = $module->count() === 1 ? $module->first() : null;


        $is_live = $this->isLive;

        return [
            'business_name' => $settings['business_name'],
            'logo' => $settings['logo'],
            'address' => $settings['address'],
            'phone' => $settings['phone'],
            'email' => $settings['email_address'],
            'base_urls' => [
                'item_image_url' => $assetPath('product'),
                'refund_image_url' => $assetPath('refund'),
                'customer_image_url' => $assetPath('profile'),
                'banner_image_url' => $assetPath('banner'),
                'category_image_url' => $assetPath('category'),
                'review_image_url' => $assetPath('review'),
                'notification_image_url' => $assetPath('notification'),
                'store_image_url' => $assetPath('store'),
                'vendor_image_url' => $assetPath('vendor'),
                'store_cover_photo_url' => $assetPath('store/cover'),
                'delivery_man_image_url' => $assetPath('delivery-man'),
                'chat_image_url' => $assetPath('conversation'),
                'campaign_image_url' => $assetPath('campaign'),
                'business_logo_url' => $assetPath('business'),
                'order_attachment_url' => $assetPath('order'),
                'module_image_url' => $assetPath('module'),
                'parcel_category_image_url' => $assetPath('parcel_category'),
                'landing_page_image_url' => $baseUrl.'/public/assets/landing/image',
                'react_landing_page_images' => $assetPath('react_landing'),
                'react_landing_page_feature_images' => $assetPath('react_landing/feature'),
                'coupon_image_url' => $assetPath('coupon'),
            ],
            'country' => $settings['country'],
            'default_location' => [
                'lat' => $default_location['lat'] ?? '23.757989',
                'lng' => $default_location['lng'] ?? '90.360587'
            ],
            'currency_symbol' => translate('messages.currency_symbol'),
            'currency_symbol_direction' => $settings['currency_symbol_position'],
            'app_minimum_version_android' => (float)$settings['app_minimum_version_android'],
            'app_url_android' => $settings['app_url_android'],
            'app_minimum_version_ios' => (float)$settings['app_minimum_version_ios'],
            'app_url_ios' => $settings['app_url_ios'],
            'app_minimum_version_android_store' => (float)($settings['app_minimum_version_android_store'] ?? 0),
            'app_url_android_store' => $settings['app_url_android_store'] ?? null,
            'app_minimum_version_ios_store' => (float)($settings['app_minimum_version_ios_store'] ?? 0),
            'app_url_ios_store' => $settings['app_url_ios_store'] ?? null,
            'app_minimum_version_android_deliveryman' => (float)($settings['app_minimum_version_android_deliveryman'] ?? 0),
            'app_url_android_deliveryman' => $settings['app_url_android_deliveryman'] ?? null,
            'app_minimum_version_ios_deliveryman' => (float)($settings['app_minimum_version_ios_deliveryman'] ?? 0),
            'app_url_ios_deliveryman' => $settings['app_url_ios_deliveryman'] ?? null,
            'customer_verification' => (bool)$settings['customer_verification'],
            'prescription_order_status' => (bool)($settings['prescription_order_status'] ?? false),
            'schedule_order' => (bool)$settings['schedule_order'],
            'order_delivery_verification' => (bool)$settings['order_delivery_verification'],
            'cash_on_delivery' => (bool)($cod['status'] ?? false),
            'digital_payment' => (bool)($digital_payment['status'] ?? false),
            'per_km_shipping_charge' => (double)$settings['per_km_shipping_charge'],
            'minimum_shipping_charge' => (double)$settings['minimum_shipping_charge'],
            'free_delivery_over' => (float)($settings['free_delivery_over'] ?? 0),
            'demo' => (bool)(env('APP_MODE') === 'demo'),
            'maintenance_mode' => (bool)($settings['maintenance_mode'] ?? false),
            'order_confirmation_model' => config('order_confirmation_model'),
            'show_dm_earning' => (bool)$settings['show_dm_earning'],
            'canceled_by_deliveryman' => (bool)$settings['canceled_by_deliveryman'],
            'canceled_by_store' => (bool)$settings['canceled_by_store'],
            'timeformat' => (string)$settings['timeformat'],
            'language' => $lang_array,
            'social_login' => $social_login,
            'apple_login' => $apple_login,
            'toggle_veg_non_veg' => (bool)$settings['toggle_veg_non_veg'],
            'toggle_dm_registration' => (bool)$settings['toggle_dm_registration'],
            'toggle_store_registration' => (bool)$settings['toggle_store_registration'],
            'refund_active_status' => (bool)$settings['refund_active_status'],
            'schedule_order_slot_duration' => (int)$settings['schedule_order_slot_duration'],
            'digit_after_decimal_point' => (int)config('round_up_to_digit'),
            'module_config' => config('module'),
            'module' => $module,
            'parcel_per_km_shipping_charge' => (float)$settings['parcel_per_km_shipping_charge'],
            'parcel_minimum_shipping_charge' => (float)$settings['parcel_minimum_shipping_charge'],
            'landing_page_settings' => json_decode($settings['web_app_landing_page_settings'] ?? 'null', true),
            'social_media' => [],
            'footer_text' => $settings['footer_text'] ?? '',
            'fav_icon' => $settings['icon'],
            'landing_page_links' => json_decode($settings['landing_page_links'] ?? '[]'),
            'dm_tips_status' => (int)($settings['dm_tips_status'] ?? 0),
            'loyalty_point_exchange_rate' => (int)($settings['loyalty_point_exchange_rate'] ?? 0),
            'loyalty_point_item_purchase_point' => (float)($settings['loyalty_point_item_purchase_point'] ?? 0.0),
            'loyalty_point_status' => (int)($settings['loyalty_point_status'] ?? 0),
            'customer_wallet_status' => (int)($settings['wallet_status'] ?? 0),
            'ref_earning_status' => (int)($settings['ref_earning_status'] ?? 0),
            'ref_earning_exchange_rate' => (double)($settings['ref_earning_exchange_rate'] ?? 0),
            'refund_policy' => (int)((json_decode($settings['refund'] ?? '{}', true)['status'] ?? 0)),
            'cancelation_policy' => (int)(json_decode($settings['cancelation'] ?? '{}', true)['status'] ?? 0),
            'shipping_policy' => (int)(json_decode($settings['shipping_policy'] ?? '{}', true)['status'] ?? 0),
            'loyalty_point_minimum_point' => (int)($settings['loyalty_point_minimum_point'] ?? 0),
            'tax_included' => (int)($settings['tax_included'] ?? 0),
            'ar_general_stores_btn_title' => $landing->ar_general_stores_btn_title ?? '',
            'en_general_stores_btn_title' => $landing->en_general_stores_btn_title ?? '',
            'general_store_image' => $landing->general_store_image ?? '',
            'en_general_store_image' => $landing->en_general_store_image ?? '',
            'splash_video' => $landing->splash_video ?? '',
            'is_ramadan' => $landing->is_ramadan ?? '0',
            'ramadan_day' => DB::table('ramadan_days')->where('date', date('Y-m-d'))->first() ?? null,
            'current_orders' => $currentOrders ?? [],
            'is_logged_in' => (bool)$request->user('api'),
            'user_data' => $userData ?? null,
            'zone_info' => $zoneInfo ?? null,
            'is_live' => $is_live,
            'base_url' => $is_live ? 'https://postajji.com' : 'https://postajji.com/ios',
            'app_apple_store_link' => 'https://apps.apple.com/app/id6475656422',
            'app_google_store_link' => 'https://play.google.com/store/apps/details?id=com.syweb.postajji',
        ];
    }
}
