<?php

namespace App\Console\Commands;

use App\System;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;

class ForceLogoutAllUsers extends Command
{
    protected $signature = 'pos:forceLogoutAllUsers
                            {--now : Force logout immediately, ignoring the scheduled time}';

    protected $description = 'Force-logout all active users by clearing their sessions. '
                           . 'Reads force_logout_at from system settings (YYYY-MM-DD HH:MM:SS). '
                           . 'Use --now to run immediately without a schedule check.';

    public function handle(): int
    {
        if (!$this->option('now')) {
            $scheduledAt = System::getProperty('force_logout_at');

            if (empty($scheduledAt)) {
                // No scheduled logout configured — nothing to do.
                return 0;
            }

            try {
                $scheduledTime = Carbon::parse($scheduledAt);
            } catch (\Throwable $e) {
                $this->error('Invalid force_logout_at value: ' . $scheduledAt);
                return 1;
            }

            if (Carbon::now()->lt($scheduledTime)) {
                // Target time has not arrived yet.
                return 0;
            }
        }

        $cleared = $this->clearSessions();

        // Remove the setting so it does not fire again on the next cron tick.
        if (!$this->option('now')) {
            System::removeProperty('force_logout_at');
        }

        $msg = $cleared >= 0
            ? "Force-logout complete. {$cleared} session(s) cleared."
            : 'Force-logout complete (cache-based sessions flushed).';

        $this->info($msg);
        Log::info('pos:forceLogoutAllUsers — ' . $msg);

        return 0;
    }

    private function clearSessions(): int
    {
        $driver = config('session.driver');

        if ($driver === 'file') {
            $path = config('session.files', storage_path('framework/sessions'));
            if (!is_dir($path)) {
                return 0;
            }
            $files = File::files($path);
            foreach ($files as $file) {
                File::delete($file->getPathname());
            }
            return count($files);
        }

        if ($driver === 'database') {
            return DB::table(config('session.table', 'sessions'))->delete();
        }

        // Redis / Memcached / other cache-based drivers
        \Illuminate\Support\Facades\Cache::store(config('session.store'))->flush();
        return -1;
    }
}
