@extends('layouts.app')
@section('title', __('nav.new_sale'))
@section('body_class', 'pos-page')
@section('content')
<div class="d-flex justify-content-between align-items-center mb-3">
    <h1 class="h4 mb-0">{{ __('nav.new_sale') }}</h1>
</div>

<form method="post" action="{{ route('sales.store') }}" id="posForm" class="pos-shell">
@csrf
<input type="hidden" name="customer_id" id="customer_id" value="{{ old('customer_id') }}">
<input type="hidden" name="line_id" id="line_id" value="{{ old('line_id') }}">
<input type="hidden" name="plan_id" id="plan_id_input" value="{{ old('plan_id') }}">
<input type="hidden" name="sale_date" value="{{ now()->toDateString() }}">
<input type="hidden" name="activation_date" value="{{ now()->toDateString() }}">
<input type="hidden" name="override_price" id="override_price" value="0">

<div class="row g-3">
    <div class="col-lg-7">
        <div class="card card-body mb-3">
            <label class="form-label fw-semibold mb-1">{{ __('messages.customer') }}</label>
            <div class="search-wrap">
                <input class="form-control" id="customerSearch" autocomplete="off" placeholder="{{ __('messages.search_customer') }}">
                <div class="pos-results d-none" id="customerResults"></div>
            </div>
            <div id="selectedCustomer" class="mt-2 small text-muted">{{ __('messages.choose_customer') }}</div>
            <button class="btn btn-link btn-sm px-0" type="button" data-bs-toggle="collapse" data-bs-target="#newCustomerBox">{{ __('messages.new_customer') }}</button>
            <div class="collapse" id="newCustomerBox">
                <div class="row g-2">
                    <div class="col-md-6"><input class="form-control" name="new_customer[name]" id="new_customer_name" placeholder="{{ __('messages.name') }}"></div>
                    <div class="col-md-6"><input class="form-control" name="new_customer[phone]" placeholder="{{ __('messages.phone') }}"></div>
                    <input type="hidden" name="new_customer[customer_type]" value="individual">
                </div>
            </div>
        </div>

        <div class="card card-body mb-3">
            <label class="form-label fw-semibold mb-2">{{ __('messages.company') }}</label>
            <div class="company-chips" id="companyChips">
                @forelse($companies as $company)
                    <button type="button" class="company-chip" data-id="{{ $company->id }}" data-name="{{ $company->name }}">
                        {{ $company->name }}
                        <span class="count">{{ $company->available_lines_count }}</span>
                    </button>
                @empty
                    <div class="text-muted">{{ __('messages.no_results') }}</div>
                @endforelse
            </div>
        </div>

        <div class="card card-body mb-3" id="linesBox">
            <div class="d-flex justify-content-between align-items-center mb-2">
                <label class="form-label fw-semibold mb-0">{{ __('messages.available_products') }}</label>
                <input class="form-control form-control-sm" id="lineFilter" style="max-width:180px" placeholder="{{ __('messages.filter') }}">
            </div>
            <div class="product-grid" id="lineGrid">
                <div class="text-muted small">{{ __('messages.choose_company_first') }}</div>
            </div>
        </div>

        <div class="card card-body" id="plansBox">
            <label class="form-label fw-semibold mb-2">{{ __('messages.monthly_plan') }}</label>
            <div class="product-grid" id="planGrid">
                <div class="text-muted small">{{ __('messages.choose_company_first') }}</div>
            </div>
        </div>
    </div>

    <div class="col-lg-5">
        <div class="card pos-checkout">
            <div class="card-body">
                <div class="small text-muted">{{ __('messages.selected_line') }}</div>
                <div class="fw-bold mb-2" id="selectedLineLabel">—</div>
                <div class="d-flex justify-content-between mb-2"><span>{{ __('messages.line_price') }}</span><strong id="linePriceLabel">{{ money(0) }}</strong></div>
                <input type="hidden" name="line_price" id="line_price" value="0">
                <div class="small text-muted">{{ __('messages.plan') }}</div>
                <div class="fw-bold mb-1" id="selectedPlanLabel">{{ __('messages.no_plan') }}</div>
                <div class="small text-muted mb-3">{{ __('messages.plan_billed_monthly') }} — <strong id="planPriceLabel">{{ money(0) }}</strong></div>
                <input type="hidden" name="plan_price" id="plan_price" value="0">
                <div class="mb-2">
                    <label class="form-label mb-1">{{ __('messages.discount') }}</label>
                    <input class="form-control form-control-sm" name="discount" id="discount" value="0" min="0" step="0.01">
                </div>
                @if($canOverridePrice)
                    <div class="form-check mb-2">
                        <input class="form-check-input" type="checkbox" id="overrideToggle">
                        <label class="form-check-label" for="overrideToggle">{{ __('messages.override_price') }}</label>
                    </div>
                    <div id="overrideBox" class="d-none mb-2">
                        <div class="row g-2">
                            <div class="col-6"><input class="form-control form-control-sm" id="override_line_price" placeholder="{{ __('messages.line_price') }}"></div>
                            <div class="col-12"><input class="form-control form-control-sm" name="override_reason" placeholder="{{ __('messages.override_reason') }}"></div>
                        </div>
                    </div>
                @endif
                <hr>
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <span class="fw-semibold">{{ __('messages.total') }}</span>
                    <div class="pos-total" id="totalLabel">{{ money(0) }}</div>
                </div>
                <div class="mb-2">
                    <label class="form-label mb-1">{{ __('messages.payment_method') }}</label>
                    <select class="form-select" name="payment_method">
                        @foreach(['cash','visa','bank','wallet','other'] as $m)
                            <option value="{{ $m }}">{{ __('status.method_'.$m) }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="row g-2 mb-2">
                    <div class="col-6">
                        <label class="form-label mb-1">{{ __('messages.paid') }}</label>
                        <input class="form-control" name="paid" id="paid" value="0" min="0" step="0.01">
                    </div>
                    <div class="col-6">
                        <label class="form-label mb-1">{{ __('messages.remaining') }}</label>
                        <input class="form-control" id="remaining" value="0" readonly>
                    </div>
                </div>
                <button class="btn btn-success w-100 btn-lg" id="completeSale">{{ __('messages.complete_sale') }}</button>
            </div>
        </div>
    </div>
</div>
</form>
@endsection
@section('scripts')
<script>
const lookupCustomers = @json(route('sales.lookup.customers'));
const lookupLines = @json(route('sales.lookup.lines'));
const lookupPlans = @json(route('sales.lookup.plans'));
const canOverride = @json($canOverridePrice);
const currency = @json(setting('currency', 'EGP'));
const noPlan = @json(__('messages.no_plan'));
const money = (n) => Number(n || 0).toFixed(2) + ' ' + currency;
const qs = (id) => document.getElementById(id);
function debounce(fn, ms) { let t; return (...a) => { clearTimeout(t); t = setTimeout(() => fn(...a), ms); }; }

let catalogLine = 0, catalogPlan = 0, companyId = null, allLines = [], selectedPlanName = noPlan;

function renderResults(box, rows, html) {
    if (!rows.length) { box.classList.add('d-none'); box.innerHTML = ''; return; }
    box.innerHTML = rows.map(html).join('');
    box.classList.remove('d-none');
}

qs('customerSearch').addEventListener('input', debounce(async (e) => {
    const q = e.target.value.trim();
    if (q.length < 1) { qs('customerResults').classList.add('d-none'); return; }
    const rows = await (await fetch(lookupCustomers + '?q=' + encodeURIComponent(q))).json();
    renderResults(qs('customerResults'), rows, (c) => `<button type="button" data-id="${c.id}">${c.name} — ${c.phone}</button>`);
    [...qs('customerResults').querySelectorAll('button')].forEach(btn => btn.addEventListener('click', () => {
        const c = rows.find(r => String(r.id) === btn.dataset.id);
        qs('customer_id').value = c.id;
        qs('selectedCustomer').textContent = c.name + ' — ' + c.phone;
        qs('customerSearch').value = c.name;
        qs('customerResults').classList.add('d-none');
        qs('new_customer_name').value = '';
    }));
}, 220));

document.querySelectorAll('#companyChips .company-chip').forEach(btn => {
    btn.addEventListener('click', () => selectCompany(btn));
});

async function selectCompany(btn) {
    document.querySelectorAll('#companyChips .company-chip').forEach(el => el.classList.remove('active'));
    btn.classList.add('active');
    companyId = btn.dataset.id;
    qs('line_id').value = '';
    qs('plan_id_input').value = '';
    qs('selectedLineLabel').textContent = '—';
    catalogLine = 0;
    catalogPlan = 0;
    selectedPlanName = noPlan;
    qs('selectedPlanLabel').textContent = noPlan;
    qs('lineGrid').innerHTML = '';
    qs('planGrid').innerHTML = '';
    const [lines, plans] = await Promise.all([
        fetch(lookupLines + '?telecom_company_id=' + companyId).then(r => r.json()),
        fetch(lookupPlans + '?telecom_company_id=' + companyId).then(r => r.json()),
    ]);
    allLines = lines;
    renderLines(allLines);
    renderPlans(plans);
    recalc();
}

function renderLines(lines) {
    if (!lines.length) {
        qs('lineGrid').innerHTML = `<div class="text-muted small">{{ __('messages.no_results') }}</div>`;
        return;
    }
    qs('lineGrid').innerHTML = lines.map(l => `
        <button type="button" class="product-card ${qs('line_id').value == l.id ? 'active' : ''}" data-id="${l.id}">
            <div class="fw-bold">${l.phone_number}</div>
            <div class="small text-muted">${l.sim_type_label}</div>
            <div class="price mt-1">${money(l.sale_price)}</div>
        </button>
    `).join('');
    [...qs('lineGrid').querySelectorAll('.product-card')].forEach(card => {
        card.addEventListener('click', () => {
            const line = allLines.find(l => String(l.id) === card.dataset.id);
            qs('line_id').value = line.id;
            qs('selectedLineLabel').textContent = line.phone_number;
            catalogLine = Number(line.sale_price || 0);
            renderLines(filterLines());
            recalc();
        });
    });
}

function renderPlans(plans) {
    const items = [{ id: '', name: noPlan, price: '0.00' }, ...plans];
    qs('planGrid').innerHTML = items.map(p => `
        <button type="button" class="product-card ${String(qs('plan_id_input').value) === String(p.id) ? 'active' : ''}" data-id="${p.id}" data-price="${p.price}" data-name="${p.name}">
            <div class="fw-bold">${p.name}</div>
            <div class="price mt-1">${p.id ? money(p.price) + ' / {{ __("messages.month") }}' : '—'}</div>
        </button>
    `).join('');
    [...qs('planGrid').querySelectorAll('.product-card')].forEach(card => {
        card.addEventListener('click', () => {
            qs('plan_id_input').value = card.dataset.id;
            catalogPlan = Number(card.dataset.price || 0);
            selectedPlanName = card.dataset.name;
            qs('selectedPlanLabel').textContent = selectedPlanName;
            renderPlans(plans);
            recalc();
        });
    });
}

function filterLines() {
    const q = qs('lineFilter').value.trim();
    return q ? allLines.filter(l => l.phone_number.includes(q)) : allLines;
}
qs('lineFilter').addEventListener('input', () => renderLines(filterLines()));

qs('discount').addEventListener('input', recalc);
qs('paid').addEventListener('input', recalc);
if (canOverride) {
    qs('overrideToggle').addEventListener('change', function () {
        qs('overrideBox').classList.toggle('d-none', !this.checked);
        qs('override_price').value = this.checked ? '1' : '0';
        if (this.checked) {
            qs('override_line_price').value = catalogLine;
        }
        recalc();
    });
    qs('override_line_price').addEventListener('input', recalc);
}

function usedPrices() {
    const overrideOn = canOverride && qs('overrideToggle')?.checked;
    return {
        line: overrideOn ? Number(qs('override_line_price').value || 0) : catalogLine,
        plan: 0,
        monthly: catalogPlan,
    };
}

function recalc() {
    const { line, monthly } = usedPrices();
    const discount = Number(qs('discount').value || 0);
    const total = Math.max(line - discount, 0);
    qs('line_price').value = line.toFixed(2);
    qs('plan_price').value = '0.00';
    qs('linePriceLabel').textContent = money(line);
    qs('planPriceLabel').textContent = money(monthly);
    qs('totalLabel').textContent = money(total);
    if (document.activeElement !== qs('paid') || qs('paid').value === '' || Number(qs('paid').value) === 0) {
        qs('paid').value = total.toFixed(2);
    }
    qs('remaining').value = Math.max(total - Number(qs('paid').value || 0), 0).toFixed(2);
}

qs('new_customer_name').addEventListener('input', function () {
    if (this.value.trim()) {
        qs('customer_id').value = '';
        qs('selectedCustomer').textContent = this.value;
    }
});

qs('posForm').addEventListener('submit', (e) => {
    if (!qs('line_id').value) {
        e.preventDefault();
        alert(@json(__('messages.choose_line')));
        return;
    }
    if (!qs('customer_id').value && !qs('new_customer_name').value) {
        e.preventDefault();
        alert(@json(__('messages.choose_customer')));
    }
});
</script>
@endsection
