<?php

namespace App\Console\Commands;

use App\Models\Tenant;
use App\Models\Tenant\Product;
use App\Services\TenantService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB; // Import DB facade
use Illuminate\Support\Facades\Mail; // Import Mail facade
use App\Mail\ExpiringProductsNotification; // Import the Mailable
use App\Models\User; // Assuming User model is in App\Models

class NotifyExpiringProducts extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:notify-expiring-products';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Notifies tenants about products expiring within 7 days.';

    /**
     * The TenantService instance.
     *
     * @var \App\Services\TenantService
     */
    protected $tenantService;

    /**
     * Create a new command instance.
     *
     * @param \App\Services\TenantService $tenantService
     * @return void
     */
    public function __construct(TenantService $tenantService)
    {
        parent::__construct();
        $this->tenantService = $tenantService;
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('Starting expiry notification process...');

        $tenants = Tenant::all();

        if ($tenants->isEmpty()) {
            $this->info('No tenants found. Exiting.');
            return;
        }

        foreach ($tenants as $tenant) {
            $this->info("Processing tenant: {$tenant->name} (ID: {$tenant->id})");

            try {
                $this->tenantService->switchToTenant($tenant);
                
                $expiringProducts = Product::whereNotNull('expiry_date')
                                            ->where('expiry_date', '<=', now()->addDays(7))
                                            ->get();

                if ($expiringProducts->isNotEmpty()) {
                    $this->warn("Tenant {$tenant->name} has " . $expiringProducts->count() . " products expiring soon.");
                    
                    // Find the tenant's admin user to send the notification
                    // Assuming the first user associated with the tenant is the admin
                    $adminUser = User::where('tenant_id', $tenant->id)->first();

                    if ($adminUser && $adminUser->email) {
                        Mail::to($adminUser->email)->send(new ExpiringProductsNotification($tenant, $expiringProducts));
                        $this->info("Expiry notification email sent to {$adminUser->email} for tenant {$tenant->name}.");
                    } else {
                        $this->warn("No admin user found or email missing for tenant {$tenant->name}. Skipping email notification.");
                    }

                    foreach ($expiringProducts as $product) {
                        Log::info("Product expiring soon for tenant {$tenant->name}: {$product->name} (Expiry: {$product->expiry_date->format('Y-m-d')})");
                    }
                } else {
                    $this->info("No products expiring soon for tenant {$tenant->name}.");
                }
            } catch (\Exception $e) {
                $this->error("Error processing tenant {$tenant->name}: " . $e->getMessage());
                Log::error("Expiry notification error for tenant {$tenant->name}: " . $e->getMessage());
            } finally {
                // Switch back to central connection after processing each tenant
                DB::setDefaultConnection('mysql');
                DB::purge('tenant'); // Clear tenant connection to prevent issues
            }
        }

        $this->info('Expiry notification process completed.');
    }
}
