@extends('layouts.app')
@section('title','Easy Fuel Sale')
@section('page_title','تیل خرڅول - ډېر ساده POS')

@section('content')
<form method="POST" action="{{ route('fuel-sales.store') }}" id="posForm">
@csrf
<input type="hidden" name="fuel_type_id" id="fuel_type_id">
<input type="hidden" name="shift_id" value="{{ $activeShift?->id }}">
<input type="hidden" name="exchange_rate" value="1">

<div class="row g-3">
    <div class="col-xl-8">
        <div class="top-card mb-3">
            <h5 class="fw-bold mb-1"><i class="fa-solid fa-hand-pointer text-success"></i> ۱) تیل انتخاب کړئ</h5>
            <p class="mini-help mb-3">قیمت له مخکې په تنظیماتو کې تعریف دی؛ دلته قیمت مه لیکئ.</p>
            <div class="row g-3">
                @foreach($fuelTypes as $fuel)
                <div class="col-md-4">
                    <button type="button" class="fuel-choice" id="fuelBtn{{ $fuel->id }}" onclick="selectFuel({{ $fuel->id }}, {{ (float)$fuel->sale_price }}, '{{ $fuel->unit }}')">
                        <i class="fa-solid fa-gas-pump"></i>
                        <div class="name mt-2">{{ $fuel->name_ps ?: $fuel->name_en }}</div>
                        <div class="rate">{{ number_format($fuel->sale_price,2) }} / {{ $fuel->unit }}</div>
                    </button>
                </div>
                @endforeach
            </div>
        </div>

        <div class="top-card">
            <h5 class="fw-bold mb-3"><i class="fa-solid fa-pen-to-square text-success"></i> ۲) لږ معلومات ولیکئ</h5>
            <div class="row g-3">
                <div class="col-md-4">
                    <label class="easy-label required">تاریخ</label>
                    <input type="date" name="sale_date" value="{{ date('Y-m-d') }}" class="form-control form-control-lg" required>
                </div>
                <div class="col-md-4">
                    <label class="easy-label required">ټانک</label>
                    <select name="tank_id" id="tank_id" class="form-select form-select-lg" required>
                        <option value="">لومړی تیل انتخاب کړئ</option>
                        @foreach($tanks as $tank)
                            <option value="{{ $tank->id }}" data-fuel="{{ $tank->fuel_type_id }}" data-stock="{{ $tank->current_qty }}" hidden>
                                {{ $tank->name }} | ذخیره: {{ number_format($tank->current_qty,2) }}
                            </option>
                        @endforeach
                    </select>
                    <small class="mini-help" id="stockHint">د Fuel له انتخاب وروسته اړوند ټانک ښکاري.</small>
                </div>
                <div class="col-md-4">
                    <label class="easy-label required">کرنسي</label>
                    <select name="currency_id" class="form-select form-select-lg" required>
                        @foreach($currencies as $currency)<option value="{{ $currency->id }}">{{ $currency->code }}</option>@endforeach
                    </select>
                </div>

                <div class="col-md-6">
                    <label class="easy-label">Meter Start / د مېټر شروع</label>
                    <input type="number" step="0.001" name="meter_start" id="meter_start" class="form-control form-control-lg" placeholder="مثال: 12000" oninput="calculateQty()">
                </div>
                <div class="col-md-6">
                    <label class="easy-label">Meter End / د مېټر ختم</label>
                    <input type="number" step="0.001" name="meter_end" id="meter_end" class="form-control form-control-lg" placeholder="مثال: 12150" oninput="calculateQty()">
                </div>
                <div class="col-md-6">
                    <label class="easy-label required">اندازه / Quantity</label>
                    <input type="number" step="0.001" name="quantity" id="quantity" class="form-control form-control-lg" required placeholder="Liter / KG" oninput="calculateTotal()">
                    <small class="mini-help">که مېټر نه کاروئ، مستقیم اندازه ولیکئ.</small>
                </div>
                <div class="col-md-6">
                    <label class="easy-label">تعریف شوی قیمت</label>
                    <div class="form-control form-control-lg bg-light fw-bold" id="priceText">Fuel انتخاب کړئ</div>
                </div>

                <div class="col-md-6">
                    <label class="easy-label required">مشتری</label>
                    <select name="customer_type" id="customer_type" class="form-select form-select-lg" onchange="toggleCustomer()">
                        <option value="walk_in">عام مشتری / Walk-in</option>
                        <option value="account">حسابي مشتری</option>
                    </select>
                </div>
                <div class="col-md-6 d-none" id="customer_box">
                    <label class="easy-label">حسابي مشتری انتخاب</label>
                    <select name="customer_id" class="form-select form-select-lg">
                        <option value="">مشتری انتخاب کړئ</option>
                        @foreach($customers as $customer)<option value="{{ $customer->id }}">{{ $customer->name }}</option>@endforeach
                    </select>
                </div>

                <div class="col-md-6">
                    <label class="easy-label required">اخیستل شوې پیسې</label>
                    <input type="number" step="0.01" name="paid_amount" id="paid_amount" value="0" class="form-control form-control-lg" required oninput="calculateDue()">
                </div>
                <div class="col-md-6">
                    <label class="easy-label required">د پیسو ډول</label>
                    <select name="payment_type" class="form-select form-select-lg">
                        <option value="cash">نقد / Cash</option>
                        <option value="credit">پور / Credit</option>
                        <option value="bank">Bank</option>
                        <option value="mixed">Mixed</option>
                    </select>
                </div>
                <div class="col-12">
                    <label class="easy-label">یادښت</label>
                    <input name="notes" class="form-control form-control-lg" placeholder="اختیاري یادښت">
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-4">
        <div class="top-card sticky-top" style="top:18px">
            <h5 class="fw-bold"><i class="fa-solid fa-receipt text-success"></i> بل / حساب</h5>
            <div class="summary-box mt-3">
                <div class="d-flex justify-content-between"><span>قیمت</span><strong id="rate_text">0.00</strong></div>
                <div class="d-flex justify-content-between"><span>اندازه</span><strong id="qty_text">0</strong></div>
                <hr>
                <div class="d-flex justify-content-between fs-4"><span>ټول مبلغ</span><strong id="total_text">0.00</strong></div>
                <div class="d-flex justify-content-between text-danger"><span>باقي</span><strong id="due_text">0.00</strong></div>
            </div>
            <button class="btn btn-success btn-lg w-100 mt-3" onclick="return validatePOS()"><i class="fa-solid fa-print"></i> Save & Print</button>
            <a class="btn btn-light btn-lg w-100 mt-2" href="{{ route('dashboard') }}"><i class="fa-solid fa-house"></i> کور پاڼه</a>
            <div class="alert alert-info mt-3 mb-0">خرڅلاو Save شي، ذخیره اتومات کمیږي.</div>
        </div>
    </div>
</div>
</form>
@endsection

@push('js')
<script>
let selectedRate = 0;
let selectedUnit = '';
function selectFuel(id, price, unit){
    selectedRate = parseFloat(price) || 0;
    selectedUnit = unit || '';
    document.getElementById('fuel_type_id').value = id;
    document.getElementById('priceText').innerText = selectedRate.toFixed(2) + ' / ' + selectedUnit;
    document.querySelectorAll('.fuel-choice').forEach(b => b.classList.remove('selected'));
    document.getElementById('fuelBtn'+id).classList.add('selected');

    const tank = document.getElementById('tank_id');
    let first = '';
    [...tank.options].forEach(opt => {
        if(!opt.value){ opt.hidden = false; return; }
        const ok = opt.dataset.fuel == id;
        opt.hidden = !ok;
        if(ok && !first) first = opt.value;
    });
    tank.value = first;
    updateStockHint();
    calculateTotal();
}
function updateStockHint(){
    const opt = document.getElementById('tank_id').selectedOptions[0];
    document.getElementById('stockHint').innerText = opt && opt.value ? 'موجوده ذخیره: ' + parseFloat(opt.dataset.stock || 0).toFixed(2) : 'د Fuel له انتخاب وروسته ټانک ښکاري.';
}
document.getElementById('tank_id').addEventListener('change', updateStockHint);
function toggleCustomer(){
    document.getElementById('customer_box').classList.toggle('d-none', document.getElementById('customer_type').value !== 'account');
}
function calculateQty(){
    const start = parseFloat(document.getElementById('meter_start').value) || 0;
    const end = parseFloat(document.getElementById('meter_end').value) || 0;
    if(end >= start && start > 0){ document.getElementById('quantity').value = (end - start).toFixed(3); }
    calculateTotal();
}
function calculateTotal(){
    const q = parseFloat(document.getElementById('quantity').value) || 0;
    const total = q * selectedRate;
    document.getElementById('rate_text').innerText = selectedRate.toFixed(2);
    document.getElementById('qty_text').innerText = q.toFixed(3);
    document.getElementById('total_text').innerText = total.toFixed(2);
    calculateDue();
}
function calculateDue(){
    const total = parseFloat(document.getElementById('total_text').innerText) || 0;
    const paid = parseFloat(document.getElementById('paid_amount').value) || 0;
    document.getElementById('due_text').innerText = Math.max(total - paid, 0).toFixed(2);
}
function validatePOS(){
    if(!document.getElementById('fuel_type_id').value){ alert('لومړی تیل انتخاب کړئ.'); return false; }
    if(!document.getElementById('tank_id').value){ alert('ټانک انتخاب کړئ.'); return false; }
    if((parseFloat(document.getElementById('quantity').value)||0) <= 0){ alert('اندازه ولیکئ.'); return false; }
    return true;
}
</script>
@endpush
