<?php

namespace App\Console\Commands;

use App\Mail\OwnerDigest;
use App\Models\Booking;
use App\Models\HousekeepingTask;
use App\Models\InventoryItem;
use App\Models\Order;
use App\Models\Payment;
use App\Models\Room;
use App\Models\Setting;
use App\Support\Notify;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Schema;

class SendOwnerDigest extends Command
{
    protected $signature = 'epelcon:daily-digest';

    protected $description = 'Send the daily performance digest to hotel owners';

    public function handle(): int
    {
        if (class_exists(\App\Models\Hotel::class) && Schema::hasTable('hotels')) {
            foreach (\App\Models\Hotel::all() as $hotel) {
                if (class_exists(\App\Support\Tenancy::class)) {
                    \App\Support\Tenancy::set($hotel);
                }

                $this->dispatchDigest(
                    $this->computeStats(),
                    $hotel->name ?? 'Epelcon Hospitality',
                    $hotel->email,
                    $hotel->phone
                );
            }
        } else {
            $this->dispatchDigest(
                $this->computeStats(),
                Setting::get('hotel_name', 'Epelcon Hospitality'),
                Setting::get('email'),
                Setting::get('phone')
            );
        }

        $this->info('Owner digest dispatched.');

        return self::SUCCESS;
    }

    protected function computeStats(): array
    {
        $today = now()->toDateString();

        $roomsTotal = Room::count();
        $roomsOccupied = Room::where('status', 'occupied')->count();

        return [
            'revenue_today' => (float) Payment::where('status', 'completed')->whereDate('paid_at', $today)->sum('amount'),
            'orders_today' => Order::whereDate('created_at', $today)->count(),
            'occupancy' => $roomsTotal > 0 ? (int) round($roomsOccupied / $roomsTotal * 100) : 0,
            'arrivals_today' => Booking::whereDate('check_in', $today)->whereIn('status', ['pending', 'confirmed'])->count(),
            'low_stock' => InventoryItem::whereColumn('quantity', '<=', 'reorder_level')->count(),
            'pending_housekeeping' => HousekeepingTask::whereIn('status', ['pending', 'in_progress'])->count(),
        ];
    }

    protected function dispatchDigest(array $stats, string $hotelName, ?string $email, ?string $phone): void
    {
        if ($email) {
            try {
                Mail::to($email)->send(new OwnerDigest($stats, $hotelName));
            } catch (\Throwable $e) {
                Log::warning("Owner digest email failed for {$email}: " . $e->getMessage());
            }
        }

        if ($phone) {
            $currency = Setting::get('currency', '₦');
            $message = sprintf(
                'Epelcon digest: %s%s today · %d orders · %d%% occupancy · %d arrivals · %d low-stock · %d HK tasks',
                $currency,
                number_format($stats['revenue_today']),
                $stats['orders_today'],
                $stats['occupancy'],
                $stats['arrivals_today'],
                $stats['low_stock'],
                $stats['pending_housekeeping']
            );

            Notify::send($phone, $message, 'generic');
        }
    }
}
