<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\AppSetting;

class AppSettingController extends Controller
{
    /**
     * عرض إعدادات التطبيق
     */
    public function index()
    {
        try {
            $settings = AppSetting::first();

            if (!$settings) {
                return response()->json([
                    'success' => false,
                    'message' => 'لم يتم العثور على إعدادات التطبيق',
                    'data' => null
                ], 404);
            }

            return response()->json([
                'success' => true,
                'message' => 'تم جلب إعدادات التطبيق بنجاح',
                'data' => [
                    'app_name' => $settings->app_name,
                    'app_email' => $settings->app_email,
                    'app_description' => $settings->app_description,
                    'app_about' => $settings->app_about,
                    'app_icon' => $settings->app_icon ? asset('storage/' . $settings->app_icon) : null,
                    'app_logo' => $settings->app_logo ? asset('storage/' . $settings->app_logo) : null,
                    'subscriptions' => [
                        'driver' => [
                            'type' => $settings->driver_subscription_type,
                            'value' => $settings->driver_subscription_value,
                            'enabled' => $settings->driver_subscription_enabled,
                        ],
                        'restaurant' => [
                            'type' => $settings->restaurant_subscription_type,
                            'value' => $settings->restaurant_subscription_value,
                            'enabled' => $settings->restaurant_subscription_enabled,
                        ],
                        'gas' => [
                            'type' => $settings->gas_subscription_type,
                            'value' => $settings->gas_subscription_value,
                            'enabled' => $settings->gas_subscription_enabled,
                        ],
                    ],
                    'passenger_services' => [
                        'taxi_enabled' => (bool) ($settings->passenger_service_taxi_enabled ?? true),
                        'food_enabled' => (bool) ($settings->passenger_service_food_enabled ?? true),
                        'gas_enabled' => (bool) ($settings->passenger_service_gas_enabled ?? true),
                    ],
                    'services_banner' => [
                        'enabled' => (bool) ($settings->services_banner_enabled ?? true),
                        'title' => $settings->services_banner_title,
                        'subtitle' => $settings->services_banner_subtitle,
                        'body' => $settings->services_banner_body,
                        'cta_label' => $settings->services_banner_cta_label,
                        'extra_service_delivery_fee' => (float) ($settings->passenger_extra_service_delivery_fee ?? 0),
                        'extra_service_app_fee' => min(600, (float) ($settings->passenger_extra_service_app_fee ?? 600)),
                    ],
                    'promo_wheel' => [
                        'interval' => (int) ($settings->wheel_milestone_interval ?? 250),
                        'winning_segment' => (int) ($settings->wheel_winning_segment ?? 12),
                        'global_completed_orders' => (int) ($settings->global_completed_orders_count ?? 0),
                    ],
                    'referral_withdrawal_rules' => [
                        'min_qualified_invitees' => (int) ($settings->referral_withdraw_min_invitees ?? 60),
                        'min_orders_per_invitee' => (int) ($settings->referral_withdraw_min_orders_per_invitee ?? 10),
                    ],
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'حدث خطأ أثناء جلب الإعدادات',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * حساب رسوم الاشتراك
     */
    public function calculateSubscription(Request $request)
    {
        try {
            $request->validate([
                'service_type' => 'required|in:driver,restaurant,gas',
                'amount' => 'required|numeric|min:0',
            ]);

            $settings = AppSetting::first();

            if (!$settings) {
                return response()->json([
                    'success' => false,
                    'message' => 'لم يتم العثور على إعدادات التطبيق',
                    'data' => null
                ], 404);
            }

            $subscriptionField = $request->service_type . '_subscription_';
            $type = $subscriptionField . 'type';
            $value = $subscriptionField . 'value';
            $enabled = $subscriptionField . 'enabled';

            if (!$settings->$enabled) {
                return response()->json([
                    'success' => true,
                    'message' => 'الاشتراك غير مفعل لهذه الخدمة',
                    'data' => [
                        'subscription_fee' => 0,
                        'total_amount' => $request->amount,
                        'subscription_type' => null,
                        'subscription_value' => 0
                    ]
                ]);
            }

            $subscriptionFee = 0;
            if ($settings->$type === 'percentage') {
                $subscriptionFee = ($request->amount * $settings->$value) / 100;
            } else {
                $subscriptionFee = $settings->$value;
            }

            return response()->json([
                'success' => true,
                'message' => 'تم حساب رسوم الاشتراك بنجاح',
                'data' => [
                    'subscription_fee' => round($subscriptionFee, 2),
                    'total_amount' => $request->amount,
                    'final_amount' => round($request->amount + $subscriptionFee, 2),
                    'subscription_type' => $settings->$type,
                    'subscription_value' => $settings->$value
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'حدث خطأ أثناء حساب رسوم الاشتراك',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}
