<?php

namespace App\Http\Controllers;

use App\Models\IshareTopup;
use App\Models\OrderPayment;
use Illuminate\Http\Request;
use App\Models\AFAOrderPayment;
use App\Models\AdminIshareBalance;
use App\Models\IshareOrderPayment;
use Illuminate\Support\Facades\Log;
use App\Models\CommissionTransactions;
use App\Http\Integrations\Imake\iShareGhana;
use App\Http\Integrations\Imake\Requests\iShareGhana\ShareBundle;

class WebhookController extends Controller
{
    public function handleBulkClientWebhook(Request $request)
    {
        $requestData = $request->all();

        //  Log::info("Webhook received");

        $status = $requestData['status'];

        // Log::info("Data: " . json_encode($data));

        $externalRef = $requestData['transaction_id'];

        $parts = explode('-', $externalRef, 2);
        $prefix = $parts[0];
        $reference = $parts[1];

        // Log::info("Prefix: " . $prefix);
        // Log::info("Reference: " . $reference);

        switch ($prefix) {
            case 'OP':
                $orderPaymentReceipt = OrderPayment::where('transaction_id', $externalRef)->first();

                if (!$orderPaymentReceipt) {
                    Log::error("Order payment receipt not found");
                    return;
                }

                switch ($status) {
                    case 'success':
                        $orderPaymentReceipt->update([
                            'status' => 'completed'
                        ]);

                        $orderPaymentReceipt->order()->update([
                            'payment_status' => 'completed'
                        ]);

                        break;

                    case 'failed':
                        $orderPaymentReceipt->update([
                            'status' => 'failed',
                        ]);

                        $orderPaymentReceipt->order()->update([
                            'payment_status' => 'failed',
                        ]);
                        break;
                }
                break;

            case 'AT':
                $ishareOrder = IshareOrderPayment::where('transaction_id', $externalRef)->first();

                if (!$ishareOrder) {
                    Log::error("Ishare order not found");
                    return;
                }

                switch ($status) {
                    case 'success':
                        if ($ishareOrder->status == 'completed') {
                            return;
                        }

                        $ishareOrder->update([
                            'status' => 'completed'
                        ]);

                        $order = $ishareOrder->order;
                        $capacityInGb = $order->capacity / 1000;

                        $api = new iShareGhana();
                        $request = new ShareBundle($order->recipient, $capacityInGb, $order->reference);
                        $response = $api->send($request);
                        // dd($response->json());

                        if ($response->successful()) {
                            $order->update([
                                'status' => 'completed',
                                'api_status' => 'completed',
                            ]);

                            //update user balance
                            $order->user->ishareWallet->update([
                                'balance' => $order->user->ishareWallet->balance - $order->capacity,
                            ]);

                            //create transaction
                            IshareTopup::create([
                                'user_id' => $order->user->id,
                                'ishare_id' => $order->user->ishareWallet->id,
                                'capacity' => $order->capacity,
                                'price' => $ishareOrder->amount,
                                'current_capacity' => $order->user->ishareWallet->balance + $order->capacity,
                                'new_capacity' => $order->user->ishareWallet->balance,
                                'narration' => 'Data Transfer to ' . $order->recipient,
                                'payment_mode' => 'momo',
                                'payment_status' => 'completed',
                                'transaction_id' => $order->reference,
                                'type' => 'debit',
                                'status' => 'completed',
                            ]);

                            //update admin allocated balance
                            $admin = AdminIshareBalance::first();
                            $admin->allocated -= $order->capacity;
                            $admin->save();

                            if ($order->is_customer) {
                                $commission = $ishareOrder->amount;

                                // Check if commission transaction already exists for this order
                                $existingTransaction = CommissionTransactions::whereHas('ishareTransaction', function ($query) use ($order) {
                                    $query->where('order_id', $order->id);
                                })->first();

                                if (!$existingTransaction) {
                                    $commissionTransaction = CommissionTransactions::create([
                                        'user_id' => $order->user->id,
                                        'wallet_id' => $order->user->commissionWallet->id,
                                        'amount' => $commission,
                                        'status' => 'completed',
                                        'narration' => 'Commission from iShare Order # ' . $order->id,
                                        'order_id' => null,
                                        'current_bal' => $order->user->commissionWallet->balance,
                                        'new_bal' => $order->user->commissionWallet->balance + $commission,
                                    ]);

                                    $commissionTransaction->ishareTransaction()->create([
                                        'transaction_id' => $commissionTransaction->id,
                                        'order_id' => $order->id,
                                        'status' => 'completed',
                                    ]);

                                    $order->user->commissionWallet->increment('balance', $commission);
                                }
                            }
                        } else {
                            $order->update([
                                'api_status' => 'failed',
                                'status' => 'failed',
                            ]);
                        }

                        break;

                    case 'failed':
                        $ishareOrder->update([
                            'status' => 'failed',
                        ]);
                        break;
                }
                break;

            case 'AF':
                $afaRegistrationReceipt = AFAOrderPayment::where('transaction_id', $externalRef)->first();

                if (!$afaRegistrationReceipt) {
                    Log::error("AFA registration receipt not found");
                    return;
                }

                switch ($status) {
                    case 'success':
                        $afaRegistrationReceipt->update([
                            'status' => 'completed'
                        ]);

                        $afaRegistrationReceipt->registration()->update([
                            'payment_status' => 'completed'
                        ]);

                        break;

                    case 'failed':
                        $afaRegistrationReceipt->update([
                            'status' => 'failed',
                        ]);
                        break;
                }
                break;
        }
    }
}