<?php
declare(strict_types=1);

use App\Core\Database;

return function (Database $db): void {
    $offers = $db->select("SELECT id FROM board_offers WHERE is_active = 1 ORDER BY id");
    if (empty($offers)) {
        return;
    }

    foreach ($offers as $offer) {
        $offerId = (int) $offer['id'];

        $existing = $db->selectOne(
            "SELECT id FROM board_offer_tiers WHERE board_offer_id = ? LIMIT 1",
            [$offerId]
        );
        if ($existing) {
            continue;
        }

        $tiers = [
            [
                'tier_order'        => 1,
                'tier_name_ar'      => 'كاش — خصم 10%',
                'payment_type'      => 'cash',
                'cash_discount_pct' => '10.00',
                'down_payment_pct'  => null,
                'months'            => null,
                'interest_rate'     => null,
            ],
            [
                'tier_order'        => 2,
                'tier_name_ar'      => 'تقسيط 24 شهر — بدون فوائد',
                'payment_type'      => 'installment',
                'cash_discount_pct' => null,
                'down_payment_pct'  => '50.00',
                'months'            => 24,
                'interest_rate'     => '0.00',
            ],
            [
                'tier_order'        => 3,
                'tier_name_ar'      => 'تقسيط 40 شهر — فائدة 15%',
                'payment_type'      => 'installment',
                'cash_discount_pct' => null,
                'down_payment_pct'  => '33.33',
                'months'            => 40,
                'interest_rate'     => '15.00',
            ],
            [
                'tier_order'        => 4,
                'tier_name_ar'      => 'تقسيط 60 شهر — فائدة 15%',
                'payment_type'      => 'installment',
                'cash_discount_pct' => null,
                'down_payment_pct'  => '13.33',
                'months'            => 60,
                'interest_rate'     => '15.00',
            ],
        ];

        foreach ($tiers as $tier) {
            $db->insert('board_offer_tiers', array_merge($tier, [
                'board_offer_id' => $offerId,
                'is_active'      => 1,
                'created_at'     => date('Y-m-d H:i:s'),
                'updated_at'     => date('Y-m-d H:i:s'),
            ]));
        }
    }
};
