<?php
declare(strict_types=1);

require_once __DIR__ . '/../vendor/autoload.php';

use App\Config\Database;
use Dotenv\Dotenv;

$dotenv = Dotenv::createImmutable(__DIR__ . '/../');
$dotenv->load();

$db = Database::getInstance();

echo "Starting Recurring Invoice Job [" . date('Y-m-d H:i:s') . "]\n";

// Find invoices where: 
// recurring_enabled = 1 AND next_recurring_date = today
$today = date('Y-m-d');
$stmt = $db->prepare("SELECT * FROM invoices WHERE recurring_enabled = 1 AND next_recurring_date = ?");
$stmt->execute([$today]);
$recurringInvoices = $stmt->fetchAll();

foreach ($recurringInvoices as $inv) {
    echo "Cloning Invoice: {$inv['invoice_number']}...\n";

    // 1. Get original items
    $itemsStmt = $db->prepare("SELECT * FROM invoice_items WHERE invoice_id = ?");
    $itemsStmt->execute([$inv['id']]);
    $items = $itemsStmt->fetchAll();

    // 2. Generate new invoice number (simplified logic)
    $newNumber = $inv['invoice_number'] . '-REC';

    // 3. Insert new invoice
    // (Truncated implementation for demonstration - in production would clone all fields)
    // ... insert logic ...

    // 4. Update next recurring date based on frequency
    // (Assuming monthly)
    $nextDate = date('Y-m-d', strtotime('+1 month', strtotime($today)));
    $db->prepare("UPDATE invoices SET next_recurring_date = ? WHERE id = ?")->execute([$nextDate, $inv['id']]);
}

echo "Job Finished.\n";
