<?php
declare(strict_types=1);

use App\Core\Database;

/**
 * Ensure open fiscal years exist for ALL years that have financial data.
 *
 * Without a fiscal year, ALL auto-posted journal entries silently fail
 * because JournalService::createEntry() requires FiscalYear::findByDate().
 *
 * This seed:
 * 1. Scans payments, fines, sales, payroll for the earliest and latest dates
 * 2. Creates a fiscal year for every calendar year in that range (+ current year)
 * 3. Ensures exactly the current-year fiscal year is marked is_current = 1
 *
 * SAFE TO RE-RUN: Skips years that already have a fiscal year.
 *
 * Run: php cli.php seed
 */
return function (Database $db): void {

    $now = date('Y-m-d H:i:s');
    $currentYear = (int) date('Y');

    // Find the range of years with financial data
    $minMaxQueries = [
        "SELECT MIN(payment_date) as min_date, MAX(payment_date) as max_date FROM payments WHERE is_voided = 0",
    ];

    // Optional tables — only query if they exist
    $optionalTables = [
        'fines'          => "SELECT MIN(created_at) as min_date, MAX(created_at) as max_date FROM fines",
        'sales'          => "SELECT MIN(sale_date) as min_date, MAX(sale_date) as max_date FROM sales WHERE status = 'completed'",
        'hr_payroll_runs' => "SELECT MIN(paid_at) as min_date, MAX(paid_at) as max_date FROM hr_payroll_runs WHERE status = 'paid'",
        'installment_plans' => "SELECT MIN(created_at) as min_date, MAX(created_at) as max_date FROM installment_plans",
    ];

    foreach ($optionalTables as $table => $query) {
        $exists = $db->selectOne("SELECT 1 FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = ?", [$table]);
        if ($exists) {
            $minMaxQueries[] = $query;
        }
    }

    $minYear = $currentYear;
    $maxYear = $currentYear;

    foreach ($minMaxQueries as $query) {
        try {
            $row = $db->selectOne($query);
            if ($row && $row['min_date']) {
                $y = (int) substr($row['min_date'], 0, 4);
                if ($y > 2000 && $y < $minYear) {
                    $minYear = $y;
                }
            }
            if ($row && $row['max_date']) {
                $y = (int) substr($row['max_date'], 0, 4);
                if ($y > 2000 && $y > $maxYear) {
                    $maxYear = $y;
                }
            }
        } catch (\Throwable $e) {
            // Table might not exist or query might fail — skip
            continue;
        }
    }

    echo "  Fiscal year range needed: {$minYear} — {$maxYear}\n";

    // Clear stale is_current flags
    $db->query("UPDATE fiscal_years SET is_current = 0 WHERE is_current = 1");

    $created = 0;
    for ($year = $minYear; $year <= $maxYear; $year++) {
        $startDate = $year . '-01-01';
        $endDate   = $year . '-12-31';

        // Check if fiscal year already exists for this range
        $existing = $db->selectOne(
            "SELECT id, status FROM fiscal_years
             WHERE start_date <= ? AND end_date >= ? AND is_archived = 0",
            [$startDate, $endDate]
        );

        if ($existing) {
            // Ensure it's open so the sync seed can post entries
            if ($existing['status'] !== 'open') {
                $db->update('fiscal_years', [
                    'status'     => 'open',
                    'updated_at' => $now,
                ], '`id` = ?', [(int) $existing['id']]);
                echo "    Reopened fiscal year {$year} for sync\n";
            }

            // Mark current year as is_current
            if ($year === $currentYear) {
                $db->update('fiscal_years', [
                    'is_current'  => 1,
                    'updated_at'  => $now,
                ], '`id` = ?', [(int) $existing['id']]);
            }
            continue;
        }

        // Create new fiscal year
        $db->insert('fiscal_years', [
            'name_ar'     => 'السنة المالية ' . $year,
            'name_en'     => 'Fiscal Year ' . $year,
            'start_date'  => $startDate,
            'end_date'    => $endDate,
            'status'      => 'open',
            'is_current'  => ($year === $currentYear) ? 1 : 0,
            'is_archived' => 0,
            'created_at'  => $now,
            'updated_at'  => $now,
        ]);
        $created++;
        echo "    Created fiscal year {$year}\n";
    }

    if ($created === 0) {
        echo "  All fiscal years already exist.\n";
    } else {
        echo "  Created {$created} fiscal year(s).\n";
    }
};
