<?php

namespace App\Console\Commands\Payouts;

use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Yajny\Member\Models\Currencies;
use Yajny\Member\Models\Member;
use Yajny\Member\Models\PayoutMethods;
use Yajny\Member\Models\UserBonus;
use Yajny\Member\Models\UserPayoutMethods;
use Yajny\Member\Models\UserPayouts;
use Yajny\Member\Models\UserSales;

class MerchantsPayoutsCreation extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'merchantPayment:create {backInMonths=3}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'will create merchants payouts';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $fee = 0.02;
        $startDate = Carbon::now()->subMonths($this->argument('backInMonths'))->startOfMonth();
        $endDate = Carbon::now()->subMonths($this->argument('backInMonths'))->endOfMonth();

        $merchants = Member::where("is_merchant", true)
            ->where("active", 1)
            ->where("parent_id", 0)
            ->get();

        foreach ($merchants as $merchant) {
            $this->output->write("merchant ID : " . $merchant->user_id, true);
            $total_cashback = 0;
            $total_cashback_EGP = 0;
            $total_cashback_SAR = 0;
            $total_cashback_AED = 0;
            $total_cashback_KWD = 0;
            $merchantCashback = UserSales::where([['user_id', $merchant->user_id], ['status', 'confirmed'], ['is_reset', false]])
                ->whereBetween('created_at', [$startDate, $endDate])
                ->select(DB::raw("SUM(cashback_egp) as cashback_egp,SUM(cashback_sar) as cashback_sar ,SUM(cashback_aed) as cashback_aed ,SUM(cashback_kwd) as cashback_kwd, SUM(cashback) as cashback"))
                ->first();
            // getting merchant cashback
            $this->output->write("start : " . $startDate . "   end : " . $endDate, true);
            $total_cashback += (double)$merchantCashback->cashback;
            $total_cashback_EGP += (double)$merchantCashback->cashback_egp;
            $total_cashback_SAR += (double)$merchantCashback->cashback_sar;
            $total_cashback_AED += (double)$merchantCashback->cashback_aed;
            $total_cashback_KWD += (double)$merchantCashback->cashback_kwd;
            $this->output->write("merchant cashback : " . $total_cashback, true);

            $merchantchilds = Member::where("parent_id", $merchant->user_id)
                ->get();

            $merchantBonus = UserBonus::where([['user_id', $merchant->user_id], ['status', 'confirmed'], ['is_reset', false]])
                ->where("bonus_code", "loyalty_program")
                ->whereBetween('awarded_on', [
                    Carbon::now()->startOfMonth()->format('Y-m-d'),
                    Carbon::now()->endOfMonth()->format('Y-m-d')
                ])
                ->select(DB::raw("SUM(amount_egp) as amount_egp,SUM(amount_sar) as amount_sar,SUM(amount_kwd) as amount_kwd,SUM(amount_aed) as amount_aed,SUM(amount) as amount"))
                ->first();
            // getting merchant bonus
            $total_cashback += (double)$merchantBonus->amount;
            $total_cashback_EGP += (double)$merchantBonus->amount_egp;
            $total_cashback_SAR += (double)$merchantBonus->amount_sar;
            $total_cashback_AED += (double)$merchantBonus->amount_aed;
            $total_cashback_KWD += (double)$merchantBonus->amount_kwd;
            $this->output->write("merchant cashback after bonus : " . $merchantBonus, true);

            // getting merchant childs cashback
            foreach ($merchantchilds as $child) {
                $childCashback = UserSales::where([['user_id', $child->user_id], ['status', 'confirmed'], ['is_reset', false]])
                    ->whereBetween('created_at', [$startDate, $endDate])
                    ->select(DB::raw("SUM(cashback_egp) as cashback_egp,SUM(cashback_sar) as cashback_sar ,SUM(cashback_aed) as cashback_aed ,SUM(cashback_kwd) as cashback_kwd, SUM(cashback) as cashback"))
                    ->first();
                $total_cashback += (double)$childCashback->cashback;
                $total_cashback_EGP += (double)$childCashback->cashback_egp;
                $total_cashback_SAR += (double)$childCashback->cashback_sar;
                $total_cashback_AED += (double)$childCashback->cashback_aed;
                $total_cashback_KWD += (double)$childCashback->cashback_kwd;
            }
            $this->output->write("merchant cashback after childs bonus : " . $total_cashback, true);

            // check if the merchant have cashback or not
            if ($total_cashback > 0) {
                // create payout for the merchant
                $user_method = UserPayoutMethods::where('user_id', $merchant->user_id)->where('enabled', true)->first();
                if ($user_method) {
                    $method = PayoutMethods::where('code', $user_method->method_code)->first();
                    $rate = Currencies::where('iso_code', $method->default_currency)->first()->conversion_rate;
                    $localCashbackAmount = $this->localCashbackAmountByCurrency($method->default_currency, $total_cashback, $total_cashback_EGP, $total_cashback_SAR, $total_cashback_AED, $total_cashback_KWD);
                    $localFeeAmount = $this->calculateLocaleFee($localCashbackAmount * $fee) ;

                    $merchantPayout = new UserPayouts();
                    $merchantPayout->user_id = $merchant->user_id;
                    $merchantPayout->method_code = $method->code;
                    $merchantPayout->account = $user_method->account;
                    $merchantPayout->amount = $total_cashback;
                    $merchantPayout->cashback_amount = 0;
                    $merchantPayout->reward_amount = 0;
                    $merchantPayout->status = "created";
                    $merchantPayout->note = "created by automated script";
                    $merchantPayout->local_currency = $method->default_currency;
                    $merchantPayout->currency_rate = $rate;

                    $merchantPayout->fees_amount = $total_cashback * $fee;
                    $merchantPayout->final_amount = $total_cashback - ($total_cashback * $fee);
                    $merchantPayout->local_amount = $localCashbackAmount;
                    $merchantPayout->local_fees_amount = $localFeeAmount;
                    $merchantPayout->local_final_amount = $localCashbackAmount - $localFeeAmount;
                    $merchantPayout->is_reset = false;
                    $merchantPayout->amount_egp = $total_cashback_EGP;
                    $merchantPayout->amount_sar = $total_cashback_SAR;
                    $merchantPayout->amount_aed = $total_cashback_AED;
                    $merchantPayout->amount_kwd = $total_cashback_KWD;
                    $merchantPayout->save();
                    $this->output->write($merchant->user_id . '           ' . $method->id, true);
                }

            }

        }

    }

    private function localCashbackAmountByCurrency($currency, $cashbackInDollar, $cashbackEgp, $cashbackSar, $cashbackAed, $cashbackKwd)
    {
        $cashback = [
            'EGP' => $cashbackEgp,
            'SAR' => $cashbackSar,
            'AED' => $cashbackAed,
            'KWD' => $cashbackKwd,
            'USD' => $cashbackInDollar,
        ];
        return $cashback[$currency] ?? $cashbackInDollar;
    }
    private function calculateLocaleFee($feeAmount)
    {
        if ($feeAmount > 200) {
            return 200;
        }
        if ($feeAmount < 20) {
            return 20;
        }
        return $feeAmount;
    }
}
