<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\AppSetting;
use Illuminate\Support\Facades\Storage;

class AppSettingController extends Controller
{
    public function index()
    {
        $settings = AppSetting::first();

        if (!$settings) {
            $settings = AppSetting::create([
                'app_name' => 'Taxi App',
                'driver_subscription_type' => 'percentage',
                'driver_subscription_value' => 10.00,
                'restaurant_subscription_type' => 'percentage',
                'restaurant_subscription_value' => 15.00,
                'gas_subscription_type' => 'percentage',
                'gas_subscription_value' => 12.00,
            ]);
        }

        return view('admin.settings.index', compact('settings'));
    }

    public function update(Request $request)
    {
        $request->validate([
            'app_name' => 'required|string|max:255',
            'app_email' => 'nullable|email',
            'app_description' => 'nullable|string',
            'app_about' => 'nullable|string',
            'app_icon' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
            'app_logo' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
            'driver_subscription_type' => 'required|in:percentage,monthly',
            'driver_subscription_value' => 'required|numeric|min:0',
            'driver_subscription_enabled' => 'boolean',
            'restaurant_subscription_type' => 'required|in:percentage,monthly',
            'restaurant_subscription_value' => 'required|numeric|min:0',
            'restaurant_subscription_enabled' => 'boolean',
            'gas_subscription_type' => 'required|in:percentage,monthly',
            'gas_subscription_value' => 'required|numeric|min:0',
            'gas_subscription_enabled' => 'boolean',
            'wallet_zain_cash_phone' => 'nullable|string|max:32',
            'wallet_topup_instructions' => 'nullable|string',
            'wallet_mastercard_instructions' => 'nullable|string',
            'wallet_aman_card_enabled' => 'boolean',
            'wallet_aman_card_instructions' => 'nullable|string',
            'cashback_enabled' => 'boolean',
            'cashback_base_percent' => 'nullable|numeric|min:0|max:100',
            'cashback_level_1_trips' => 'nullable|integer|min:1',
            'cashback_level_1_percent' => 'nullable|numeric|min:0|max:100',
            'cashback_level_2_trips' => 'nullable|integer|min:1',
            'cashback_level_2_percent' => 'nullable|numeric|min:0|max:100',
            'cashback_level_3_trips' => 'nullable|integer|min:1',
            'cashback_level_3_percent' => 'nullable|numeric|min:0|max:100',
            'cashback_rating_threshold' => 'nullable|numeric|min:0|max:5',
            'cashback_rating_bonus_percent' => 'nullable|numeric|min:0|max:100',
            'cashback_continuity_days' => 'nullable|integer|min:1',
            'cashback_continuity_bonus_percent' => 'nullable|numeric|min:0|max:100',
            'cashback_lock_days' => 'nullable|integer|min:1',
            'cashback_early_transfer_penalty_percent' => 'nullable|numeric|min:0|max:100',
            'cashback_referral_percent' => 'nullable|numeric|min:0|max:100',
            'cashback_referral_months' => 'nullable|integer|min:1',
            'services_banner_title' => 'nullable|string|max:255',
            'services_banner_subtitle' => 'nullable|string|max:500',
            'services_banner_body' => 'nullable|string|max:5000',
            'services_banner_cta_label' => 'nullable|string|max:120',
            'passenger_extra_service_delivery_fee' => 'nullable|numeric|min:0|max:1000000',
            'passenger_extra_service_app_fee' => 'nullable|numeric|min:0|max:600',
            'wheel_milestone_interval' => 'nullable|integer|min:1|max:100000',
            'wheel_winning_segment' => 'nullable|integer|min:1|max:12',
            'referral_withdraw_min_invitees' => 'nullable|integer|min:1|max:500',
            'referral_withdraw_min_orders_per_invitee' => 'nullable|integer|min:1|max:500',
        ]);

        $settings = AppSetting::first();

        if (!$settings) {
            $settings = new AppSetting();
        }

        // Handle file uploads
        if ($request->hasFile('app_icon')) {
            if ($settings->app_icon) {
                Storage::delete('public/' . $settings->app_icon);
            }
            $iconPath = $request->file('app_icon')->store('app', 'public');
            $settings->app_icon = $iconPath;
        }

        if ($request->hasFile('app_logo')) {
            if ($settings->app_logo) {
                Storage::delete('public/' . $settings->app_logo);
            }
            $logoPath = $request->file('app_logo')->store('app', 'public');
            $settings->app_logo = $logoPath;
        }

        $settings->fill($request->except(['app_icon', 'app_logo']));

        // حفظ حقول محفظة المطعم/الغاز/السائق صراحةً لضمان الكتابة في قاعدة البيانات
        $settings->wallet_zain_cash_phone = $request->input('wallet_zain_cash_phone');
        $settings->wallet_topup_instructions = $request->input('wallet_topup_instructions');
        $settings->wallet_mastercard_instructions = $request->input('wallet_mastercard_instructions');
        $settings->wallet_aman_card_enabled = $request->boolean('wallet_aman_card_enabled');
        $settings->wallet_aman_card_instructions = $request->input('wallet_aman_card_instructions');

        foreach (['cashback_enabled', 'cashback_base_percent', 'cashback_level_1_trips', 'cashback_level_1_percent',
            'cashback_level_2_trips', 'cashback_level_2_percent', 'cashback_level_3_trips', 'cashback_level_3_percent',
            'cashback_rating_threshold', 'cashback_rating_bonus_percent', 'cashback_continuity_days',
            'cashback_continuity_bonus_percent', 'cashback_lock_days', 'cashback_early_transfer_penalty_percent',
            'cashback_referral_percent', 'cashback_referral_months'] as $key) {
            if ($request->has($key)) {
                $settings->$key = $request->input($key);
            }
        }

        $settings->passenger_service_taxi_enabled = $request->boolean('passenger_service_taxi_enabled');
        $settings->passenger_service_food_enabled = $request->boolean('passenger_service_food_enabled');
        $settings->passenger_service_gas_enabled = $request->boolean('passenger_service_gas_enabled');
        $settings->services_banner_enabled = $request->boolean('services_banner_enabled');
        $settings->services_banner_title = $request->input('services_banner_title');
        $settings->services_banner_subtitle = $request->input('services_banner_subtitle');
        $settings->services_banner_body = $request->input('services_banner_body');
        $settings->services_banner_cta_label = $request->input('services_banner_cta_label');
        $settings->passenger_extra_service_delivery_fee = (float) ($request->input('passenger_extra_service_delivery_fee', 0));
        $settings->passenger_extra_service_app_fee = min(600, (float) ($request->input('passenger_extra_service_app_fee', 600)));

        if ($request->filled('wheel_milestone_interval')) {
            $settings->wheel_milestone_interval = max(1, (int) $request->input('wheel_milestone_interval'));
        }
        if ($request->filled('wheel_winning_segment')) {
            $settings->wheel_winning_segment = min(12, max(1, (int) $request->input('wheel_winning_segment')));
        }
        if ($request->filled('referral_withdraw_min_invitees')) {
            $settings->referral_withdraw_min_invitees = max(1, (int) $request->input('referral_withdraw_min_invitees'));
        }
        if ($request->filled('referral_withdraw_min_orders_per_invitee')) {
            $settings->referral_withdraw_min_orders_per_invitee = max(1, (int) $request->input('referral_withdraw_min_orders_per_invitee'));
        }

        $settings->save();

        return redirect()->route('admin.settings.index')->with('success', 'تم تحديث الإعدادات بنجاح');
    }
}
