<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\License;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Activate licenses whose start date has arrived';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('Starting license activation process...');
        
        $today = Carbon::today();
        
        // Find licenses that should be activated today
        $licensesToActivate = License::where('starts_at', '<=', $today)
            ->where('is_active', false)
            ->with('user')
            ->get();
        
        if ($licensesToActivate->isEmpty()) {
            $this->info('No licenses to activate today.');
            return;
        }
        
        $activatedCount = 0;
        
        foreach ($licensesToActivate as $license) {
            try {
                // Activate the license
                $license->update(['is_active' => true]);
                
                // Activate the user account
                if ($license->user) {
                    $license->user->update(['status' => 'active']);
                    $activatedCount++;
                    
                    $this->info("Activated license for user: {$license->user->name} ({$license->user->email})");
                    
                    Log::info("License activated automatically", [
                        'license_id' => $license->id,
                        'user_id' => $license->user->id,
                        'user_email' => $license->user->email,
                        'starts_at' => $license->starts_at,
                        'activated_at' => now()
                    ]);
                }
            } catch (\Exception $e) {
                $this->error("Failed to activate license {$license->id}: {$e->getMessage()}");
                Log::error("Failed to activate license", [
                    'license_id' => $license->id,
                    'error' => $e->getMessage()
                ]);
            }
        }
        
        $this->info("Successfully activated {$activatedCount} licenses.");
        
        // Also check for expired licenses
        $this->checkExpiredLicenses();
    }
    
    /**
     * Check and deactivate expired licenses
     */
    private function checkExpiredLicenses()
    {
        $today = Carbon::today();
        
        $expiredLicenses = License::where('expires_at', '<', $today)
            ->where('is_active', true)
            ->with('user')
            ->get();
        
        if ($expiredLicenses->isEmpty()) {
            return;
        }
        
        $deactivatedCount = 0;
        
        foreach ($expiredLicenses as $license) {
            try {
                // Deactivate the license
                $license->update(['is_active' => false]);
                
                // Deactivate the user account
                if ($license->user) {
                    $license->user->update(['status' => 'inactive']);
                    $deactivatedCount++;
                    
                    $this->info("Deactivated expired license for user: {$license->user->name} ({$license->user->email})");
                    
                    Log::info("License deactivated due to expiry", [
                        'license_id' => $license->id,
                        'user_id' => $license->user->id,
                        'user_email' => $license->user->email,
                        'expires_at' => $license->expires_at,
                        'deactivated_at' => now()
                    ]);
                }
            } catch (\Exception $e) {
                $this->error("Failed to deactivate expired license {$license->id}: {$e->getMessage()}");
                Log::error("Failed to deactivate expired license", [
                    'license_id' => $license->id,
                    'error' => $e->getMessage()
                ]);
            }
        }
        
        if ($deactivatedCount > 0) {
            $this->info("Successfully deactivated {$deactivatedCount} expired licenses.");
        }
    }
}
