<?php

use App\Models\Wallet;
use App\Models\WalletTransaction;
use App\Mail\AdminDepositMail;
use App\Mail\WalletTransactionMail;
use App\Services\DefaultCurrencyService;
use App\Services\Investment\SubscriptionService;
use App\Services\Sms\SmsAfrikasTalking;
use App\Traits\Vrm\Livewire\WithNotifications;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Sleep;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Layout;
use Livewire\Component;

return new #[Layout('layouts.trading')] class extends Component {
    use WithNotifications;

    public string $amount = '';
    public string $phoneNumber = '';
    public string $depositStep = 'form';
    public float $submittedDepositAmount = 0.0;
    public string $intent = '';
    public string $intentPackageId = '';
    public string $targetAmount = '';

    public function mount(): void
    {
        $this->useToasts();

        $amountFromQuery = request()->query('amount');
        if (is_string($amountFromQuery) && is_numeric($amountFromQuery) && (float) $amountFromQuery > 0) {
            $this->amount = number_format((float) $amountFromQuery, 2, '.', '');
        }

        $intentFromQuery = (string) request()->query('intent', '');
        if ($intentFromQuery === SubscriptionService::META_INTENT_SUBSCRIPTION) {
            $this->intent = $intentFromQuery;
            $this->intentPackageId = (string) request()->query('package_id', '');
            $this->targetAmount = (string) request()->query('target_amount', '');
        }
    }

    #[Computed]
    public function wallet(): Wallet
    {
        return Wallet::query()->firstOrCreate(['user_id' => auth()->id()], ['currency_code' => app(DefaultCurrencyService::class)->code()]);
    }

    /** System default currency from ATU (single currency across the app). */
    #[Computed]
    public function currencyCode(): string
    {
        return app(DefaultCurrencyService::class)->code();
    }

    #[Computed]
    public function requests()
    {
        return WalletTransaction::query()
            ->where('user_id', auth()->id())
            ->where('type', 'mpesa_deposit_request')
            ->latest()
            ->limit(10)
            ->get();
    }

    public function submitDepositRequest(): void
    {
        $this->validate([
            'amount' => 'required|numeric|min:100',
            'phoneNumber' => ['required', 'string', 'max:13', 'regex:/^(?:\+254|254|0)(?:7|1)\d{8}$/'],
        ]);

        $wallet = $this->wallet;
        $mpesaService = app(\App\Services\Payments\MpesaService::class);
        $normalizedPhone = $mpesaService->normalizePhoneNumber($this->phoneNumber);

        // Initiate STK Push
        $response = $mpesaService->stkPush(
            $normalizedPhone,
            (float) $this->amount,
            'Deposit-' . auth()->id(),
            'Wallet Deposit'
        );

        if (!$response['status']) {
            $this->notifyError($response['message'] ?: __('M-Pesa request failed. Please try again.'));
            return;
        }

        $stkData = $response['data'];

        $meta = [
            'channel' => 'mpesa',
            'phone_number' => $this->phoneNumber,
            'merchant_request_id' => $stkData['MerchantRequestID'] ?? null,
            'checkout_request_id' => $stkData['CheckoutRequestID'] ?? null,
        ];

        if ($this->intent === SubscriptionService::META_INTENT_SUBSCRIPTION && is_numeric($this->intentPackageId)) {
            $meta['intent'] = SubscriptionService::META_INTENT_SUBSCRIPTION;
            $meta['package_id'] = (int) $this->intentPackageId;
            $meta['amount'] = is_numeric($this->targetAmount) && (float) $this->targetAmount > 0 ? (float) $this->targetAmount : (float) $this->amount;
        }

        $transaction = WalletTransaction::query()->create([
            'wallet_id' => $wallet->id,
            'user_id' => auth()->id(),
            'type' => 'mpesa_deposit_request',
            'provider' => 'mpesa',
            'status' => 'pending',
            'amount' => (float) $this->amount,
            'currency_code' => app(DefaultCurrencyService::class)->code(),
            'description' => 'M-Pesa wallet deposit request',
            'phone_number' => $this->phoneNumber,
            'merchant_request_id' => $stkData['MerchantRequestID'] ?? null,
            'checkout_request_id' => $stkData['CheckoutRequestID'] ?? null,
            'transaction_code' => null,
            'meta' => $meta,
        ]);

        Mail::to('admin@fxinvest.io')->queue(new AdminDepositMail(
            auth()->user()->name,
            auth()->user()->email,
            (float) $transaction->amount,
            $transaction->currency_code,
            'submitted',
            'mpesa',
            $transaction->transaction_code,
        ));

        Mail::to(auth()->user()->email)->queue(new WalletTransactionMail(
            auth()->user()->name,
            'mpesa_deposit_request',
            $transaction->currency_code,
            (float) $transaction->amount,
            'pending',
            $transaction->phone_number,
            $transaction->transaction_code,
            $transaction->created_at?->format('M j, Y g:i A'),
        ));

        app(SmsAfrikasTalking::class)->sendShortMessage(
            $transaction->phone_number ?: auth()->user()->phone,
            "Deposit request submitted: {$transaction->currency_code} ".number_format((float) $transaction->amount, 2).'. Please enter your PIN on your phone.',
        );

        $this->submittedDepositAmount = (float) $this->amount;
        $this->depositStep = 'result';
        $this->intent = '';
        $this->intentPackageId = '';
        $this->targetAmount = '';

        $this->notifySuccess(__('STK Push sent to your phone.'));
    }

    public function resetDepositFlow(): void
    {
        $this->depositStep = 'form';
        $this->amount = '';
        $this->phoneNumber = '';
        $this->submittedDepositAmount = 0.0;
    }

    public function goToDashboard(): void
    {
        $this->redirectRoute('member.dashboard', navigate: true);
    }

    #[Computed]
    public function maskedPhoneNumber(): string
    {
        $digits = preg_replace('/\D+/', '', $this->phoneNumber);

        if (str_starts_with($digits, '254')) {
            $digits = '0' . substr($digits, 3);
        }

        if (str_starts_with($digits, '07') || str_starts_with($digits, '01')) {
            return substr($digits, 0, 2) . '****';
        }

        return '01****';
    }

    public function completePayment(): void
    {
        $this->redirectRoute('member.transactions', navigate: true);
    }

    protected function view($data = [])
    {
        return app('view')->file('/home1/xxwewbmy/zidii.fxinvest.io/storage/framework/views/livewire/views/bb29c245.blade.php', $data);
    }
}; 