<?php

namespace App\Http\Controllers\Admin;

use App\Helpers\ChatMessenger;
use App\Models\TradeGiftCard;
use App\Models\TradeRequests;
use App\Models\TradingCardDetails;
use App\Models\TransactionHistory;
use App\Models\User;
use App\Models\Deposit;
use Chatify\Facades\ChatifyMessenger as Chatify;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Transaction;
use App\Models\Wallet;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Response;

class ManageGiftcardTradesController extends Controller
{

    protected $perPage = 30;
    public function allTrade()
    {
        $search = request('search');
        $status = request('status');
        $trades = TradeRequests::join('merchants','trade_requests.send_to', '=', 'merchants.id')
            ->join('users','trade_requests.request_by', '=', 'users.id')
            ->join('trade_gift_cards','trade_requests.trade_id', '=', 'trade_gift_cards.id')->when($status,function($q) use($status){
            return $q->where('request_status',$status);
        })
        ->when($search,function($q) use($search){
            return $q->where('reference_no','like',"%$search%");
        })->select('trade_requests.*','merchants.name AS merchant_name','users.name',
                'trade_gift_cards.trade_descriptions','trade_gift_cards.total_amount','trade_gift_cards.reference_no')
        ->latest()->paginate(15);
       // dd($trades);
        return view('admin.manage_giftcard_trade.index', compact('trades','search'));
    }


    //view trades conversations
    public function viewTrade($id)
    {


        $id = $id;
        $chat = new ChatMessenger();
        $query = $chat->fetchMessagesQuery($id)->latest();
        $messages = $query->paginate($request->per_page ?? $this->perPage);
        $totalMessages = $messages->total();
        $lastPage = $messages->lastPage();
        $response = [
            'total' => $totalMessages,
            'last_page' => $lastPage,
            'last_message_id' => collect($messages->items())->last()->id ?? null,
            'messages' => '',
        ];

        // if there is no messages yet.
        if ($totalMessages < 1) {
            $response['messages'] ='<p class="message-hint center-el"><span>Say \'hi\' and start messaging</span></p>';
            return Response::json($response);
        }
        if (count($messages->items()) < 1) {
            $response['messages'] = '';
            return Response::json($response);
        }

        // $tradeRequest = TradeRequests::where('id',$id)->where('send_to',Auth::user()->id)->first();
//dd($tradeRequest);
        // $fetch = User::where('id', $tradeRequest->request_by)->first();
        $tradeRequest = TradeRequests::join('merchants','trade_requests.send_to', '=', 'merchants.id')
            ->join('users','trade_requests.request_by', '=', 'users.id')
            ->join('trade_gift_cards','trade_requests.trade_id', '=', 'trade_gift_cards.id')->where('trade_requests.id',$id)->select('trade_requests.*','merchants.name AS merchant_name','users.name',
                'trade_gift_cards.trade_descriptions','trade_gift_cards.total_amount','trade_gift_cards.reference_no')//->where('source','Giftcard')
            ->first();
        $tradeDetails = TradingCardDetails::where('trading_id', $tradeRequest->trade_id);
        $messenger_color = Auth::user()->messenger_color;
        //  echo $id;
        // dd($tradeDetails->get());
        return view('admin.manage_giftcard_trade.trade_chats.pages.app', [
            'id' => $id ?? 0,
            'tradeRequest' => $tradeRequest,
            'tradeDetails' => $tradeDetails->get(),
            'messages'=>$messages,
            'messengerColor' => $messenger_color ? $messenger_color : Chatify::getFallbackColor(),
            'dark_mode' => Auth::user()->dark_mode < 1 ? 'light' : 'dark', 'trade'
        ]);
    }

    public function approvalTransactionList()
    {
        $search = request('search');
        $status = request('status');
        $trades = TransactionHistory::join('merchants','transaction_histories.created_by', '=', 'merchants.id')
            ->join('users','transaction_histories.user_id', '=', 'users.id')
->where('transaction_histories.status','Pending')
            ->when($search,function($q) use($search){
                return $q->where('users.name','like',"%$search%");
            })->select('transaction_histories.*','merchants.name AS merchant_name','users.name')->where('source','Giftcard')
            ->latest()->paginate(15);
        // dd($trades);
        return view('admin.manage_giftcard_trade.approve_transaction', compact('trades','search'));
    }


    public function approve(Request $request)
    {
        $trans = TransactionHistory::where('id',$request->id)->where('status','pending')->where('source','Giftcard')->first();
       if($trans) {
           $trans->status = 'payout';
           $trans->status_at = now()->toDateTimeString();
           $trans->status_by = Auth()->user()->id;
           if ($trans->save()) {

               //  Auth()->user()->saveToClientWallet($trans->amount,$trans->user_id,'Balance', 'Giftcard','');
               $getWallet = Wallet::where('user_id', $trans->user_id)->first();
               $amount = $trans->amount;
               $pendingBalance = $getWallet->pending_balance;
               $getWallet->pending_balance = $pendingBalance - $amount;
               $walletBalance = $getWallet->balance;
               $getWallet->balance = $walletBalance + $amount;

               $getWallet->save();
           };
           if (!empty($trans->referer_user_id)) {
               Auth()->user()->saveToClientWallet($trans->refer_bonus, $trans->referer_user_id, 'Refer', 'Giftcard', $trans->user_id);
               saveReferTracking($trans->referer_user_id,'Giftcard',$trans->user_id,$trans->refer_bonus);
           }

           return back()->with('success', 'Payout has been approved');
       }else{
              return back()->with('error', 'Payout Failed to approved, Trade not in pending');
       }

    }


    public function reject(Request $request)
    {

        $trans = TransactionHistory::where('id',$request->id)->where('status','pending')->where('source','Giftcard')->first();
        $trans->status = 'decline';
        $trans->status_reason =  $request->reject_reason;
        $trans->status_at= now()->toDateTimeString();
        $trans->status_by = Auth()->user()->id;
        if($trans->save())

        return back()->with('success','Payout has been decline');

    }

    public function tradeTransactions()
    {
        $search = request('search');
        $status = request('status');
        $trades = TransactionHistory::join('merchants','transaction_histories.created_by', '=', 'merchants.id')
            ->join('users','transaction_histories.user_id', '=', 'users.id')

            ->when($search,function($q) use($search){
                return $q->where('users.name','like',"%$search%");
            })->select('transaction_histories.*','merchants.name AS merchant_name','users.name')->where('source','Giftcard')
            ->latest()->paginate(15);
        // dd($trades);
        return view('admin.manage_giftcard_trade.trade_transaction', compact('trades','search'));
    }

}
