<?php
    $declaration = $taxDeclaration ?? null;
    $sections = $taxSections ?? [];
    $projection = $taxProjection ?? [];
    $windowOpen = $taxWindowOpen ?? true;
    $financialYear = $taxFinancialYear ?? \App\Support\FinancialYear::forDate();
    $proofMandatory = ($taxSettings['proof_mandatory'] ?? '0') === '1';
    $ui = $taxUiState ?? [
        'mode' => 'edit',
        'label' => 'Not started',
        'hint' => 'Choose regime and save to start your declaration.',
        'can_edit' => $windowOpen,
        'can_save' => $windowOpen,
        'can_submit' => false,
        'can_upload_proofs' => false,
    ];
    $selectedRegime = old('regime', $declaration->regime ?? 'new');
    $itemMap = collect($declaration?->items ?? [])->keyBy('section_code');
    $proofBadge = [
        'pending' => 'bg-amber-100 text-amber-800',
        'approved' => 'bg-emerald-100 text-emerald-800',
        'rejected' => 'bg-red-100 text-red-800',
    ];
    $grossAnnual = (float) ($declaration->gross_annual_estimate ?? ($projection['gross_annual'] ?? 0));
?>

<div
    class="space-y-5"
    x-data="incomeTaxForm({
        financialYear: <?php echo \Illuminate\Support\Js::from($financialYear)->toHtml() ?>,
        regime: <?php echo \Illuminate\Support\Js::from($selectedRegime)->toHtml() ?>,
        canEdit: <?php echo \Illuminate\Support\Js::from((bool) $ui['can_edit'])->toHtml() ?>,
        previewUrl: <?php echo \Illuminate\Support\Js::from(route('payroll.income-tax.preview'))->toHtml() ?>,
        saveUrl: <?php echo \Illuminate\Support\Js::from(route('payroll.income-tax.store'))->toHtml() ?>,
        submitUrl: <?php echo \Illuminate\Support\Js::from(route('payroll.income-tax.submit'))->toHtml() ?>,
        projection: <?php echo \Illuminate\Support\Js::from([
            'gross_annual' => $grossAnnual,
            'deductions' => (float) ($projection['deductions'] ?? 0),
            'taxable_income' => (float) ($projection['taxable_income'] ?? 0),
            'annual_tax' => (float) ($projection['annual_tax'] ?? 0),
            'monthly_tds' => (float) ($projection['monthly_tds'] ?? 0),
        ])->toHtml() ?>,
        csrf: <?php echo \Illuminate\Support\Js::from(csrf_token())->toHtml() ?>,
    })"
>
    <div class="flex flex-wrap items-start justify-between gap-4">
        <div>
            <h2 class="text-lg font-semibold text-slate-900">Income Tax — FY <?php echo e($financialYear); ?></h2>
            <p class="mt-1 text-sm text-slate-600">Declare your regime and deductions. HR verifies before TDS is applied.</p>
        </div>
        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($declaration && $declaration->status === 'verified'): ?>
            <a href="<?php echo e(route('payroll.income-tax.form16', ['financialYear' => $financialYear, 'download' => 1])); ?>"
               class="inline-flex rounded-lg bg-primary px-4 py-2 text-sm font-medium text-white hover:bg-primary/90">
                Download Form 16
            </a>
        <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
    </div>

    <div x-show="flash.message" x-cloak
         :class="flash.ok ? 'border-emerald-200 bg-emerald-50 text-emerald-800' : 'border-red-200 bg-red-50 text-red-800'"
         class="rounded-lg border px-4 py-3 text-sm" x-text="flash.message"></div>

    <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
        <div class="flex flex-wrap items-center gap-3">
            <span class="inline-flex rounded-full px-3 py-1 text-xs font-semibold uppercase tracking-wide
                <?php echo e($ui['mode'] === 'locked' ? 'bg-emerald-100 text-emerald-800' : ($ui['mode'] === 'proof_only' ? 'bg-amber-100 text-amber-800' : 'bg-slate-100 text-slate-700')); ?>">
                <?php echo e($ui['label']); ?>

            </span>
            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if (! ($windowOpen)): ?>
                <span class="text-xs font-medium text-amber-700">Declaration window closed</span>
            <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
            <span x-show="previewLoading" x-cloak class="text-xs text-slate-400">Updating estimate…</span>
        </div>
        <p class="mt-2 text-sm text-slate-600"><?php echo e($ui['hint']); ?></p>
        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($declaration?->hr_remarks): ?>
            <p class="mt-2 rounded-lg bg-amber-50 px-3 py-2 text-sm text-amber-900"><strong>HR:</strong> <?php echo e($declaration->hr_remarks); ?></p>
        <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
    </div>

    <div class="grid gap-5 lg:grid-cols-3">
        <div class="space-y-5 lg:col-span-2">
            <?php if (isset($component)) { $__componentOriginal53747ceb358d30c0105769f8471417f6 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal53747ceb358d30c0105769f8471417f6 = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.card','data' => []] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('card'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes([]); ?>
                <div class="space-y-5">
                    <div>
                        <h3 class="text-sm font-semibold text-slate-900">1. Tax regime</h3>
                        <div class="mt-3 flex flex-col gap-2 sm:flex-row sm:gap-4">
                            <label class="flex flex-1 cursor-pointer items-start gap-3 rounded-lg border p-3"
                                   :class="regime === 'new' ? 'border-primary bg-primary/5' : 'border-slate-200'">
                                <input type="radio" value="new" x-model="regime" @change="schedulePreview()" <?php echo e(!$ui['can_edit'] ? 'disabled' : ''); ?> class="mt-0.5">
                                <span>
                                    <span class="block text-sm font-medium text-slate-900">New regime</span>
                                    <span class="block text-xs text-slate-500">No proof uploads</span>
                                </span>
                            </label>
                            <label class="flex flex-1 cursor-pointer items-start gap-3 rounded-lg border p-3"
                                   :class="regime === 'old' ? 'border-primary bg-primary/5' : 'border-slate-200'">
                                <input type="radio" value="old" x-model="regime" @change="schedulePreview()" <?php echo e(!$ui['can_edit'] ? 'disabled' : ''); ?> class="mt-0.5">
                                <span>
                                    <span class="block text-sm font-medium text-slate-900">Old regime</span>
                                    <span class="block text-xs text-slate-500">80C, HRA + proofs</span>
                                </span>
                            </label>
                        </div>
                    </div>

                    <div x-show="regime === 'old'" x-cloak>
                        <h3 class="text-sm font-semibold text-slate-900">2. Deductions &amp; proofs</h3>
                        <p class="mt-1 text-xs text-slate-500">Amounts update TDS live. Save draft to upload proofs.</p>
                        <div class="mt-3 space-y-3">
                            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__currentLoopData = $sections; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $code => $meta): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <?php
                                    $item = $itemMap->get($code);
                                    $value = old('amounts.'.$code, $item?->declared_amount ?? '');
                                ?>
                                <div class="rounded-lg border border-slate-200 p-3">
                                    <div class="grid gap-3 sm:grid-cols-[1fr_140px] sm:items-start">
                                        <div>
                                            <label class="block text-sm font-medium text-slate-800"><?php echo e($meta['name']); ?></label>
                                            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($meta['limit']): ?>
                                                <span class="text-xs text-slate-500">Max ₹<?php echo e(number_format($meta['limit'])); ?>/year</span>
                                            <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                                            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($meta['proof_required'] ?? true): ?>
                                                <span class="ml-1 text-xs text-amber-600">Proof required if amount &gt; 0</span>
                                            <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                                        </div>
                                        <input type="number" min="0" step="0.01" placeholder="0"
                                            x-model.number="amounts['<?php echo e($code); ?>']"
                                            @input="schedulePreview()"
                                            value="<?php echo e($value); ?>"
                                            <?php echo e(!$ui['can_edit'] ? 'readonly' : ''); ?>

                                            class="rounded-lg border border-slate-300 px-3 py-2 text-sm">
                                    </div>

                                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($item && (float) $item->declared_amount > 0): ?>
                                        <div class="mt-3 flex flex-wrap items-center gap-3 border-t border-slate-100 pt-3">
                                            <span class="inline-flex rounded-full px-2 py-0.5 text-xs font-medium capitalize <?php echo e($proofBadge[$item->proof_status] ?? 'bg-slate-100 text-slate-600'); ?>">
                                                Proof: <?php echo e($item->proof_status); ?>

                                            </span>
                                            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($item->proof_path): ?>
                                                <a href="<?php echo e(route('payroll.income-tax.proof.download', $item)); ?>" class="text-xs font-medium text-primary hover:underline">View file</a>
                                            <?php elseif($proofMandatory && ($meta['proof_required'] ?? true)): ?>
                                                <span class="text-xs font-medium text-amber-700">Proof missing</span>
                                            <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                                            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($ui['can_upload_proofs']): ?>
                                                <form action="<?php echo e(route('payroll.income-tax.proof.upload', $item)); ?>" method="post" enctype="multipart/form-data" class="inline-flex flex-wrap items-center gap-2">
                                                    <?php echo csrf_field(); ?>
                                                    <input type="file" name="proof" accept=".pdf,.jpg,.jpeg,.png" class="max-w-[180px] text-xs">
                                                    <button type="submit" class="rounded bg-slate-800 px-2 py-1 text-xs font-medium text-white hover:bg-slate-900">Upload</button>
                                                </form>
                                            <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                                        </div>
                                    <?php elseif($ui['can_edit']): ?>
                                        <p class="mt-2 text-xs text-slate-400">Save draft to enable proof upload.</p>
                                    <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                                </div>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                        </div>
                    </div>

                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($ui['can_save']): ?>
                        <div class="flex flex-wrap items-center gap-2 border-t border-slate-100 pt-4">
                            <button type="button" @click="saveDraft()" :disabled="saving"
                                class="rounded-lg bg-slate-800 px-4 py-2 text-sm font-medium text-white hover:bg-slate-900 disabled:opacity-50">
                                <span x-show="!saving">Save draft</span>
                                <span x-show="saving" x-cloak>Saving…</span>
                            </button>
                        </div>
                    <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>

                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($declaration && $ui['can_submit']): ?>
                        <div class="border-t border-slate-100 pt-4">
                            <button type="button" @click="submitDeclaration()" :disabled="saving"
                                class="rounded-lg bg-primary px-4 py-2 text-sm font-medium text-white hover:bg-primary/90 disabled:opacity-50">
                                Submit for HR verification
                            </button>
                            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($proofMandatory && $selectedRegime === 'old'): ?>
                                <p class="mt-2 text-xs text-slate-500">All declared sections with proof required must have documents uploaded.</p>
                            <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                        </div>
                    <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                </div>
             <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal53747ceb358d30c0105769f8471417f6)): ?>
<?php $attributes = $__attributesOriginal53747ceb358d30c0105769f8471417f6; ?>
<?php unset($__attributesOriginal53747ceb358d30c0105769f8471417f6); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal53747ceb358d30c0105769f8471417f6)): ?>
<?php $component = $__componentOriginal53747ceb358d30c0105769f8471417f6; ?>
<?php unset($__componentOriginal53747ceb358d30c0105769f8471417f6); ?>
<?php endif; ?>
        </div>

        <div>
            <?php if (isset($component)) { $__componentOriginal53747ceb358d30c0105769f8471417f6 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal53747ceb358d30c0105769f8471417f6 = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.card','data' => []] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('card'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes([]); ?>
                <h3 class="text-sm font-semibold text-slate-900">TDS estimate</h3>
                <p class="mt-1 text-xs text-slate-500">Live preview — final TDS after HR verification.</p>
                <dl class="mt-4 space-y-3 text-sm">
                    <div class="flex justify-between gap-2">
                        <dt class="text-slate-500">Annual gross</dt>
                        <dd class="font-medium text-slate-900" x-text="formatRupee(projection.gross_annual)"></dd>
                    </div>
                    <div class="flex justify-between gap-2">
                        <dt class="text-slate-500">Deductions</dt>
                        <dd class="font-medium text-slate-900" x-text="formatRupee(projection.deductions)"></dd>
                    </div>
                    <div class="flex justify-between gap-2">
                        <dt class="text-slate-500">Taxable income</dt>
                        <dd class="font-medium text-slate-900" x-text="formatRupee(projection.taxable_income)"></dd>
                    </div>
                    <div class="flex justify-between gap-2 border-t border-slate-100 pt-3">
                        <dt class="text-slate-500">Annual tax</dt>
                        <dd class="font-semibold text-slate-900" x-text="formatRupee(projection.annual_tax)"></dd>
                    </div>
                    <div class="flex justify-between gap-2">
                        <dt class="text-slate-500">Monthly TDS</dt>
                        <dd class="font-semibold text-primary" x-text="formatRupee(projection.monthly_tds)"></dd>
                    </div>
                </dl>
             <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal53747ceb358d30c0105769f8471417f6)): ?>
<?php $attributes = $__attributesOriginal53747ceb358d30c0105769f8471417f6; ?>
<?php unset($__attributesOriginal53747ceb358d30c0105769f8471417f6); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal53747ceb358d30c0105769f8471417f6)): ?>
<?php $component = $__componentOriginal53747ceb358d30c0105769f8471417f6; ?>
<?php unset($__componentOriginal53747ceb358d30c0105769f8471417f6); ?>
<?php endif; ?>
        </div>
    </div>
</div>

<script>
function incomeTaxForm(config) {
    const initialAmounts = {};
    <?php $__currentLoopData = $sections; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $code => $meta): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
        <?php $item = $itemMap->get($code); ?>
        initialAmounts[<?php echo \Illuminate\Support\Js::from($code)->toHtml() ?>] = <?php echo e((float) old('amounts.'.$code, $item?->declared_amount ?? 0)); ?>;
    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>

    return {
        financialYear: config.financialYear,
        regime: config.regime,
        canEdit: config.canEdit,
        previewUrl: config.previewUrl,
        saveUrl: config.saveUrl,
        submitUrl: config.submitUrl,
        csrf: config.csrf,
        amounts: initialAmounts,
        projection: config.projection,
        previewLoading: false,
        saving: false,
        flash: { message: '', ok: true },
        previewTimer: null,

        formatRupee(value) {
            return '₹' + Number(value || 0).toLocaleString('en-IN', { maximumFractionDigits: 0 });
        },

        schedulePreview() {
            if (!this.canEdit) return;
            clearTimeout(this.previewTimer);
            this.previewTimer = setTimeout(() => this.fetchPreview(), 400);
        },

        async fetchPreview() {
            this.previewLoading = true;
            try {
                const res = await fetch(this.previewUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json',
                        'X-CSRF-TOKEN': this.csrf,
                    },
                    body: JSON.stringify({
                        financial_year: this.financialYear,
                        regime: this.regime,
                        amounts: this.amounts,
                    }),
                });
                const data = await res.json();
                if (data.projection) {
                    this.projection = { ...this.projection, ...data.projection };
                }
            } catch (e) {
                console.error(e);
            } finally {
                this.previewLoading = false;
            }
        },

        async saveDraft() {
            this.saving = true;
            this.flash = { message: '', ok: true };
            try {
                const res = await fetch(this.saveUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json',
                        'X-CSRF-TOKEN': this.csrf,
                    },
                    body: JSON.stringify({
                        financial_year: this.financialYear,
                        regime: this.regime,
                        amounts: this.amounts,
                    }),
                });
                const data = await res.json();
                this.flash = { message: data.message, ok: data.success };
                if (data.projection) {
                    this.projection = { ...this.projection, ...data.projection };
                }
                if (data.success) {
                    setTimeout(() => window.location.reload(), 800);
                }
            } catch (e) {
                this.flash = { message: 'Save failed. Please try again.', ok: false };
            } finally {
                this.saving = false;
            }
        },

        async submitDeclaration() {
            if (!confirm('Submit declaration for HR verification?')) return;
            this.saving = true;
            this.flash = { message: '', ok: true };
            try {
                const res = await fetch(this.submitUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json',
                        'X-CSRF-TOKEN': this.csrf,
                    },
                    body: JSON.stringify({ financial_year: this.financialYear }),
                });
                const data = await res.json();
                this.flash = { message: data.message, ok: data.success };
                if (data.success) {
                    setTimeout(() => window.location.reload(), 800);
                }
            } catch (e) {
                this.flash = { message: 'Submit failed.', ok: false };
            } finally {
                this.saving = false;
            }
        },
    };
}
</script>
<?php /**PATH /var/www/html/kiyohr/v2_version/resources/views/payroll/tabs/my/income-tax.blade.php ENDPATH**/ ?>