<?php

namespace App\Console\Commands;

use App\Models\EmployeeDocument;
use App\Models\ReminderHistory;
use App\Models\TenantDocument;
use Illuminate\Console\Command;

class CheckDocumentExpiries extends Command
{
    protected $signature = 'compliance:check-expiries';

    protected $description = 'Check expiring company trade licenses and employee passports/visas and record reminder history.';

    public function handle(): int
    {
        $this->info('Scanning compliance document expiry dates...');

        // 1. Company Documents
        $companyDocs = TenantDocument::where('expiry_reminder_enabled', true)
            ->where('expiry_date', '<=', now()->addDays(90))
            ->get();

        foreach ($companyDocs as $doc) {
            $days = now()->diffInDays($doc->expiry_date, false);
            ReminderHistory::firstOrCreate([
                'tenant_id' => $doc->tenant_id,
                'entity_type' => 'company_document',
                'entity_id' => $doc->id,
                'days_before_expiry' => $days,
            ], [
                'scheduled_date' => now(),
                'sent_at' => now(),
                'channel' => 'in_app',
                'status' => 'sent',
            ]);
        }

        // 2. Employee Documents
        $empDocs = EmployeeDocument::where('reminder_enabled', true)
            ->where('expiry_date', '<=', now()->addDays(90))
            ->get();

        foreach ($empDocs as $doc) {
            $days = now()->diffInDays($doc->expiry_date, false);
            ReminderHistory::firstOrCreate([
                'tenant_id' => $doc->tenant_id,
                'entity_type' => 'employee_document',
                'entity_id' => $doc->id,
                'days_before_expiry' => $days,
            ], [
                'scheduled_date' => now(),
                'sent_at' => now(),
                'channel' => 'in_app',
                'status' => 'sent',
            ]);
        }

        $this->info('Compliance document expiry scan completed.');

        return Command::SUCCESS;
    }
}
