<?php
/**
 * Invoice Auto-Generation Scheduler
 * This script should be run by cron daily to check if invoices need to be generated
 * Example cron setup: 0 2 * * * /usr/bin/php /path/to/ssci/cron/scheduler.php
 */

// Change to the project root
chdir(dirname(__DIR__));

require_once 'config/bootstrap.php';

use SSCI\Classes\Database;

$dbConfig = require 'config/database.php';
$db = new Database($dbConfig);

// Check if auto-generation is enabled
$autoGenEnabled = $db->fetch("SELECT value FROM settings WHERE key = ?", ['auto_generate_invoices']);
if (!$autoGenEnabled || $autoGenEnabled['value'] !== '1') {
    exit("Auto-generation is disabled\n");
}

// Get scheduling settings
$daySettings = $db->fetch("SELECT value FROM settings WHERE key = ?", ['auto_generate_day']);
$timeSettings = $db->fetch("SELECT value FROM settings WHERE key = ?", ['auto_generate_time']);

$generationDay = $daySettings ? (int)$daySettings['value'] : 15;
$generationTime = $timeSettings ? $timeSettings['value'] : '02:00';

// Check if today is the generation day
$currentDay = (int)date('d');
$currentTime = date('H:i');

// Parse generation time (HH:mm format)
list($hour, $minute) = explode(':', $generationTime);
$generationMinutes = ($hour * 60) + (int)$minute;
$currentMinutes = (int)date('H') * 60 + (int)date('i');

// Allow 5-minute window for execution
$timeWindow = 5 * 60; // 5 minutes in seconds

if ($currentDay === $generationDay && abs($generationMinutes - $currentMinutes) <= $timeWindow) {
    echo "Generating invoices for month: " . date('Y-m') . "\n";
    
    // Get all active posts
    $posts = $db->fetchAll("SELECT id FROM posts WHERE status = 'Active'");
    
    if (empty($posts)) {
        echo "No active posts found\n";
        exit(0);
    }

    $postIds = array_map(fn($p) => $p['id'], $posts);
    
    // Call the invoice generation function
    $billingMonth = date('Y-m');
    $invoiceDate = date('Y-m-01');
    $dueDate = date('Y-m-d', strtotime("$invoiceDate +30 days"));
    $userId = 1; // System user
    $generatedCount = 0;
    
    // Get currency
    $appConfig = require 'config/app.php';
    $currency = $appConfig['currency']['code'] ?? 'FCFA';

    foreach ($postIds as $postId) {
        // Get post details
        $post = $db->fetch("SELECT * FROM posts WHERE id = ? AND status = 'Active'", [$postId]);

        if (!$post) {
            continue;
        }

        // Get owner_id from post
        $clientId = $post['owner_id'] ?? null;
        
        if (!$clientId) {
            continue;
        }

        // Check if invoice already exists for this month
        $existing = $db->fetch(
            "SELECT id FROM invoices WHERE owner_id = ? AND post_id = ? AND DATE_FORMAT(invoice_date, '%Y-%m') = ?",
            [$clientId, $postId, $billingMonth]
        );

        if ($existing) continue;

        // Generate invoice
        require_once 'public/api.php';
        $invoiceNumber = generateInvoiceNumber($db);
        
        $db->query(
            "INSERT INTO invoices (invoice_number, owner_id, post_id, invoice_date, due_date, currency, status, created_by, created_at)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())",
            [
                $invoiceNumber,
                $clientId,
                $postId,
                $invoiceDate,
                $dueDate,
                $currency,
                'Draft',
                $userId
            ]
        );

        $invoiceId = $db->lastInsertId();

        // Add line items from post services
        $services = [];
        if (!empty($post['services'])) {
            $services = json_decode($post['services'], true) ?: [];
        }

        if (!empty($services) && is_array($services)) {
            foreach ($services as $service) {
                $description = $service['name'] ?? 'Service';
                $quantity = (float)($service['quantity'] ?? 1);
                $unitPrice = (float)($service['price'] ?? 0);
                $lineTotal = $quantity * $unitPrice;

                $db->query(
                    "INSERT INTO invoice_items (invoice_id, description, quantity, unit_price, line_total)
                     VALUES (?, ?, ?, ?, ?)",
                    [
                        $invoiceId,
                        $description,
                        $quantity,
                        $unitPrice,
                        $lineTotal
                    ]
                );
            }
        } else {
            // Fallback: Default line item
            $monthName = date('F');
            $db->query(
                "INSERT INTO invoice_items (invoice_id, description, quantity, unit_price, line_total)
                 VALUES (?, ?, ?, ?, ?)",
                [
                    $invoiceId,
                    "Security Services - {$monthName}",
                    1,
                    5000.00,
                    5000.00
                ]
            );
        }

        // Update invoice totals
        updateInvoiceTotals($db, $invoiceId);

        $generatedCount++;
    }

    echo "Generated $generatedCount invoices\n";
} else {
    echo "Not scheduled for auto-generation. Current day: $currentDay, Scheduled: $generationDay\n";
}

exit(0);
?>
