<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\AppSetting;
use App\Services\DriverCashbackService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class DriverCashbackController extends Controller
{
    /**
     * عرض محفظة الكاش باك
     */
    public function index(): JsonResponse
    {
        $user = Auth::user();
        if (!$user || $user->user_type !== 'driver') {
            return response()->json(['success' => false, 'message' => 'يجب تسجيل الدخول كسائق'], 401);
        }

        $settings = AppSetting::first();
        $cashbackEnabled = (bool) ($settings->cashback_enabled ?? true);

        if (!$cashbackEnabled) {
            return response()->json([
                'success' => true,
                'data' => [
                    'enabled' => false,
                    'message' => 'نظام الكاش باك غير مفعّل حالياً',
                ],
            ], 200, [], JSON_UNESCAPED_UNICODE);
        }

        $wallet = DriverCashbackService::getOrCreateWallet((int) $user->id);
        $wallet->load('transactions');

        $lockDays = (int) ($settings->cashback_lock_days ?? 30);
        $availableAt = $wallet->first_deposit_at
            ? $wallet->first_deposit_at->copy()->addDays($lockDays)
            : null;

        return response()->json([
            'success' => true,
            'data' => [
                'enabled' => true,
                'balance' => (float) $wallet->balance,
                'currency' => 'IQD',
                'can_transfer' => $wallet->canTransfer(),
                'available_at' => $availableAt?->toIso8601String(),
                'consecutive_days' => (int) $wallet->consecutive_days,
                'rules' => [
                    'base_percent' => (float) ($settings->cashback_base_percent ?? 4),
                    'level_1' => ['trips' => (int) ($settings->cashback_level_1_trips ?? 5), 'percent' => (float) ($settings->cashback_level_1_percent ?? 5)],
                    'level_2' => ['trips' => (int) ($settings->cashback_level_2_trips ?? 10), 'percent' => (float) ($settings->cashback_level_2_percent ?? 6)],
                    'level_3' => ['trips' => (int) ($settings->cashback_level_3_trips ?? 15), 'percent' => (float) ($settings->cashback_level_3_percent ?? 8)],
                    'rating_bonus' => (float) ($settings->cashback_rating_bonus_percent ?? 1),
                    'continuity_bonus' => (float) ($settings->cashback_continuity_bonus_percent ?? 2),
                    'lock_days' => $lockDays,
                    'early_penalty' => (float) ($settings->cashback_early_transfer_penalty_percent ?? 20),
                ],
                'transactions' => $wallet->transactions->take(20)->map(fn ($t) => [
                    'id' => $t->id,
                    'type' => $t->type,
                    'amount' => (float) $t->amount,
                    'description' => $t->description,
                    'created_at' => $t->created_at->toIso8601String(),
                ])->values(),
            ],
        ], 200, [], JSON_UNESCAPED_UNICODE);
    }

    /**
     * تحويل الكاش باك للمحفظة الرئيسية
     */
    public function transferToWallet(): JsonResponse
    {
        $user = Auth::user();
        if (!$user || $user->user_type !== 'driver') {
            return response()->json(['success' => false, 'message' => 'يجب تسجيل الدخول كسائق'], 401);
        }

        $result = DriverCashbackService::transferToMainWallet((int) $user->id);

        if (!$result['success']) {
            return response()->json([
                'success' => false,
                'message' => $result['message'],
            ], 422, [], JSON_UNESCAPED_UNICODE);
        }

        return response()->json([
            'success' => true,
            'message' => $result['message'],
            'data' => [
                'amount' => $result['amount'],
                'penalty' => $result['penalty'] ?? 0,
            ],
        ], 200, [], JSON_UNESCAPED_UNICODE);
    }

    /**
     * الحصول على كود دعوة السائق أو إنشاؤه
     */
    public function getReferralCode(): JsonResponse
    {
        $user = Auth::user();
        if (!$user || $user->user_type !== 'driver') {
            return response()->json(['success' => false, 'message' => 'يجب تسجيل الدخول كسائق'], 401);
        }

        $existing = \App\Models\DriverReferralCode::where('driver_id', $user->id)->first();
        if ($existing) {
            return response()->json([
                'success' => true,
                'data' => [
                    'referral_code' => $existing->code,
                    'message' => 'كود الدعوة الخاص بك',
                ],
            ], 200, [], JSON_UNESCAPED_UNICODE);
        }

        $code = \App\Models\DriverReferralCode::generateUnique();
        \App\Models\DriverReferralCode::create([
            'driver_id' => $user->id,
            'code' => $code,
        ]);

        return response()->json([
            'success' => true,
            'data' => [
                'referral_code' => $code,
                'message' => 'تم إنشاء كود الدعوة - ادعُ سائقين واحصل على 5% من رحلاتهم لمدة شهر',
            ],
        ], 200, [], JSON_UNESCAPED_UNICODE);
    }
}
