<?php

namespace App\Console\Commands;

use App\Mail\DocumentExpiryNotification;
use App\Models\Document; // Import the Mailable
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail; // Import the Mail facade

class CheckExpiringDocuments extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'documents:check-expiring';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Checks for documents expiring soon and logs them.';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('Checking for expiring documents...');

        $expiringSoon = Document::where('expiry_date', '!=', null)
            ->where('expiry_date', '<=', now()->addDays((int) config('documents.expiry_threshold_days')))
            ->where('expiry_date', '>=', now())
            ->where('status', 'valid')
            ->get();

        if ($expiringSoon->isEmpty()) {
            $this->info('No documents expiring in the next 30 days.');
            Log::info('No documents expiring in the next 30 days.');

            return Command::SUCCESS;
        }

        $this->warn('Found '.$expiringSoon->count().' documents expiring soon:');
        Log::warning('Found '.$expiringSoon->count().' documents expiring soon:');

        foreach ($expiringSoon as $document) {
            $message = sprintf(
                "Document '%s' (ID: %d) for %s (ID: %d) expires on %s.",
                $document->name,
                $document->id,
                $document->documentable_type,
                $document->documentable_id,
                $document->expiry_date->format('Y-m-d')
            );
            $this->line($message);
            Log::warning($message);
        }

        // Send email notification
        // For now, send to a fixed email address. In a real app, this would be configurable
        // or sent to relevant users (e.g., employee's email, admin email).
        $recipientEmail = env('MAIL_TO_EXPIRING_DOCUMENTS', 'admin@example.com'); // Use a configurable email

        try {
            Mail::to($recipientEmail)->send(new DocumentExpiryNotification($expiringSoon));
            $this->info('Email notification sent for expiring documents to '.$recipientEmail);
            Log::info('Email notification sent for expiring documents to '.$recipientEmail);
        } catch (\Exception $e) {
            $this->error('Failed to send email notification: '.$e->getMessage());
            Log::error('Failed to send email notification: '.$e->getMessage());
        }

        $this->info('Expiring documents check completed.');

        return Command::SUCCESS;
    }
}
