<?php

namespace App\Console\Commands;

use DB;
use Carbon\Carbon;
use Illuminate\Console\Command;
use App\Domain\Points\Models\Point;
use App\Domain\Points\Enums\DirectionEnum;
use App\Domain\Subscriptions\Models\Package;
use App\Domain\Subscriptions\Models\Subscription;
use App\Domain\Subscriptions\Service\SubscriptionService;

class AutoSubscribeApp extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'teaser:auto-subs-app';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Autosubscription to the site';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $plan = Package::findOrFail(1);
        $price = $plan->price;

        $lists = DB::table('subscriptions')
        ->join('users', 'subscriptions.user_id', '=', 'users.id')
        ->selectRaw('subscriptions.user_id, MAX(subscriptions.ends_at) as last_time, users.autosubscription_site')
        ->groupBy('subscriptions.user_id', 'users.autosubscription_site')
        ->havingRaw('MAX(subscriptions.ends_at) <= ?', [now()])
        ->having('users.autosubscription_site', true)
        ->get();

        foreach($lists as $list){
            $balance = SubscriptionService::calculate($list->user_id);
            $ends_at = Carbon::now()->addMonths();

            if ($price > $balance) {
                echo 'Недостаточно средств ' . $list->user_id . PHP_EOL;

                DB::table('users')
                    ->where('id', $list->user_id)
                    ->update(['autosubscription_site' => false]);
                continue;
            }

            $sub = new Subscription;
            $sub->user_id = $list->user_id;
            $sub->package_id = $plan->id;
            $sub->price = $price;
            $sub->ends_at = $ends_at;
            $sub->status = 'complete'; //YSV ENUM!
            $sub->save();

            $point = new Point;
            $point->user_id =$list->user_id;
            $point->point = $price;
            $point->type = 'Оплата за подписку';  //YSV ENUM!
            $point->direction = DirectionEnum::EXPENSE();
            $point->save();

        }



        return 0;
    }
}
