<?php
namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Client;
use App\Models\Invoice;
use App\Models\InvoiceItem;
use App\Models\Visit;

class GenerateRecurringInvoice extends Command
{
    protected $signature   = 'invoice:recurring';
    protected $description = 'Generate monthly maintenance invoices';

    public function handle(): void
    {
        $clients = Client::where('type','maintenance')->where('is_active',1)->get();
        $month   = now()->month;
        $year    = now()->year;
        $count   = 0;

        foreach ($clients as $client) {
            $exists = Invoice::where('client_id',$client->id)
                ->where('billing_month',$month)
                ->where('billing_year',$year)
                ->where('type','maintenance')
                ->exists();
            if ($exists) continue;

            $extraVisits = Visit::where('client_id',$client->id)
                ->where('is_extra',1)
                ->whereMonth('visit_date', now()->subMonth()->month)
                ->whereYear('visit_date', now()->subMonth()->year)
                ->count();

            $invoice = Invoice::create([
                'invoice_number' => Invoice::generateNumber($client->division),
                'client_id'      => $client->id,
                'created_by'     => 1,
                'division'       => $client->division,
                'type'           => 'maintenance',
                'issue_date'     => now(),
                'due_date'       => now()->addDays(14),
                'billing_month'  => $month,
                'billing_year'   => $year,
                'tax_percent'    => 0,
                'status'         => 'draft',
                'is_recurring'   => true,
            ]);

            InvoiceItem::create([
                'invoice_id'  => $invoice->id,
                'description' => "Biaya Maintenance ".now()->format('F Y'),
                'qty'         => 1,
                'unit_price'  => $client->monthly_fee,
                'total'       => $client->monthly_fee,
            ]);

            if ($extraVisits > 0) {
                $extraTotal = $extraVisits * $client->extra_visit_fee;
                InvoiceItem::create([
                    'invoice_id'  => $invoice->id,
                    'description' => "Kunjungan Ekstra ({$extraVisits}x)",
                    'qty'         => $extraVisits,
                    'unit_price'  => $client->extra_visit_fee,
                    'total'       => $extraTotal,
                ]);
            }
            $invoice->recalculate();
            $count++;
        }
        $this->info("Generated {$count} recurring invoices.");
    }
}
