<?php

namespace App\Console\Commands;

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

class MarkInactiveProfiles extends Command
{
    protected $signature = 'profiles:mark-inactive';

    protected $description = 'Mark profiles as inactive when they have not logged in for configured number of days';

    protected $daysThreshold;
    protected $logFile;

    public function __construct()
    {
        parent::__construct();

        // Get configured threshold from platform config
        $this->daysThreshold = timebank_config('profile_inactive.days_not_logged_in');
        $this->logFile = storage_path('logs/mark-inactive-profiles.log');
    }

    public function handle()
    {
        $this->info('Checking profiles for inactivity...');
        $this->logMessage('=== Starting profile inactivity check ===');

        $totalMarked = 0;
        $thresholdDate = now()->subDays($this->daysThreshold);

        // Process Users
        $users = User::whereNotNull('last_login_at')
            ->whereNull('inactive_at') // Only profiles not already marked inactive
            ->where('last_login_at', '<', $thresholdDate)
            ->get();

        foreach ($users as $user) {
            $result = $this->markInactive($user, 'User');
            if ($result) $totalMarked++;
        }

        // Process Organizations
        $organizations = Organization::whereNotNull('last_login_at')
            ->whereNull('inactive_at') // Only profiles not already marked inactive
            ->where('last_login_at', '<', $thresholdDate)
            ->get();

        foreach ($organizations as $organization) {
            $result = $this->markInactive($organization, 'Organization');
            if ($result) $totalMarked++;
        }

        $this->info("Processing complete: {$totalMarked} profiles marked as inactive");
        $this->logMessage("=== Completed: {$totalMarked} profiles marked inactive ===\n");

        return 0;
    }

    protected function markInactive($profile, $profileType)
    {
        try {
            $lastLoginAt = \Carbon\Carbon::parse($profile->last_login_at);
            $daysSinceLogin = now()->diffInDays($lastLoginAt);

            // Set inactive_at to current timestamp
            $profile->inactive_at = now();
            $profile->save();

            $this->logMessage("[{$profileType}] Marked INACTIVE: {$profile->name} (ID: {$profile->id}) - Not logged in for {$daysSinceLogin} days (last login: {$lastLoginAt->format('Y-m-d')})");
            $this->info("[{$profileType}] Marked inactive: {$profile->name} ({$daysSinceLogin} days)");

            return true;
        } catch (\Exception $e) {
            $this->logMessage("[{$profileType}] ERROR marking {$profile->name} (ID: {$profile->id}) inactive: {$e->getMessage()}");
            $this->error("[{$profileType}] Error: {$profile->name}: {$e->getMessage()}");
            return false;
        }
    }

    protected function logMessage($message)
    {
        $timestamp = now()->format('Y-m-d H:i:s');
        $logEntry = "[{$timestamp}] {$message}\n";

        file_put_contents($this->logFile, $logEntry, FILE_APPEND);
        Log::info($message);
    }
}
