<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Restaurant;
use App\Models\AdminSetting;
use Carbon\Carbon;

class DeactivateUnpaidRestaurants extends Command
{
    protected $signature = 'restaurants:deactivate-unpaid';
    protected $description = 'Deactivate restaurants with unpaid subscriptions';

    public function handle()
    {
        // Get grace period from settings (default 3 months)
        $gracePeriodMonths = AdminSetting::where('key', 'payment_grace_period_months')->value('value') ?? 3;
        
        $cutoffDate = Carbon::now()->subMonths($gracePeriodMonths);
        
        $restaurants = Restaurant::where('is_active', true)
            ->where(function($query) use ($cutoffDate) {
                $query->whereNull('last_payment_date')
                      ->orWhere('last_payment_date', '<', $cutoffDate);
            })
            ->get();

        $deactivatedCount = 0;

        foreach ($restaurants as $restaurant) {
            $restaurant->update([
                'is_active' => false,
                'operational_status' => 'closed',
                'payment_status' => 'overdue'
            ]);
            
            $deactivatedCount++;
            
            $this->info("Deactivated: {$restaurant->name}");
        }

        $this->info("Total restaurants deactivated: {$deactivatedCount}");
        
        return Command::SUCCESS;
    }
}
