<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Yajny\Member\Models\Click;
use Yajny\Member\Models\Member;
use Yajny\Member\Models\Sale;

class RunUserSalesCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'user_sales:run';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Get currency exchange rates';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $sale_ids = DB::select(
            DB::raw("SELECT s.id FROM yajny.sales as s left join yajny.user_sales as us on us.sales_id = s.id where us.id is null and s.status='confirmed';"));
        foreach ($sale_ids as $sale_id) {
            $sale = Sale::find($sale_id->id);
            $click = Click::find($sale->click_id);

            if ($click) {
                $sale->store_id = $click
                    ->store_id;
                $user = Member::find($click->user_id);
                if ($user && $user->is_merchant && $click->cashback_percent > 50)
                    $sale->cashback_percent = 50;
                else
                    $sale->cashback_percent = $click->cashback_percent;
                $sale->save();
                if ($user && $click->cashback_enabled == 1 && $click->cashback_percent > 0) {
                    $user->assignCashback($sale, true);
                    if ($click->link_id > 0) {
                        $link_earning = DB::select("SELECT getLinkCashback({$click->link_id}) as earning");
                        if ($link_earning) {
                            DB::table('user_links')->where('id', $click->link_id)->update(['earnings' => $link_earning[0]->earning]);
                        }
                    }
                }
            }
        }
    }
}
