<?php

namespace Yas\Checkout\Console\Commands;

use Illuminate\Console\Command;
use Yas\Core\Handler\Log;
use Webkul\Product\Models\ProductAttributeValue;
use Webkul\Attribute\Models\Attribute;
use Yas\Product\Models\Product;
use Yas\Checkout\Repositories\CartRepository;
use Illuminate\Support\Facades\Config;
use Yas\Checkout\Repositories\CartItemRepository;

class DeactiveCarts extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'checkout:deactivecarts';
    protected $description = 'Deactive carts after some specific time duration';
    
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(protected CartRepository $cartRepository,
    protected CartItemRepository $cartItemRepository,
    protected Log $log)
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        try {
            $this->log->generateLog('info', "Deactive Carts Cron", [
                'deactiveTime' => core()->getConfigData('sales.checkout.deactive_cart.deactive_cart_in_minutes'),
            ], config("checkout.deactive_carts"));

            $currentDate = date("Y-m-d H:i:s", time());
            //dd($currentDate);
            //$deactiveTime = 30;
            $deactiveTime = core()->getConfigData('sales.checkout.deactive_cart.deactive_cart_in_minutes');
            $timeToSubtract = 60*$deactiveTime;

            $updatedDate = date("Y-m-d H:i:s", strtotime($currentDate) - $timeToSubtract);
            
            $carts  = $this->cartRepository->where('created_at' ,"<", $updatedDate)->where('is_active',1)->get();
            $count = 0;
            foreach($carts As $cart){
                $this->cartRepository->update(['is_active'=>0],$cart->id);
                $count++;

                $cartItems = $this->cartItemRepository->where('cart_id',$cart->id)->get();
                //$this->productRepository->removeHolingStatus($cartItems);
                foreach ($cartItems as $cartItem) {
                    $this->productRepository->where('id', $cartItem->product_id)->update(['holding_status'=>0]);
                }
            }
            if($count){
                $this->info("{$count} Carts deactivated successfully.");
            }else{
                $this->info("No carts to deactive");
            }
        } catch (\Throwable $e) {
            dd($e->getMessage().$e->getTraceAsString());
        }
    }
}
