<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\RecurringInvoice;
use App\Models\Invoice;
use App\Models\InvoiceItem;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class ProcessRecurringInvoices extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'invoices:process';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Process due recurring invoices and generate real invoices';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $today = Carbon::today();

        $due = RecurringInvoice::where('is_active', true)
            ->where('next_run_date', '<=', $today)
            ->where(function ($q) use ($today) {
                $q->whereNull('end_date')
                    ->orWhere('end_date', '>=', $today);
            })
            ->get();

        $this->info("Found {$due->count()} recurring invoices due for processing.");

        foreach ($due as $subscription) {
            DB::transaction(function () use ($subscription) {
                // Create Invoice
                $invoice = Invoice::create([
                    'customer_id' => $subscription->customer_id,
                    'code' => 'INV-' . strtoupper(uniqid()), // Ideally use a sequence generator
                    'date' => Carbon::today(),
                    'due_date' => Carbon::today()->addDays(7),
                    'status' => 'sent', // Assume sent or draft
                    'notes' => 'Generated from subscription: ' . $subscription->title,
                    'tax_percent' => 14, // Default tax or from settings
                ]);

                // Create Items
                $subtotal = 0;
                foreach ($subscription->items as $item) {
                    $total = $item['quantity'] * $item['unit_price'];
                    $subtotal += $total;

                    InvoiceItem::create([
                        'invoice_id' => $invoice->id,
                        'description' => $item['description'],
                        'quantity' => $item['quantity'],
                        'unit_price' => $item['unit_price'],
                        'total' => $total,
                    ]);
                }

                // Update Totals
                $taxAmount = $subtotal * 0.14;
                $invoice->update([
                    'subtotal' => $subtotal,
                    'tax_amount' => $taxAmount,
                    'total' => $subtotal + $taxAmount,
                ]);

                // Update Subscription Next Run Date
                $subscription->last_run_at = now();
                $subscription->next_run_date = $subscription->calculateNextRunDate($subscription->next_run_date);
                $subscription->save();

                $this->info("Generated Invoice {$invoice->code} for Subscription #{$subscription->id}");
            });
        }
    }
}
