<?php

namespace App\Http\Controllers;

use App\Models\Funding;
use App\Models\WalletAddress;
use App\Models\FundingChat;
use App\Models\FundingMessage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Notifications\GeneralNotification;
use App\Services\AdminNotificationService;

class FundingController extends Controller
{
    public function verifyCode($qty){
        $acc_num = '';
        $nums = collect([0,2,5,8,9,4,3,6,7,1]);

        $random = $nums->shuffle()->random($qty);
        foreach ($random->all() as $number) {
           $acc_num .= $number;
        }
        return $acc_num;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function spotTransfer(Request $request)
    {
        $request->validate([
            'from_coin' => 'required',
            'to_coin' => 'required',
            'amount' => 'required'
        ]);

        switch ($request->from_coin) {
            case 'Withdrawable Balance':
                $balance = Auth::user()->withdrawableBalance();
                break;

            case 'Funding Wallet':
                $balance = Auth::user()->balance();
                break;

            case 'Referral Wallet':
                $balance = Auth::user()->referralEarning();
                break;
            
            default:

            $balance = Auth::user()->getCoinBalance($request->from_coin);
           
            break;
        }

        
        if ($balance < $request->amount) {
            return response()->json([
                'status' => 'error',
                'message' => 'insufficient funds in your '.$request->from_coin.' balance'
            ], 400);
        }

        $funding = new Funding;
        $funding->user_id = Auth::id();
        $funding->amount = $request->amount;
        $funding->status = 'successful';
        $funding->gateway = $request->to_coin;
        $funding->transaction_id = $this->verifyCode(10);
        $funding->save();

        $funding = new Funding;
        $funding->user_id = Auth::id();
        $funding->amount = -$request->amount;
        $funding->status = 'successful';
        $funding->gateway = $request->from_coin;
        $funding->transaction_id = $this->verifyCode(10);
        $funding->save();

        return response()->json([
            'status' => 'success',
            'message' => 'transfer was successful',
        ], 200);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'amount' => 'required',
            'gateway' => 'required',
            'transaction_id' => 'required',
        ]);

        $funding = new Funding;
        $funding->user_id = Auth::id();
        $funding->amount = $request->amount;
        $funding->status = 'successful';
        $funding->gateway = $request->gateway;
        $funding->transaction_id = $request->transaction_id;
        $funding->save();

        // Send admin notification about new funding request
        AdminNotificationService::newFundingRequest($funding);

        $fundings = Funding::orderByDesc('id')->where('user_id', (int)Auth::id())->get()->load(['advertiser']);
        $balance = Auth::user()->balance();
        $subscriptionBalance = Auth::user()->subscriptionBalance();
        $referralBalance = Auth::user()->referralEarning();

        return response()->json([
            'status' => 'success',
            'message' => 'account funded successfully',
            'fundings' => $fundings,
            'balance' => $balance,
            'subscriptionBalance' => $subscriptionBalance,
            'referralBalance' => $referralBalance
        ], 200);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Funding  $funding
     * @return \Illuminate\Http\Response
     */
    public function show(Funding $funding)
    {
        $fundings = Funding::orderByDesc('id')->where('user_id', (int)Auth::id())->get()->load(['advertiser']);
        $balance = Auth::user()->balance();
        $subscriptionBalance = Auth::user()->subscriptionBalance();
        $referralBalance = Auth::user()->referralEarning();

        $withdrawableBalance = Auth::user()->withdrawableBalance();

        return response()->json([
            'status' => 'success',
            'message' => 'successful',
            'fundings' => $fundings,
            'balance' => $balance,
            'subscriptionBalance' => $subscriptionBalance,
            'referralBalance' => $referralBalance,
            'withdrawableBalance' => $withdrawableBalance
        ],200);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Funding  $funding
     * @return \Illuminate\Http\Response
     */
    public function list(Funding $funding)
    {
        $fundings = $funding->orderByDesc('id')->take(50)->get()->load(['user', 'advertiser']);
        return response()->json([
            'status' => 'success',
            'message' => 'fundings loaded successfully',
            'fundings' => $fundings
        ], 200);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Funding  $funding
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Funding $funding)
    {
        $request->validate([
            'amount' => 'required',
            'coin' => 'required',
        ]);

        $address = WalletAddress::find($request->coin);
        if (!$address) {
            return response()->json([
                'status' => 'error',
                'message' => 'invalid payment method',
            ], 400);
        }

        $funding = new Funding;

        if ($request->has('wallet_name')) {
            $funding->wallet_name = $request->wallet_name;

            if ($request->has('wallet_address')) {
                $funding->wallet_address = $request->wallet_address;
            }
        }

        $funding->user_id = Auth::id();
        $funding->amount = $request->amount;
        $funding->status = 'processing';
        $funding->wallet_address_id = $request->coin;
        $funding->gateway = $address->coin_name;
        $funding->transaction_id = $this->verifyCode(10);
        $funding->save();

        // Create a funding chat for this funding if it's a P2P transaction
        if (!is_null($address->trader_name)) {
            // Create a chat
            $chat = FundingChat::create([
                'user_id' => Auth::id(),
                'payment_method' => $address->payment_description ?? 'Bank Transfer',
                'status' => 'active',
                'funding_id' => $funding->id
            ]);

            // Update funding with the chat ID
            $funding->chat_id = $chat->id;
            $funding->save();

            // Create a system message to start the conversation
            FundingMessage::create([
                'chat_id' => $chat->id,
                'sender_id' => null, // Null sender indicates system message
                'message' => 'Transaction has been initiated. You can chat with the other party here.',
                'is_system' => true
            ]);
            
            // Notify admins about the new P2P transaction
            $this->notifyAdminOfP2PTransaction($funding, Auth::user());
        }

        if (!$address->trader_name === null) {
            $notification_deposit = [
                'title' => 'P2P Transaction Initiated',
                'url' => '/',
                'content' =>  '💰 P2P Transaction Initiated',
                'mail_content' => "Dear ". $funding->user->name. ", <br/> This is to notify you that your P2P transaction of $".number_format($funding->amount, 2, '.', ',')." has been successfully registered, check your account for the payment details of the advertiser to complete this payment.<br/> Below is the details of this transaction: <br/><br/> 
                <p style='text-align:left;'>
                <p><strong>Advertiser:</strong> ". $address->trader_name."</p>
                <p><strong>Gateway:</strong> ". $address->payment_description ."</p>
                <p><strong>Amount:</strong> $". number_format($funding->amount, 2, '.', ',') ."</p> 
                <p><strong>Transaction:</strong> ". $funding->transaction_id ."</p> 
                <p><strong>Payment Link:</strong> https://dashboard.amdconsults.com/payment/".$funding->id ."</p> 
                <p><strong>Date:</strong> ". $funding->created_at->format('d-m-Y') ."</p>
                <br/> Regards<br/> AMD CONSULTING  <br/> <br/><br/><br/><strong>If you  didn't initiate the above transaction kindly contact our support for security checks on your account. Thank you </strong></p>         
                ",
            ];
        } else {
            $notification_deposit = [
                'title' => 'Deposit Registered 💰',
                'url' => '/',
                'content' =>  'Deposit Registered 💰',
                'mail_content' => "Dear ". $funding->user->name. ", <br/> This is to notify you that your deosit of $".number_format($funding->amount, 4, '.', ',')." has been successfully registered, Kindly wait for admin's approval of your request as you review the details of your funding details below: <br/><br/> 
                <p style='text-align:left;'>
                <p><strong>Trader Name:</strong> ". $funding->user->name ."</p>
                <p><strong>Deposit Gateway:</strong> ". $funding->gateway ."</p>
                <p><strong>Amount:</strong> $". number_format($funding->amount) ."</p> 
                <p><strong>Transaction:</strong> ". $funding->transaction_id ."</p> 
                <p><strong>Date:</strong> ". $funding->created_at->format('d-m-Y') ."</p>
                <br/> Regards<br/> AMD CONSULTING  <br/> <br/><br/><br/><strong>If you  didn't initiate the above transaction kindly disregard. Thank you </strong></p>         
                ",
            ];
        }
        

            $ref_activity = (object)$notification_deposit;
            // $funding->user->notify(new GeneralNotification($ref_activity));

            // notify admin too

        $fundings = Funding::orderByDesc('id')->where('user_id', (int)Auth::id())->get()->load(['advertiser']);

        return response()->json([
            'status' => 'success',
            'message' => 
            $funding->wallet_name != null ?
                'order submitted successfully, make sure you receive payment before you confirm this order' :
            'order submitted successfully, kindly make your payment to the provided details to complete this transaction',
            'fundings' => $fundings,
            'funding' => $funding
        ], 200);
    }

       /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Funding  $funding
     * @return \Illuminate\Http\Response
     */
    public function confirm(Request $request, Funding $funding)
    {
        $request->validate([
            'coin' => 'required',
        ]);

       

        $funding = Funding::find($request->coin);
        if (!$funding) {
            return response()->json([
                'status' => 'error',
                'message' => 'invalid request',
            ], 400);
        }

        $address = $funding->advertiser;
        if (!$address) {
            return response()->json([
                'status' => 'error',
                'message' => 'invalid payment method',
            ], 400);
        }
        
        $funding->status =
        $funding->wallet_name != null ? 'approved' :
        'awaiting confirmation';

        $funding->amount = $funding->wallet_name != null ? -$funding->amount : $funding->amount;
        $funding->save();

        // Add a system message to the chat if this is a P2P transaction and has a chat
        if ($funding->chat) {
            FundingMessage::create([
                'chat_id' => $funding->chat->id,
                'sender_id' => null, // Null sender indicates system message
                'message' => 'Payment has been confirmed by the ' . ($funding->wallet_name != null ? 'seller' : 'buyer') . '.',
                'is_system' => true
            ]);
        }

        if (!$address->trader_name === null) {
            $notification_deposit = [
                'title' => 'Confirm P2P Transaction',
                'url' => '/',
                'content' =>  '💰 Confirm P2P Transaction',
                'mail_content' => "Dear ". $funding->user->name. ", <br/> This is to notify you that your P2P transaction of $".number_format($funding->amount, 2, '.', ',')." has been successfully registered, check your account for the payment details of the advertiser to complete this payment.<br/> Below is the details of this transaction: <br/><br/> 
                <p style='text-align:left;'>
                <p><strong>Advertiser:</strong> ". $address->trader_name."</p>
                <p><strong>Gateway:</strong> ". $address->payment_description ."</p>
                <p><strong>Amount:</strong> $". number_format($funding->amount, 2, '.', ',') ."</p> 
                <p><strong>Transaction:</strong> ". $funding->transaction_id ."</p> 
                <p><strong>Payment Link:</strong> https://dashboard.amdconsults.com/payment/".$funding->id ."</p> 
                <p><strong>Date:</strong> ". $funding->created_at->format('d-m-Y') ."</p>
                <br/> Regards<br/> AMD CONSULTING  <br/> <br/><br/><br/><strong>If you  didn't initiate the above transaction kindly contact our support for security checks on your account. Thank you </strong></p>         
                ",
                ];
        }else {
            $notification_deposit = [
                'title' => 'Deposit Registered 💰',
                'url' => '/',
                'content' =>  'Deposit Registered 💰',
                'mail_content' => "Dear ". $funding->user->name. ", <br/> This is to notify you that your deosit of $".number_format($funding->amount, 4, '.', ',')." has been successfully registered, Kindly wait for admin's approval of your request as you review the details of your funding details below: <br/><br/> 
                <p style='text-align:left;'>
                <p><strong>Trader Name:</strong> ". $funding->user->name ."</p>
                <p><strong>Deposit Gateway:</strong> ". $funding->gateway ."</p>
                <p><strong>Amount:</strong> $". number_format($funding->amount) ."</p> 
                <p><strong>Transaction:</strong> ". $funding->transaction_id ."</p> 
                <p><strong>Date:</strong> ". $funding->created_at->format('d-m-Y') ."</p>
                <br/> Regards<br/> AMD CONSULTING  <br/> <br/><br/><br/><strong>If you  didn't initiate the above transaction kindly disregard. Thank you </strong></p>         
                ",
                ];
        }
        

            $ref_activity = (object)$notification_deposit;
            // $funding->user->notify(new GeneralNotification($ref_activity));

            // notify admin too

        $fundings = Funding::orderByDesc('id')->where('user_id', (int)Auth::id())->get()->load(['advertiser']);

        return response()->json([
            'status' => 'success',
            'message' => 'please wait while your order is being confirmed',
            'fundings' => $fundings,
            'funding' => $funding
        ], 200);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Funding  $funding
     * @return \Illuminate\Http\Response
     */
    public function approve(Request $request)
    {
        $request->validate([
            'funding_id' => 'required',
            'funding_status' => 'required'
        ]);

        $funding = Funding::find($request->funding_id);
        if (!$funding) {
            return response()->json([
                'status' => 'error',
                'message' => 'invalid request',
            ], 400);
        }

        $funding->status = $request->funding_status;
        $funding->save();

        // send a mail
        $notification_completed = [
            'title' => 'funding  '.$funding->status,
            'url' => '/',
            'content' =>  'funding '.$funding->status,

            'mail_content' => "Dear ". $funding->user->name. ", <br/> This is to notify you that your funding of ".number_format($funding->amount, 4, '.', ',').". has been updated as $funding->status, you can review the details of your funding below: <br/><br/> 
            <p style='text-align:left;'>

            <p><strong>Investor:</strong> ". $funding->user->name ."</p>
            <p><strong>Amount:</strong> $". number_format($funding->amount) ."</p> 
            <p><strong>Date:</strong> ". $funding->created_at->format('d-m-Y') ."</p>            
            <br/> Regards<br/> AMD CONSULTING  <br/> <br/><br/><br/><strong>If you  didn't initiate the above transaction kindly disregard. Thank you </strong></p>         
            ",
            ];

            $ref_activity = (object)$notification_completed;
            $funding->user->notify(new GeneralNotification($ref_activity));

        return response()->json([
            'status' => 'success',
            'message' => 'deposit status updated successfully',
        ], 200);
    }

    /**
     * Add a notifyAdminOfP2PTransaction method that will find all admin users and send them notifications
     * This method should be called after a P2P transaction is saved
     * It should accept a funding and user parameter
     */

    private function notifyAdminOfP2PTransaction($funding, $user)
    {
        // Find all admin users
        $adminRoles = \App\Models\Role::where('role', 'admin')->get();
        
        foreach ($adminRoles as $adminRole) {
            $admin = \App\Models\User::find($adminRole->user_id);
            
            if ($admin) {
                // Send email notification
                $admin->notify(new \App\Notifications\AdminP2PTransactionNotification($funding, $user));
                
                // Send push notification to admin
                $title = 'New P2P Transaction';
                $message = $user->name . ' has initiated a P2P transaction of $' . $funding->amount;
                $image = '';
                $action = '/admin/fundings';
                
                $admin->pushMessage($title, $message, $image, $action);
            }
        }
    }
}
