<?php

namespace Database\Seeders;

use App\Models\DeductionSection;
use App\Models\IncomeTaxPlan;
use App\Models\TaxSlab;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

/**
 * Seeds current India income tax slabs (Union Budget FY 2025-26) and Chapter VI-A deduction sections.
 *
 * New regime: standard deduction ₹75,000; slabs per Section 115BAC (as amended).
 * Old regime: standard deduction ₹50,000; classic slab rates with Chapter VI-A deductions.
 */
class IndianIncomeTaxSeeder extends Seeder
{
    public function run(): void
    {
        DB::transaction(function () {
            $this->seedDeductionSections();
            $this->seedOldRegimePlan();
            $this->seedNewRegimePlan();
        });
    }

    protected function seedDeductionSections(): void
    {
        $sections = [
            [
                'section_code' => '80C',
                'section_name' => 'Section 80C — PPF, ELSS, LIC, EPF, tuition fees, etc.',
                'limit_amount' => 150000,
                'description' => 'Combined limit for 80C, 80CCC and 80CCD(1). Includes PPF, ELSS, life insurance premium, principal on home loan, EPF/VPF, NSC, SSY, tuition fees (2 children), etc.',
            ],
            [
                'section_code' => '80CCD1B',
                'section_name' => 'Section 80CCD(1B) — Additional NPS contribution',
                'limit_amount' => 50000,
                'description' => 'Additional deduction for NPS (Tier I) over and above the ₹1.5 lakh limit under 80C.',
            ],
            [
                'section_code' => '80D',
                'section_name' => 'Section 80D — Health insurance (self, spouse, children)',
                'limit_amount' => 25000,
                'description' => 'Medical insurance premium for self, spouse and dependent children. ₹50,000 if assessee or spouse is senior citizen.',
            ],
            [
                'section_code' => '80D_PARENT',
                'section_name' => 'Section 80D — Health insurance (parents)',
                'limit_amount' => 25000,
                'description' => 'Medical insurance premium for parents. ₹50,000 if parents are senior citizens.',
            ],
            [
                'section_code' => '80DD',
                'section_name' => 'Section 80DD — Maintenance / medical of disabled dependent',
                'limit_amount' => 75000,
                'description' => '₹1,25,000 for severe disability. Requires disability certificate.',
            ],
            [
                'section_code' => '80DDB',
                'section_name' => 'Section 80DDB — Medical treatment (specified diseases)',
                'limit_amount' => 40000,
                'description' => '₹1,00,000 for senior citizens. For specified ailments per IT rules.',
            ],
            [
                'section_code' => '80E',
                'section_name' => 'Section 80E — Interest on education loan',
                'limit_amount' => null,
                'description' => 'Deduction for interest on loan taken for higher education. No upper limit; available for up to 8 years.',
            ],
            [
                'section_code' => '80EE',
                'section_name' => 'Section 80EE — Home loan interest (first-time homebuyer)',
                'limit_amount' => 50000,
                'description' => 'Additional interest on home loan for first-time buyers (subject to conditions in IT Act).',
            ],
            [
                'section_code' => '80EEA',
                'section_name' => 'Section 80EEA — Affordable housing loan interest',
                'limit_amount' => 150000,
                'description' => 'Interest on home loan for affordable housing (stamp duty value ≤ ₹45 lakh, subject to conditions).',
            ],
            [
                'section_code' => '80G',
                'section_name' => 'Section 80G — Donations to charitable institutions',
                'limit_amount' => null,
                'description' => '50% or 100% deduction depending on fund and mode of payment. Some donations have qualifying limits.',
            ],
            [
                'section_code' => '80TTA',
                'section_name' => 'Section 80TTA — Savings account interest',
                'limit_amount' => 10000,
                'description' => 'Interest on savings accounts (not applicable to senior citizens who use 80TTB).',
            ],
            [
                'section_code' => '80TTB',
                'section_name' => 'Section 80TTB — Interest income (senior citizens)',
                'limit_amount' => 50000,
                'description' => 'Interest on deposits for resident senior citizens (replaces 80TTA for seniors).',
            ],
            [
                'section_code' => '80U',
                'section_name' => 'Section 80U — Disability (self)',
                'limit_amount' => 75000,
                'description' => '₹1,25,000 for severe disability. Requires disability certificate.',
            ],
            [
                'section_code' => 'HRA',
                'section_name' => 'House Rent Allowance (HRA) exemption',
                'limit_amount' => null,
                'description' => 'Least of: actual HRA received, rent paid minus 10% of salary, or 50%/40% of salary (metro/non-metro). Requires rent receipts.',
            ],
            [
                'section_code' => 'LTA',
                'section_name' => 'Leave Travel Allowance (LTA) exemption',
                'limit_amount' => null,
                'description' => 'Twice in a block of four calendar years. Actual travel cost within India for self and family.',
            ],
            [
                'section_code' => '80CCD2',
                'section_name' => 'Section 80CCD(2) — Employer NPS contribution',
                'limit_amount' => null,
                'description' => 'Employer contribution to NPS — up to 10% of salary (14% for Central Govt). Not part of 80C limit.',
            ],
        ];

        foreach ($sections as $row) {
            DeductionSection::query()->updateOrCreate(
                ['section_code' => $row['section_code']],
                [
                    'section_code' => $row['section_code'],
                    'section_name' => $row['section_name'],
                    'limit_amount' => $row['limit_amount'],
                    'description' => $row['description'],
                    'is_active' => true,
                    'proof_required' => $row['proof_required'] ?? true,
                ]
            );
        }

        DeductionSection::query()
            ->where('section_code', '*80C')
            ->orWhere('section_code', 'like', '*%')
            ->update(['is_active' => false]);
    }

    protected function seedOldRegimePlan(): void
    {
        $plan = IncomeTaxPlan::query()->updateOrCreate(
            ['plan_code' => 'IND-OLD-2025'],
            [
                'plan_name' => 'India Old Regime (FY 2025-26)',
                'allow_deductions' => true,
                'standard_deduction' => 50000,
                'description' => 'Indian Income Tax Act — old regime with Chapter VI-A deductions. Slabs per Section 115BAC(1A) opt-out / legacy rates. Standard deduction ₹50,000 for salaried. Health & education cess 4%.',
                'effective_from' => '2025-04-01',
                'effective_to' => '2027-03-31',
                'is_active' => true,
            ]
        );

        IncomeTaxPlan::query()
            ->where('plan_code', 'Old-Regime')
            ->where('id', '!=', $plan->id)
            ->update(['is_active' => false]);

        $this->syncSlabs($plan, [
            ['slab_no' => 1, 'min_amount' => 0, 'max_amount' => 250000, 'tax_rate' => 0, 'cess_rate' => 4],
            ['slab_no' => 2, 'min_amount' => 250000, 'max_amount' => 500000, 'tax_rate' => 5, 'cess_rate' => 4],
            ['slab_no' => 3, 'min_amount' => 500000, 'max_amount' => 1000000, 'tax_rate' => 20, 'cess_rate' => 4],
            ['slab_no' => 4, 'min_amount' => 1000000, 'max_amount' => null, 'tax_rate' => 30, 'cess_rate' => 4],
        ]);
    }

    protected function seedNewRegimePlan(): void
    {
        $plan = IncomeTaxPlan::query()->updateOrCreate(
            ['plan_code' => 'IND-NEW-2025'],
            [
                'plan_name' => 'India New Regime (FY 2025-26)',
                'allow_deductions' => false,
                'standard_deduction' => 75000,
                'description' => 'Section 115BAC default regime (FY 2025-26). Standard deduction ₹75,000. No Chapter VI-A deductions except employer NPS. Rebate u/s 87A may apply up to ₹12 lakh taxable income. Cess 4%.',
                'effective_from' => '2025-04-01',
                'effective_to' => '2027-03-31',
                'is_active' => true,
            ]
        );

        $this->syncSlabs($plan, [
            ['slab_no' => 1, 'min_amount' => 0, 'max_amount' => 400000, 'tax_rate' => 0, 'cess_rate' => 4],
            ['slab_no' => 2, 'min_amount' => 400000, 'max_amount' => 800000, 'tax_rate' => 5, 'cess_rate' => 4],
            ['slab_no' => 3, 'min_amount' => 800000, 'max_amount' => 1200000, 'tax_rate' => 10, 'cess_rate' => 4],
            ['slab_no' => 4, 'min_amount' => 1200000, 'max_amount' => 1600000, 'tax_rate' => 15, 'cess_rate' => 4],
            ['slab_no' => 5, 'min_amount' => 1600000, 'max_amount' => 2000000, 'tax_rate' => 20, 'cess_rate' => 4],
            ['slab_no' => 6, 'min_amount' => 2000000, 'max_amount' => 2400000, 'tax_rate' => 25, 'cess_rate' => 4],
            ['slab_no' => 7, 'min_amount' => 2400000, 'max_amount' => null, 'tax_rate' => 30, 'cess_rate' => 4],
        ]);
    }

    protected function syncSlabs(IncomeTaxPlan $plan, array $slabs): void
    {
        $plan->taxSlabs()->delete();

        foreach ($slabs as $slab) {
            TaxSlab::query()->create([
                'plan_id' => $plan->id,
                'slab_no' => $slab['slab_no'],
                'min_amount' => $slab['min_amount'],
                'max_amount' => $slab['max_amount'],
                'tax_rate' => $slab['tax_rate'],
                'cess_rate' => $slab['cess_rate'],
            ]);
        }
    }
}
