<?php

namespace App\Console\Commands;

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

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Adding Store Network and click to Sale_items table';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // getting 200 item from sale_items to add data in new fields
        $sales=Sale::where([
            ["network_id",19],
            ["transaction_time","LIKE","2022-12-%"],
        ])->get();
        foreach ($sales as $sale){
            $totalOrderAmount=0;
            $totalCommission=0;
            $saleItems=SaleItem::where("sale_id",$sale->id)->get();
            foreach ($saleItems as $item){
                $totalOrderAmount +=$item->unit_price*$item->quantity;
                $totalCommission +=$item->commission;
            }
            $sale->local_order_amount=$totalOrderAmount;
            $sale->order_amount=$totalOrderAmount/$sale->currency_rate;
            $sale->local_comission=$totalCommission;
            $sale->comission=$totalCommission/$sale->currency_rate;
            $sale->save();
        }
    }
}
