<?php

namespace App\Http\Controllers\Merchant;

use App\Helpers\ChatMessenger;
use App\Models\Merchant;
use App\Models\TradeGiftCard;
use App\Models\TradeRequests;
use App\Models\TradingCardDetails;
use App\Models\TradingMessage;
use App\Models\TransactionHistory;
use App\Models\User;
use Chatify\Facades\ChatifyMessenger as Chatify;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Response;
use Image;
use App\Models\Module;
use App\Models\Wallet;
use App\Models\KycForm;
use App\Models\ApiCreds;
use App\Models\Transaction;
use App\Models\Withdrawals;
use Illuminate\Support\Str;
use App\Helpers\MediaHelper;
use Illuminate\Http\Request;
use App\Models\Generalsetting;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;

class MerchantController extends Controller
{
    public $chat;
    protected $perPage = 30;

    public function __construct()
    {
        $this->chat = new ChatMessenger();
    }

    public function dashboard()
    {
        $messenger_color = Auth::user()->messenger_color;
        $tradeDetails = null;
        $tradeRequest = TradeRequests::where('send_to', Auth()->user()->id)->where('request_status', 'Pending')->get();
        return view('merchant.giftcard.chat.pages.app', [
            'id' => $id ?? 0,
            'messengerColor' => $messenger_color ? $messenger_color : Chatify::getFallbackColor(),
            'dark_mode' => Auth::user()->dark_mode < 1 ? 'light' : 'dark',
            'tradeDetails' => null,
            'tradeRequest' => $tradeRequest
        ]);
    }

    public function trading($id)
    {

        $tradeRequest = TradeRequests::where('id',$id)->where('send_to',Auth::user()->id)->first();
        if(empty($tradeRequest)){
            abort(404, 'Item not found');
        }
        //  $fetch = Merchant::where('id', $tradeRequest->request_by)->first();
        // $tradeRequest = TradeRequests::where('id',$id)->where('request_id',Auth::user()->id)->first();
        $tradeDetails = TradingCardDetails::where('trading_id',$tradeRequest->trade_id);
        $messenger_color = Auth::user()->messenger_color;
        $users = TradeRequests::join('users','trade_requests.request_by', '=', 'users.id')
            ->where('trade_requests.send_to',Auth()->user()->id)->where('trade_requests.request_status')
            ->select('users.name','users.active_status','users.avatar','users.email','trade_requests.*')
            //->orderBy('max_created_at', 'desc')
            //->groupBy('trade_requests.id')
            ->paginate(10);
        $usersList = $users->items();

        if (count($usersList) > 0) {
            $contacts = '';
            foreach ($usersList as $user) {

                $contacts .= $this->chat->getContactItem($user);
                //  dd($contacts);
            }


        } else {
            $contacts = '<p class="message-hint center-el"><span>Your contact list is empty</span></p>';
        }

        //  echo $id;
        // dd($tradeDetails->get());
        return view('merchant.giftcard.chat.pages.app', [
            'id' => $id ?? 0,
            'tradeRequest'=>$tradeRequest,
            'tradeDetails'=>$tradeDetails->get(),
            'messengerColor' => $messenger_color ? $messenger_color : Chatify::getFallbackColor(),
            'dark_mode' => Auth::user()->dark_mode < 1 ? 'light' : 'dark','contacts'=>$contacts,
            'clientId'=>Auth::user()->getUserAccessKey($tradeRequest->request_by)
        ]);

    }

    /**
     * Get favorites list
     *
     * @param Request $request
     * @return JsonResponse|void
     */
    public function getTradeRequest(Request $request)
    {
        $tradeRequestList = null;
        $tradeRequests = TradeRequests::where('send_to', Auth::user()->id)->where('request_status', 'Pending');

        foreach ($tradeRequests->get() as $tradeRequest) {
            // get user data
            $user = User::where('id', $tradeRequest->request_by)->first();
            $tradeRequestList .= view('merchant.giftcard.chat.layouts.trade_request_list', [
                'user' => $user,
                'tradeRequestId' => $tradeRequest->id
            ]);
        }
        // send the response
        return Response::json([
            'count' => $tradeRequests->count(),
            'favorites' => $tradeRequests->count() > 0
                ? $tradeRequestList
                : 0,
        ], 200);
    }

    /**
     * Get shared photos
     *
     * @param Request $request
     * @return JsonResponse|void
     */
    public function sharedPhotos(Request $request)
    {
        $shared = $this->chat->getSharedPhotos($request['user_id']);
        $sharedPhotos = null;

        // shared with its template
        for ($i = 0; $i < count($shared); $i++) {
            $sharedPhotos .= view('merchant.giftcard.chat.layouts.listItem', [
                'get' => 'sharedPhoto',
                'image' => $this->chat->getAttachmentUrl($shared[$i]),
            ])->render();
        }
        // send the response
        return Response::json([
            'shared' => count($shared) > 0 ? $sharedPhotos : '<p class="message-hint"><span>Nothing shared yet</span></p>',
        ], 200);
    }


    /**
     * Fetch data (user, favorite.. etc).
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function tradeRequestDetails(Request $request)
    {
        $id = $request['id'];
        $tradeRequest = TradeRequests::where('id', $id)->where('send_to', Auth::user()->id)->first();

        $fetch = User::where('id', $tradeRequest->request_by)->first();
        $tradeRequest = TradeRequests::where('id', $id)->where('send_to', Auth::user()->id)->first();
        $tradeDetails = TradingCardDetails::where('trading_id', $tradeRequest->trade_id);
        if ($fetch) {
            $userAvatar = $this->chat->getUserWithAvatar($fetch)->avatar;
        }
        $tradeDetailsList = null;
        if ($tradeDetails->get()) {

            $tradeDetailsList .= view('merchant.giftcard.chat.layouts._trade_details', [
                'user' => $fetch,
                'tradeRequest' => $tradeRequest,
                'tradeDetails' => $tradeDetails->get()
            ]);
        }

//dd($tradeDetails->get());
        return Response::json([
            'favorite' => 1,
            'fetch' => $fetch ?? null,
            'user_avatar' => $userAvatar ?? null,
            'tradeRequestDetails' => $tradeDetailsList
        ]);
    }

    public function acceptTrade(Request $request)
    {
        $id = $request['id'];
        $tradeRequest = TradeRequests::where('id', $id)->where('send_to', Auth::user()->id)->first();
        if ($tradeRequest) {
            //check if the user already request this trade id then cancle the rest

            $tradeRequest->request_status = 'Accepted';
            $tradeRequest->accepted_by = Auth()->user()->id;
            $tradeRequest->request_status_at = date('Y-m-d H:i:s');
            if ($tradeRequest->save()) { //acceptance successful then initiate conversation
                //send welcome message

                $message = $this->chat->newMessage([
                    'from_id' => Auth::user()->id,
                    'request_id' => $tradeRequest->id,
                    'trading_id' => $tradeRequest->trade_id,
                    'to_id' => $tradeRequest->request_by,
                    'body' => htmlentities("Hello My Name is " . Auth()->user()->name . ", Let start trading", ENT_QUOTES, 'UTF-8'),
                    'attachment' => null,
                ]);
                $tradeGiftCard = TradeGiftCard::where('id', $tradeRequest->trade_id)->first();
                $tradeGiftCard->accept_trade = 1;
                $tradeGiftCard->accepted_by = Auth()->user()->id;
                $tradeGiftCard->accepted_at = $tradeRequest->request_status_at;
                $tradeGiftCard->trade_status = 'Accepted';
                $tradeGiftCard->save();
                $messageData = $this->chat->parseMessage($message);

                $this->chat->push("private-chatify." . Auth()->user()->getUserAccessKey($tradeRequest->request_by), 'messaging', [
                    'from_id' => Auth::user()->id,
                    'request_id' => $tradeRequest->id,
                    'trading_id' => $tradeRequest->trade_id,
                    'to_id' => $tradeRequest->request_by,
                    'message' => $this->chat->messageCard($messageData, true)
                ]);
                return Response::json(['status' => true, 'requestId' => $tradeRequest->id]);

            }
        } else {
            return Response::json(['status' => false]);
        }

        /*

                    $messageData = $chat->parseMessage($message);
                    if (Auth::user()->id != $tradeRequest->request_by) {
                        $chat->push("private-chatify.".$tradeRequest->request_by, 'messaging', [
                            'from_id' => Auth::user()->id,
                            'request_id'=>$tradeRequest->id,
                            'trading_id'=>$tradeRequest->trade_id,
                            'to_id' => $tradeRequest->request_by,
                            'message' => $chat->messageCard($messageData, true)
                        ]);
                    }

                    $query = $chat->fetchMessagesQuery($tradeRequest->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);
                    }
                    $allMessages = null;
                    foreach ($messages->reverse() as $message) {
                        $allMessages .= $chat->messageCard(
                            $chat->parseMessage($message)
                        );
                    }
                    $response['messages'] = $allMessages;
                    return Response::json($response);

                    }
        */

    }

    /**
     * fetch [user/group] messages from database
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function fetchTradingConversation(Request $request)
    {
        $id = $request['id'];
        // $chat = new ChatMessenger();
        $query = $this->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);
        }
        $allMessages = null;
        foreach ($messages->reverse() as $message) {
            $allMessages .= $this->chat->messageCard(
                $this->chat->parseMessage($message)
            );
        }
        $response['messages'] = $allMessages;
        return Response::json($response);
    }

    /**
     * Get contacts list
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function getTradingList(Request $request)
    {
        // get all users that received/sent message from/to [Auth user]
        /*  $users = TradingMessage::join('users',  function ($join) {
              $join->on('ch_messages.from_id', '=', 'users.id')
                  ->orOn('ch_messages.to_id', '=', 'users.id');
          })
              ->where(function ($q) {
                  $q->where('ch_messages.from_id', Auth::user()->id)
                      ->orWhere('ch_messages.to_id', Auth::user()->id);
              })
              ->where('users.id','!=',Auth::user()->id)
              ->select('users.*',DB::raw('MAX(ch_messages.created_at) max_created_at'))
              ->orderBy('max_created_at', 'desc')
              ->groupBy('users.id')
              ->paginate($request->per_page ?? $this->perPage);
  */
        //$chat= new ChatMessenger();
        $users = TradeRequests::join('users', 'trade_requests.request_by', '=', 'users.id')
            ->where('trade_requests.send_to', Auth()->user()->id)
            ->select('users.name', 'users.active_status', 'users.avatar', 'trade_requests.*')
            //->orderBy('max_created_at', 'desc')
            //->groupBy('trade_requests.id')
            ->paginate($request->per_page);
        $usersList = $users->items();

        if (count($usersList) > 0) {
            $contacts = '';
            foreach ($usersList as $user) {
                $contacts .= $this->chat->getContactItem($user);
            }
        } else {
            $contacts = '<p class="message-hint center-el"><span>Your contact list is empty</span></p>';
        }

        return Response::json([
            'contacts' => $contacts,
            'total' => $users->total() ?? 0,
            'last_page' => $users->lastPage() ?? 1,
        ], 200);
    }


    /**
     * Send a message to database
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function sendMessage(Request $request)
    {
        $id = $request['id'];
        $tradeRequest = TradeRequests::where('id', $id)->where('accepted_by', Auth()->user()->id)->first();

        // $chat = new ChatMessenger();
        // default variables
        $error = (object)[
            'status' => 0,
            'message' => null
        ];
        $attachment = null;
        $attachment_title = null;

        if ($tradeRequest) {
            // if there is attachment [file]
            if ($request->hasFile('file')) {
                // allowed extensions
                $allowed_images = $this->chat->getAllowedImages();
                $allowed_files = $this->chat->getAllowedFiles();
                $allowed = array_merge($allowed_images, $allowed_files);

                $file = $request->file('file');
                // check file size
                if ($file->getSize() < $this->chat->getMaxUploadSize()) {
                    if (in_array(strtolower($file->extension()), $allowed)) {
                        // get attachment name
                        $attachment_title = $file->getClientOriginalName();
                        // upload attachment and store the new name
                        $attachment = Str::uuid() . "." . $file->extension();
                        $file->storeAs(config('chatify.attachments.folder'), $attachment, config('chatify.storage_disk_name'));
                    } else {
                        $error->status = 1;
                        $error->message = "File extension not allowed!";
                    }
                } else {
                    $error->status = 1;
                    $error->message = "File size you are trying to upload is too large!";
                }
            }

            if (!$error->status) {
                $message = $this->chat->newMessage([
                    'from_id' => Auth::user()->id,
                    'trading_id' => $tradeRequest->trade_id,
                    'request_id' => $tradeRequest->id,
                    'to_id' => $tradeRequest->request_by,
                    'body' => htmlentities(trim($request['message']), ENT_QUOTES, 'UTF-8'),
                    'attachment' => ($attachment) ? json_encode((object)[
                        'new_name' => $attachment,
                        'old_name' => htmlentities(trim($attachment_title), ENT_QUOTES, 'UTF-8'),
                    ]) : null,
                ]);
                $messageData = $this->chat->parseMessage($message);
                if (Auth::user()->id != $tradeRequest->request_by) {
                    $this->chat->push("private-chatify." . Auth()->user()->getUserAccessKey($tradeRequest->request_by), 'messaging', [
                        'from_id' => Auth::user()->access_key,
                        'request_id' => $request['id'],
                        'to_id' => Auth::user()->getUserAccessKey($tradeRequest->request_by),
                        'message' => $this->chat->messageCard($messageData, true)
                    ]);
                }
            }

            // send the response
            return Response::json([
                'status' => '200',
                'error' => $error,
                'message' => $this->chat->messageCard(@$messageData),
                'tempID' => $request['temporaryMsgId'],
            ]);
        } else {
            $error->status = 1;
            $error->message = "Invalid Trade!";

            return Response::json([
                'status' => '200',
                'error' => $error,
                'message' => $this->chat->messageCard([]),
                'tempID' => $request['temporaryMsgId'],
            ]);
        }
    }

    /**
     * Make messages as seen
     *
     * @param Request $request
     * @return JsonResponse|void
     */
    public function seen(Request $request)
    {
        //$chat = new ChatMessenger();
        // $id = $request['id'];
        // make as seen
        $seen = $this->chat->makeSeen($request['id']);
        // send the response
        return Response::json([
            'status' => $seen,
        ], 200);
    }

    /**
     * Update user's list item data
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function updateTradeList(Request $request)
    {
        // $chat = new ChatMessenger();
        $id = $request['user_id'];
        // Get user data
        $user = TradeRequests::join('users', 'trade_requests.request_by', '=', 'users.id')
            ->where('trade_requests.id', $id)
            ->select('users.name', 'users.active_status', 'users.avatar', 'trade_requests.*')->first();

        if (!$user) {
            return Response::json([
                'message' => 'User not found!',
            ], 401);
        }
        $contactItem = $this->chat->getContactItem($user);

        // send the response
        return Response::json([
            'contactItem' => $contactItem,
        ], 200);
    }

    public function changePassword()
    {
        return view('merchant.change_password');
    }

    public function updatePassword(Request $request)
    {
        $request->validate(['old_pass' => 'required', 'password' => 'required|min:6|confirmed']);
        $user = merchant();
        if (Hash::check($request->old_pass, $user->password)) {
            $password = bcrypt($request->password);
            $user->password = $password;
            $user->save();
            return back()->with('success', 'Password has been changed');
        } else {
            return back()->with('error', 'The old password doesn\'t match!');
        }
    }

    public function transactions()
    {
        $remark = request('remark');
        $search = request('search');
        $transactions = Transaction::where('user_id', merchant()->id)->where('user_type', 2)
            ->when($remark, function ($q) use ($remark) {
                return $q->where('remark', $remark);
            })
            ->when($search, function ($q) use ($search) {
                return $q->where('trnx', $search);
            })
            ->latest()
            ->paginate(15);

        return view('merchant.transactions', compact('transactions'));
    }

    public function trxDetails($id)
    {
        $transaction = Transaction::find($id);
        if (!$transaction) {
            return response('empty');
        }
        return view('merchant.trx_details', compact('transaction'));
    }


    public function twoStep()
    {
        return view('merchant.twostep.two_step');
    }

    public function twoStepSendCode(Request $request)
    {
        $request->validate(['password' => 'required|confirmed']);
        $user = merchant();
        if (Hash::check($request->password, $user->password)) {
            $code = randNum();
            $user->two_fa_code = $code;
            $user->update();
            sendSMS($user->phone, trans('Your two step authentication OTP is : ') . $code, Generalsetting::value('contact_no'));
            return redirect(route('merchant.two.step.verify'))->with('success', 'OTP code is sent to your phone.');
        } else {
            return back()->with('error', 'The password doesn\'t match!');
        }

    }

    public function twoStepVerifyForm()
    {
        return view('merchant.twostep.verify');
    }

    public function twoStepVerifySubmit(Request $request)
    {
        $request->validate(['code' => 'required']);
        $user = merchant();
        if ($request->code != $user->two_fa_code) {
            return back()->with('error', 'Invalid OTP');
        }
        if ($user->two_fa_status == 1) {
            $user->two_fa_status = 0;
            $msg = __('Your two step authentication is de-activated');
        } else {
            $user->two_fa_status = 1;
            $msg = __('Your two step authentication is activated');
        }
        $user->save();
        return redirect(route('merchant.two.step'))->with('success', $msg);
    }


    public function moduleOff($module)
    {
        $key = str_replace('_', '-', $module);
        $mod = Module::where('module', $key)->first();
        if ($mod && $mod->status == 1) {
            return redirect(url('merchant/' . $key));
        }
        return view('merchant.module_off', compact('module'));
    }

    /**
     * Set user's active status
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function setActiveStatus(Request $request)
    {
        $activeStatus = $request['status'] > 0 ? 1 : 0;
        $status = Merchant::where('id', Auth::user()->id)->update(['active_status' => $activeStatus]);
        return Response::json([
            'status' => $status,
        ], 200);
    }


    /**
     * This method to make a links for the attachments
     * to be downloadable.
     *
     * @param string $fileName
     * @return \Symfony\Component\HttpFoundation\StreamedResponse|void
     */
    public function download($fileName)
    {
        $filePath = config('chatify.attachments.folder') . '/' . $fileName;
        if (Chatify::storage()->exists($filePath)) {
            return Chatify::storage()->download($filePath);
        }
        return abort(404, "Sorry, File does not exist in our server or may have been deleted!");
    }

    public function approveCard(Request $request)
    {
        $request_id = $request['request_id'];
        $cardId = $request['id'];
        $rate = (float)$request['rate'];
        //check if this traderequest is for this merchant
        $tradeRequest = TradeRequests::where('id', $request_id)->where('send_to', Auth()->user()->id)->first();
        if (empty($tradeRequest)) {
            return Response::json([
                'status' => 2,
            ], 200);
        }

        if($rate<=0){
            return Response::json([
                'status' => 4,
            ], 200);
        }
//get cards
        $user_id = Auth()->user()->id;
        $cardDetails = TradingCardDetails::join('gift_cards', 'trading_card_details.card_id', '=', 'gift_cards.id')->where('trading_card_details.id', $cardId)->where('trading_id', $tradeRequest->trade_id)
            ->where('trading_card_details.created_by', $tradeRequest->request_by)->where('trading_status', '!=', 'Redeem')->select('trading_card_details.*', 'gift_cards.card_name')->first();

        if (empty($cardDetails)) {
            return Response::json([
                'status' => 3,
            ], 200);
        }
        //create Transaction
        $amount = $cardDetails->amount * $rate;
        $newTrans = new TransactionHistory();
        $newTrans->descriptions = 'Credit for Trading of $' . $cardDetails->amount . ' ' . $cardDetails->card_name;
        $newTrans->trade_id = $cardDetails->trading_id;
        $newTrans->request_id = $tradeRequest->id;
        $newTrans->tradedcard_details_id = $cardDetails->id;
        $newTrans->transaction_ref = 'R2FTX' . $cardDetails->id . time() . $cardDetails->created_by;
        $newTrans->amount = $amount;
        $newTrans->rate = $rate;
        $newTrans->currency = $cardDetails->currency;
        $newTrans->refer_bonus = $cardDetails->refer_bonus;
        $newTrans->referer_user_id = $cardDetails->referer_user_id;
        $newTrans->user_id = $cardDetails->created_by;
        $newTrans->transaction_type = 'Credit';
        $newTrans->created_by = $user_id;
        $newTrans->source = 'Giftcard';
        $newTrans->status = 'Pending';
        if ($newTrans->save()) {
            //save Refere Bonus Transaction
            $cardDetails->trading_status = "Redeem";
            $cardDetails->rate = $rate;
            $cardDetails->total_amount = $newTrans->amount;

            $cardDetails->approved_amount = $newTrans->amount;
            $cardDetails->approved_refer_bonus = $cardDetails->refer_bonus;
            $cardDetails->approved_transaction_id = $newTrans->id;
            $cardDetails->trading_status_updated_by = $user_id;
            $cardDetails->trading_status_updated_at = date('Y-m-d H:i:s');
            if ($cardDetails->save()) {
                //save wallet
                Auth()->user()->saveToClientWallet($cardDetails->approved_amount, $cardDetails->created_by, 'Pending');
                if (!empty($cardDetails->referer_user_id)) {
                    Auth()->user()->saveToClientWallet($cardDetails->approved_refer_bonus, $cardDetails->referer_user_id, 'ReferPending');
                }
                $message = $this->chat->newMessage([
                    'from_id' => Auth::user()->id,
                    'request_id' => $tradeRequest->id,
                    'trading_id' => $tradeRequest->trade_id,
                    'to_id' => $tradeRequest->request_by,
                    'body' => htmlentities($cardDetails->card_name ." - $". $cardDetails->amount.' trade successful you wallet has been credited' , ENT_QUOTES, 'UTF-8'),
                    'attachment' => null,
                ]);
                $messageData = $this->chat->parseMessage($message);

                $this->chat->push("private-chatify." . Auth()->user()->getUserAccessKey($tradeRequest->request_by), 'messaging', [
                    'from_id' => Auth::user()->access_key,
                    'request_id' => $request['id'],
                    'to_id' => Auth::user()->getUserAccessKey($tradeRequest->request_by),
                    'message' => $this->chat->messageCard($messageData, true)
                ]);

             /*   $this->chat->push("private-chatify." . Auth()->user()->getUserAccessKey($tradeRequest->request_by), 'messaging', [
                    'from_id' => Auth::user()->id,
                    'request_id' => $tradeRequest->id,
                    'trading_id' => $tradeRequest->trade_id,
                    'to_id' => $tradeRequest->request_by,
                    'message' => $this->chat->messageCard($messageData, true)
                ]);*/
                return Response::json([
                    'status' => 1,
                ], 200);

            }
        }


    }

    public function disapproveCard(Request $request)
    {
        $request_id = $request['request_id'];
        $cardId = $request['id'];
        //check if this traderequest is for this merchant
        $tradeRequest = TradeRequests::where('id', $request_id)->where('send_to', Auth()->user()->id)->first();
        if (empty($tradeRequest)) {
            return Response::json([
                'status' => 2,
            ], 200);
        }
//get cards
        $user_id = Auth()->user()->id;
        $cardDetails = TradingCardDetails::join('gift_cards', 'trading_card_details.card_id', '=', 'gift_cards.id')->where('trading_card_details.id', $cardId)->where('trading_id', $tradeRequest->trade_id)
            ->where('trading_card_details.created_by', $tradeRequest->request_by)->where('trading_status', '!=', 'Redeem')->select('trading_card_details.*', 'gift_cards.card_name')->first();
//dd($cardDetails);
        if (empty($cardDetails)) {
            return Response::json([
                'status' => 3,
            ], 200);
        }

        //save Refere Bonus Transaction
        $cardDetails->trading_status = "Decline";
        $cardDetails->approved_amount = 0;
        $cardDetails->approved_refer_bonus = 0;
        // $cardDetails->approved_transaction_id = $newTrans->id;
        $cardDetails->trading_status_updated_by = $user_id;
        $cardDetails->trading_status_updated_at = date('Y-m-d H:i:s');
        $cardDetails->reason_for_decline=$request['reason'];
        if ($cardDetails->save()) {
            $message = $this->chat->newMessage([
                'from_id' => Auth::user()->id,
                'request_id' => $tradeRequest->id,
                'trading_id' => $tradeRequest->trade_id,
                'to_id' => $tradeRequest->request_by,
                'body' => htmlentities("$" . $cardDetails->amount . ' ' . $cardDetails->card_name.' is decline; Reason: '.$cardDetails->reason_for_decline, ENT_QUOTES, 'UTF-8'),
                'attachment' => null,
            ]);
            $messageData = $this->chat->parseMessage($message);

            $this->chat->push("private-chatify." . Auth()->user()->getUserAccessKey($tradeRequest->request_by), 'messaging', [
                'from_id' => Auth::user()->id,
                'request_id' => $tradeRequest->id,
                'trading_id' => $tradeRequest->trade_id,
                'to_id' => $tradeRequest->request_by,
                'message' => $this->chat->messageCard($messageData, true)
            ]);
            return Response::json([
                'status' => 1,
            ], 200);


        }

    }
    public function completeTrade(Request $request)
    {
        $request_id = $request['request_id'];
        //check if this traderequest is for this merchant
        $tradeRequest = TradeRequests::where('id', $request_id)->where('send_to', Auth()->user()->id)->first();
        if (empty($tradeRequest)) {
            return Response::json([
                'status' => 2,
            ], 200);
        }

        $tradeDetails = TradeGiftCard::where('id',$tradeRequest->trade_id)->where('user_id',$tradeRequest->request_by)->first();
//get cards
        $user_id = Auth()->user()->id;
        $actionDate= date('Y-m-d H:i:s');

        if (empty($tradeDetails)) {
            return Response::json([
                'status' => 3,
            ], 200);
        }

        //save Refere Bonus Transaction
      $tradeRequest->completed_trade_at = $actionDate;
        $tradeRequest->completed_trade_by = Auth()->user()->id;
        if ($tradeRequest->save()) {
            $tradeDetails->trade_status = 'Completed';
            $tradeDetails->status_change_by = $user_id;;
            $tradeDetails->status_change_at = $actionDate;
            $tradeDetails->completed_trade_at = $actionDate;
            $tradeDetails->completed_trade_by = $user_id;
            $tradeDetails->save();
            $message = $this->chat->newMessage([
                'from_id' => Auth::user()->id,
                'request_id' => $tradeRequest->id,
                'trading_id' => $tradeRequest->trade_id,
                'to_id' => $tradeRequest->request_by,
                'body' => htmlentities('Trading of '.$tradeDetails->trade_descriptions ." is Completed at ". $tradeDetails->completed_trade_at , ENT_QUOTES, 'UTF-8'),
                'attachment' => null,
            ]);
            $messageData = $this->chat->parseMessage($message);

            $this->chat->push("private-chatify." . Auth()->user()->getUserAccessKey($tradeRequest->request_by), 'messaging', [
                'from_id' => Auth::user()->id,
                'request_id' => $tradeRequest->id,
                'trading_id' => $tradeRequest->trade_id,
                'to_id' => $tradeRequest->request_by,
                'message' => $this->chat->messageCard($messageData, true)
            ]);
            return Response::json([
                'status' => 1,
            ], 200);


        }

    }

  public  function getFiles (Request $request, $filename)
    {
       // return 'hi';
        $file = storage_path('/attachments/' . $filename);
        if (file_exists($file)) {
            return response()->file($file);
        } else {
            // Handle the case where the file doesn't exist
            abort(404, 'File not found');
        }
    }

    public function allTrades()
    {
      //  \DB::enableQueryLog();
        $search = request('search');
        $status = request('status');
        $merchantId = auth()->user()->id; // Example: Dynamic merchant ID from the logged-in user.

        $trades = TradeRequests::with(['merchantBy', 'requestedBy', 'tradeDetail'])
            ->when($status, function ($q) use ($status) {
                $q->whereHas('tradeDetail', function ($query) use ($status) {
                    $query->where('trade_status', $status);
                });
            })
            ->when($search, function ($q) use ($search) {
                $q->whereHas('tradeGiftCard', function ($query) use ($search) {
                    $query->where('reference_no', 'like', "%$search%");
                });
            })
            ->whereHas('merchantBy', function ($q) use ($merchantId) {
                $q->where('id', $merchantId);
            })
            ->latest()
            ->paginate(15);
       //dd(\DB::getQueryLog());
        return view('merchant.manage_giftcard_trade.all_giftcard_trades', compact('trades', 'search'));
    }





}

