<?php $attributes ??= new \Illuminate\View\ComponentAttributeBag;

$__newAttributes = [];
$__propNames = \Illuminate\View\ComponentAttributeBag::extractPropNames(([
    'packages' => [],
    'items' => [],
    'initialMode' => 'custom',
    'selectedPackageIds' => [],
    'currency' => 'KES',
]));

foreach ($attributes->all() as $__key => $__value) {
    if (in_array($__key, $__propNames)) {
        $$__key = $$__key ?? $__value;
    } else {
        $__newAttributes[$__key] = $__value;
    }
}

$attributes = new \Illuminate\View\ComponentAttributeBag($__newAttributes);

unset($__propNames);
unset($__newAttributes);

foreach (array_filter(([
    'packages' => [],
    'items' => [],
    'initialMode' => 'custom',
    'selectedPackageIds' => [],
    'currency' => 'KES',
]), 'is_string', ARRAY_FILTER_USE_KEY) as $__key => $__value) {
    $$__key = $$__key ?? $__value;
}

$__defined_vars = get_defined_vars();

foreach ($attributes->all() as $__key => $__value) {
    if (array_key_exists($__key, $__defined_vars)) unset($$__key);
}

unset($__defined_vars, $__key, $__value); ?>

<?php
    $itemRows = old('items', $items ?: []);
    $mode = old('pricing_mode', $initialMode);
    $selectedIds = array_map('strval', old('package_ids', $selectedPackageIds));
    $chargeBasisOptions = collect(\App\Enums\ChargeBasis::cases())->mapWithKeys(fn ($c) => [$c->value => $c->label()]);
    $packageOptions = collect($packages)->map(fn ($p) => [
        'id' => (string) $p->id,
        'name' => $p->name,
        'code' => $p->code,
        'type' => $p->package_type?->value ?? 'global',
        'type_label' => $p->package_type?->label() ?? 'Global',
        'fixed_price' => (float) ($p->fixed_price ?? 0),
        'pricing_method' => $p->pricing_method?->value ?? 'calculated',
    ])->values();
?>

<div
    class="mb-4"
    x-data="documentPricingBuilder(<?php echo \Illuminate\Support\Js::from([
        'mode' => $mode === 'packages' ? 'packages' : 'custom',
        'selectedPackageIds' => $selectedIds,
        'rows' => $itemRows ?: [['description' => '', 'quantity' => 1, 'unit_price' => 0, 'charge_basis' => 'once_per_event', 'tax_rate' => 0, 'guest_count' => 1, 'billable_days' => 1, 'billable_hours' => 1, 'discount_amount' => 0]],
        'spaceLines' => [],
        'totals' => ['subtotal' => 0, 'tax' => 0, 'grand_total' => 0],
        'currency' => $currency,
        'loading' => false,
    ])->toHtml() ?>, <?php echo \Illuminate\Support\Js::from($packageOptions)->toHtml() ?>, <?php echo \Illuminate\Support\Js::from($chargeBasisOptions)->toHtml() ?>, <?php echo \Illuminate\Support\Js::from(route('pricing.preview'))->toHtml() ?>, <?php echo \Illuminate\Support\Js::from(route('pricing.package-lines'))->toHtml() ?>)"
    x-init="init()"
    @vem-dates-changed.window="onContextChange($event.detail)"
    @vem-spaces-changed.window="onSpacesChange($event.detail)"
>
    <input type="hidden" name="pricing_mode" :value="mode">

    <div class="mb-3">
        <div class="form-check form-check-inline">
            <input class="form-check-input" type="radio" id="pricing_mode_packages" value="packages" x-model="mode" @change="onModeChange()">
            <label class="form-check-label" for="pricing_mode_packages">Available packages</label>
        </div>
        <div class="form-check form-check-inline">
            <input class="form-check-input" type="radio" id="pricing_mode_custom" value="custom" x-model="mode" @change="onModeChange()">
            <label class="form-check-label" for="pricing_mode_custom">Custom package</label>
        </div>
        <div class="form-text">
            Choose <strong>Available packages</strong> to pick catalog packages (line items hidden), or <strong>Custom package</strong> to enter line items manually.
        </div>
    </div>

    <div x-show="mode === 'packages'" x-cloak class="mb-4">
        <label class="form-label">Select package(s)</label>
        <div class="border rounded p-3 bg-light" style="max-height: 280px; overflow:auto;">
            <template x-if="packages.length === 0">
                <p class="text-muted mb-0">No active packages found.</p>
            </template>
            <template x-for="pkg in packages" :key="pkg.id">
                <label class="d-flex align-items-start gap-2 mb-2">
                    <input type="checkbox" class="form-check-input mt-1" :value="pkg.id" x-model="selectedPackageIds" @change="loadPackages()">
                    <span>
                        <strong x-text="pkg.name"></strong>
                        <span class="text-muted" x-text="' (' + pkg.code + ')'"></span>
                        <span class="badge text-bg-secondary ms-1" x-text="pkg.type_label"></span>
                    </span>
                </label>
            </template>
        </div>
        <template x-for="id in selectedPackageIds" :key="'hid-' + id">
            <input type="hidden" name="package_ids[]" :value="id">
        </template>
    </div>

    <div x-show="mode === 'custom'" x-cloak>
        <h6 class="mb-3">Line Items</h6>
        <template x-for="(row, index) in rows" :key="index">
            <div class="border rounded p-3 mb-3 bg-light">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <strong x-text="'Line ' + (index + 1)"></strong>
                    <button type="button" class="btn btn-sm btn-outline-danger" @click="removeRow(index)" x-show="rows.length > 1">Remove</button>
                </div>
                <div class="row g-2">
                    <div class="col-md-6">
                        <label class="form-label required">Description</label>
                        <input type="text" class="form-control" :name="'items[' + index + '][description]'" x-model="row.description" @input="schedulePreview()" required maxlength="500">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Quantity</label>
                        <input type="number" step="0.01" class="form-control" :name="'items[' + index + '][quantity]'" x-model.number="row.quantity" @input="schedulePreview()" min="0">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Unit Price</label>
                        <input type="number" step="0.01" class="form-control" :name="'items[' + index + '][unit_price]'" x-model.number="row.unit_price" @input="schedulePreview()" min="0">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Tax %</label>
                        <input type="number" step="0.01" class="form-control" :name="'items[' + index + '][tax_rate]'" x-model.number="row.tax_rate" @input="schedulePreview()" min="0">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label required">Charge Basis</label>
                        <select class="form-select" :name="'items[' + index + '][charge_basis]'" x-model="row.charge_basis" @change="schedulePreview()" required>
                            <template x-for="[value, label] in Object.entries(chargeBasisOptions)" :key="value">
                                <option :value="value" x-text="label"></option>
                            </template>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Guests</label>
                        <input type="number" class="form-control" :name="'items[' + index + '][guest_count]'" x-model.number="row.guest_count" @input="schedulePreview()" min="0">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Days</label>
                        <input type="number" class="form-control" :name="'items[' + index + '][billable_days]'" x-model.number="row.billable_days" @input="schedulePreview()" min="1">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Hours</label>
                        <input type="number" step="0.01" class="form-control" :name="'items[' + index + '][billable_hours]'" x-model.number="row.billable_hours" @input="schedulePreview()" min="0">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Discount</label>
                        <input type="number" step="0.01" class="form-control" :name="'items[' + index + '][discount_amount]'" x-model.number="row.discount_amount" @input="schedulePreview()" min="0">
                    </div>
                </div>
            </div>
        </template>
        <button type="button" class="btn btn-outline-primary btn-sm" @click="addRow()">
            <i class="bi bi-plus-lg me-1"></i> Add Line Item
        </button>
    </div>

    
    <template x-if="mode === 'packages'">
        <div>
            <template x-for="(row, index) in rows" :key="'pkg-item-' + index">
                <div>
                    <input type="hidden" :name="'items[' + index + '][description]'" :value="row.description">
                    <input type="hidden" :name="'items[' + index + '][quantity]'" :value="row.quantity">
                    <input type="hidden" :name="'items[' + index + '][unit_price]'" :value="row.unit_price">
                    <input type="hidden" :name="'items[' + index + '][charge_basis]'" :value="row.charge_basis">
                    <input type="hidden" :name="'items[' + index + '][guest_count]'" :value="row.guest_count">
                    <input type="hidden" :name="'items[' + index + '][billable_days]'" :value="row.billable_days">
                    <input type="hidden" :name="'items[' + index + '][billable_hours]'" :value="row.billable_hours">
                    <input type="hidden" :name="'items[' + index + '][discount_amount]'" :value="row.discount_amount || 0">
                    <input type="hidden" :name="'items[' + index + '][tax_rate]'" :value="row.tax_rate || 0">
                    <input type="hidden" :name="'items[' + index + '][product_id]'" :value="row.product_id || ''">
                    <input type="hidden" :name="'items[' + index + '][package_id]'" :value="row.package_id || ''">
                </div>
            </template>
        </div>
    </template>

    <div class="card mt-4 border-0 bg-body-tertiary">
        <div class="card-body">
            <div class="d-flex justify-content-between align-items-center mb-2">
                <h6 class="mb-0">Price Total</h6>
                <span class="small text-muted" x-show="loading">Calculating…</span>
            </div>
            <div class="row g-2">
                <div class="col-md-3" x-show="spaceLines.length" x-cloak>
                    <span class="text-muted">Spaces</span>
                    <div class="fw-semibold" x-text="formatMoney(spacesSubtotal())"></div>
                </div>
                <div class="col-md-3" x-show="rows.length" x-cloak>
                    <span class="text-muted">Additional Charges</span>
                    <div class="fw-semibold" x-text="formatMoney(chargesSubtotal())"></div>
                </div>
                <div class="col-md-3"><span class="text-muted">Subtotal</span><div class="fw-semibold" x-text="formatMoney(totals.subtotal)"></div></div>
                <div class="col-md-3"><span class="text-muted">Tax</span><div class="fw-semibold" x-text="formatMoney(totals.tax)"></div></div>
                <div class="col-md-3"><span class="text-muted">Grand Total</span><div class="fs-5 fw-bold text-primary" x-text="formatMoney(totals.grand_total)"></div></div>
            </div>
        </div>
    </div>
</div>

<?php if (! $__env->hasRenderedOnce('3b8dfb23-7b3f-43f6-8e0c-60837e04c34c')): $__env->markAsRenderedOnce('3b8dfb23-7b3f-43f6-8e0c-60837e04c34c'); ?>
<?php $__env->startPush('scripts'); ?>
<script>
function documentPricingBuilder(state, packages, chargeBasisOptions, previewUrl, packageLinesUrl) {
    return {
        ...state,
        packages,
        chargeBasisOptions,
        previewUrl,
        packageLinesUrl,
        previewTimer: null,
        _lineTotals: [],
        csrf() {
            return document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';
        },
        init() {
            this.schedulePreview();
            if (this.mode === 'packages' && this.selectedPackageIds.length) {
                this.loadPackages();
            }
        },
        onModeChange() {
            if (this.mode === 'packages') {
                this.loadPackages();
            } else if (!this.rows.length) {
                this.addRow();
            }
            this.schedulePreview();
        },
        onContextChange(detail) {
            // Recalculate package lines when guest count / dates change
            if (this.mode === 'packages') {
                this.loadPackages();
            } else {
                this.schedulePreview();
            }
        },
        onSpacesChange(detail) {
            this.spaceLines = detail?.lines || [];
            this.schedulePreview();
        },
        addRow() {
            this.rows.push({
                description: '', quantity: 1, unit_price: 0, charge_basis: 'once_per_event',
                tax_rate: 0, guest_count: this.guestCount(), billable_days: this.billableDays(),
                billable_hours: 1, discount_amount: 0
            });
            this.schedulePreview();
        },
        removeRow(index) {
            this.rows.splice(index, 1);
            this.schedulePreview();
        },
        guestCount() {
            var el = document.querySelector('[name="guest_count"]');
            return Math.max(1, parseInt(el?.value || '1', 10) || 1);
        },
        billableDays() {
            var start = document.querySelector('[name="event_start"]')?.value;
            var end = document.querySelector('[name="event_end"]')?.value;
            if (!start || !end) return 1;
            var s = new Date(start);
            var e = new Date(end);
            if (isNaN(s) || isNaN(e) || e < s) return 1;
            var days = Math.floor((Date.UTC(e.getFullYear(), e.getMonth(), e.getDate()) - Date.UTC(s.getFullYear(), s.getMonth(), s.getDate())) / 86400000) + 1;
            return Math.max(1, days);
        },
        billableHours() {
            var start = document.querySelector('[name="event_start"]')?.value;
            var end = document.querySelector('[name="event_end"]')?.value;
            if (!start || !end) return 1;
            var s = new Date(start);
            var e = new Date(end);
            if (isNaN(s) || isNaN(e) || e <= s) return 1;
            return Math.max(1, Math.round(((e - s) / 3600000) * 100) / 100);
        },
        loadPackages() {
            var self = this;
            if (!this.selectedPackageIds.length) {
                this.rows = [];
                this.schedulePreview();
                return;
            }
            this.loading = true;
            fetch(this.packageLinesUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': this.csrf(),
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: JSON.stringify({
                    package_ids: this.selectedPackageIds.map(Number),
                    guest_count: this.guestCount(),
                    billable_days: this.billableDays(),
                    billable_hours: this.billableHours()
                })
            })
                .then(function (r) { return r.json(); })
                .then(function (data) {
                    self.rows = (data.lines || []).map(function (line) {
                        return {
                            description: line.description || '',
                            quantity: line.quantity ?? 1,
                            unit_price: line.unit_price ?? 0,
                            charge_basis: line.charge_basis || 'once_per_event',
                            guest_count: line.guest_count ?? self.guestCount(),
                            billable_days: line.billable_days ?? self.billableDays(),
                            billable_hours: line.billable_hours ?? self.billableHours(),
                            discount_amount: line.discount_amount ?? 0,
                            tax_rate: line.tax_rate ?? 0,
                            product_id: line.product_id || '',
                            package_id: line.package_id || '',
                            fixed_amount: line.fixed_amount ?? line.unit_price ?? 0
                        };
                    });
                    self.schedulePreview();
                })
                .finally(function () { self.loading = false; });
        },
        schedulePreview() {
            var self = this;
            clearTimeout(this.previewTimer);
            this.previewTimer = setTimeout(function () { self.runPreview(); }, 250);
        },
        runPreview() {
            var self = this;
            this.loading = true;
            var lines = (this.spaceLines || []).concat(this.rows || []);
            fetch(this.previewUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': this.csrf(),
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: JSON.stringify({ items: lines })
            })
                .then(function (r) { return r.json(); })
                .then(function (data) {
                    self.totals = data.document_totals || self.totals;
                    self._lineTotals = data.line_totals || [];
                })
                .finally(function () { self.loading = false; });
        },
        spacesSubtotal() {
            var spaceCount = (this.spaceLines || []).length;
            if (!spaceCount || !this._lineTotals || this._lineTotals.length < spaceCount) return 0;
            return this._lineTotals.slice(0, spaceCount).reduce(function (sum, line) {
                return sum + Number(line.base || 0);
            }, 0);
        },
        chargesSubtotal() {
            var spaceCount = (this.spaceLines || []).length;
            if (!this._lineTotals || this._lineTotals.length <= spaceCount) return 0;
            return this._lineTotals.slice(spaceCount).reduce(function (sum, line) {
                return sum + Number(line.base || 0);
            }, 0);
        },
        formatMoney(value) {
            var n = Number(value || 0);
            return this.currency + ' ' + n.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        }
    };
}
</script>
<?php $__env->stopPush(); ?>
<?php endif; ?>
<?php /**PATH C:\xampp\htdocs\hotelplus\consol\resources\views/components/document-pricing-builder.blade.php ENDPATH**/ ?>