<?php

namespace App\Http\Controllers\Merchant;

use App\Http\Controllers\Controller;
use App\Models\GiftCardAmount;
use App\Models\GiftCards;
use App\Models\Merchant;
use App\Models\TradeGiftCard;
use App\Models\TradingCardDetails;
use Chatify\Facades\ChatifyMessenger as Chatify;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Pusher\Pusher;

class TradeGiftController extends Controller
{
    //
    public $pusher;
    public function __construct()
    {
        $this->pusher = new Pusher(
           'api-key',
          'app-secret',
         'app-id',
            config('chatify.pusher.options'),
        );
    }
    public function SellGiftCard(){
        $giftCards = GiftCards::all();
        return view('user.giftcard.sell_index', compact('giftCards'));
    }

    public function getGiftCardAmount($gid){
        $giftAmount = GiftCardAmount::where('card_id',$gid)->pluck('id','amount');
        return response()->json($giftAmount);
    }

    public function getRate($ref){
        $giftAmount =GiftCardAmount::where('id', $ref)->select('id', 'rate', 'amount')->first();
        return response()->json($giftAmount);
    }

    public function saveTrade(Request $request){
        $request->validate([
            'giftCardID'=>'required',
            'qty'=>'required',
            'amount'=>'required'
        ],[
            'giftCardID.required' => 'Please Add the giftcard you want to trade',
            'qty.required' => 'Please enter the quantity.',
            'amount.required' => 'Please enter the amount.'
        ]);
       // try{
            $giftCardId = $request->giftCardID;
            $rateID = $request->amount;
            $totalTrade = count($rateID);
            $tQty = $request->qty;
            if($totalTrade>0){//which mean thier data in giftcardid
                //run check for the rate
                //create Trading
                $refNo = 'R2T-'.time();
                $tradingModel = new TradeGiftCard();
                $tradingModel->user_id=auth()->user()->id;
                $tradingModel->trade_status="Pending";
                $tradingModel->reference_no = $refNo;
                $tradingModel->save();

              //  $selectedGiftCard = GiftCardAmount::whereIn('id',$rateID)->get();
$totalAmount = 0;
$totalRfbonus = 0;
$tradeDescription = "";
                for($i=0;$i<$totalTrade;$i++){
                    $getRate =  GiftCardAmount::where('id',$rateID[$i])->first();
                    if(!(empty($getRate))){
                        $qty = $tQty[$i];

                        for($x=0;$x<$qty;$x++) {
                            $tradeModel = new TradingCardDetails();
                            $tradeModel->card_id = $getRate->card_id;;
                            $tradeModel->trading_id = $tradingModel->id;
                            $tradeModel->rate = $getRate->rate;
                            $tradeModel->amount = $getRate->amount;
                            $tradeModel->total_amount = $getRate->rate * $getRate->amount;
                            $tradeModel->refer_bonus = $getRate->refer_bonus;
                            $tradeModel->trading_status = 'Pending';
                            if($tradeModel->save()){
                                $totalAmount+=$tradeModel->total_amount;
                                $totalRfbonus+=$tradeModel->refer_bonus;

                            }

                        }
                        $tradeDescription.='$'.$tradeModel->amount.' '.$getRate->giftCard->card_name.' x ' .$qty .', ';
                    }

                }
                $tradingModel->trade_descriptions= $tradeDescription;
                $tradingModel->total_amount = $totalAmount;
                $tradingModel->refer_bonus = $totalRfbonus;
               if( $tradingModel->save()) {
                   return $tradingModel->reference_no;
                  // return redirect()->route('user.merchant',['reference'=>$tradingModel->reference_no]);
               }

            }

      /*  }catch (\Throwable $th){
            return response()->json($th->getMessage());
        }
      */


    }

    public function listMerchant(Request $request){
        $merchants = Merchant::all();
        $tradeId = $request->reference;
        if(request()->headers->has('X-Pjax')){
            return 'hello';
    }else{
            return view('merchant.giftcard.list_merchant', compact('merchants', 'tradeId'));

        }
    }

    public function tradeChat(){
        $messenger_color = Auth::user()->messenger_color;
        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',
        ]);
    }

    public function checkPusher(){
        $data=['message'=>'Hello Front'];
        $this->pusher->trigger('my-channel','message-send',$data);
        return 'Sent';
    }




}
