@extends('layouts.app')

@section('page-title', 'Edit Service Sale')

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-md-8 offset-md-2">
            <div class="card">
                <div class="card-header">
                    <h4>Edit Service Sale</h4>
                </div>
                <div class="card-body">
                    <form action="{{ route('service-sales.update', $serviceSale->id) }}" method="POST">
                        @csrf
                        @method('PUT')

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="date" class="form-label">Date</label>
                                <input type="date" class="form-control" id="date" name="date" value="{{ old('date', $serviceSale->date) }}">
                            </div>
                            <div class="col-md-6">
                                <label for="customer_id" class="form-label">Customer *</label>
                                <select class="form-control" id="customer_id" name="customer_id" required>
                                    <option value="">Select Customer</option>
                                    @foreach($customers as $customer)
                                        <option value="{{ $customer->id }}" {{ old('customer_id', $serviceSale->customer_id) == $customer->id ? 'selected' : '' }}>
                                            {{ $customer->name }} - {{ $customer->company_name ?? 'N/A' }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="service_id" class="form-label">Service *</label>
                                <select class="form-control" id="service_id" name="service_id" required>
                                    <option value="">Select Service</option>
                                    @foreach($services as $service)
                                        <option value="{{ $service->id }}"
                                            data-price="{{ $service->price }}"
                                            data-cost="{{ $service->cost_price ?? 0 }}"
                                            {{ old('service_id', $serviceSale->service_id) == $service->id ? 'selected' : '' }}>
                                            {{ $service->name }} - {{ number_format($service->price, 2) }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label for="qty" class="form-label">Quantity</label>
                                <input type="number" class="form-control" id="qty" name="qty" value="{{ old('qty', $serviceSale->qty ?? 1) }}" min="1">
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="sales" class="form-label">Sale Price *</label>
                                <input type="number" step="0.01" class="form-control" id="sales" name="sales" value="{{ old('sales', $serviceSale->sales / ($serviceSale->qty ?? 1)) }}" required min="0">
                            </div>
                            <div class="col-md-6">
                                <label for="total_sales" class="form-label">Total Sales</label>
                                <input type="number" step="0.01" class="form-control" id="total_sales" name="total_sales" value="{{ old('total_sales', $serviceSale->sales) }}" readonly style="background-color: #e9ecef;">
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="particulars" class="form-label">Particulars</label>
                                <input type="text" class="form-control" id="particulars" name="particulars" value="{{ old('particulars', $serviceSale->particulars) }}">
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="payment" class="form-label">Payment</label>
                                <input type="number" step="0.01" class="form-control" id="payment" name="payment" value="{{ old('payment', $serviceSale->payment) }}" min="0">
                            </div>
                            <div class="col-md-6">
                                <label for="payment_method" class="form-label">Payment Method</label>
                                <select class="form-select" id="payment_method" name="payment_method">
                                    <option value="">Select Method</option>
                                    <option value="cash" {{ old('payment_method', $serviceSale->payment_method) == 'cash' ? 'selected' : '' }}>Cash</option>
                                    <option value="bank" {{ old('payment_method', $serviceSale->payment_method) == 'bank' ? 'selected' : '' }}>Bank</option>
                                    <option value="digital" {{ old('payment_method', $serviceSale->payment_method) == 'digital' ? 'selected' : '' }}>Digital</option>
                                </select>
                            </div>
                        </div>

                        <div class="mb-3" id="bank_account_field" style="display: none;">
                            <label for="bank_account_id" class="form-label">Bank Account</label>
                            <select class="form-select" id="bank_account_id" name="bank_account_id">
                                <option value="">Select Account</option>
                                @foreach($bankAccounts as $account)
                                    <option value="{{ $account->id }}" {{ old('bank_account_id', $serviceSale->bank_account_id) == $account->id ? 'selected' : '' }}>{{ $account->bank_name }} - {{ $account->account_name }}</option>
                                @endforeach
                            </select>
                        </div>

                        <div class="mb-3" id="digital_payment_field" style="display: none;">
                            <label for="digital_payment_id" class="form-label">Digital Payment</label>
                            <select class="form-select" id="digital_payment_id" name="digital_payment_id">
                                <option value="">Select Account</option>
                                @foreach($digitalPayments as $payment)
                                    <option value="{{ $payment->id }}" {{ old('digital_payment_id', $serviceSale->digital_payment_id) == $payment->id ? 'selected' : '' }}>{{ $payment->provider }} - {{ $payment->account_number }}</option>
                                @endforeach
                            </select>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="due" class="form-label">Due</label>
                                <input type="number" step="0.01" class="form-control" id="due" name="due" value="{{ old('due', $serviceSale->due) }}" readonly style="background-color: #e9ecef;">
                            </div>
                            <div class="col-md-6">
                                <label for="cogs" class="form-label">COGS</label>
                                <input type="number" step="0.01" class="form-control" id="cogs" name="cogs" value="{{ old('cogs', $serviceSale->cogs) }}">
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="gross_profit" class="form-label">Gross Profit</label>
                                <input type="number" step="0.01" class="form-control" id="gross_profit" name="gross_profit" value="{{ old('gross_profit', $serviceSale->gross_profit) }}" readonly style="background-color: #e9ecef;">
                            </div>
                            <div class="col-md-6">
                                <label for="percentage" class="form-label">Profit Margin (%)</label>
                                <input type="number" step="0.01" class="form-control" id="percentage" name="percentage" value="{{ old('percentage', $serviceSale->percentage) }}" readonly style="background-color: #e9ecef;">
                            </div>
                        </div>

                        <div class="d-flex justify-content-between">
                            <a href="{{ route('service-sales.index') }}" class="btn btn-secondary">Cancel</a>
                            <button type="submit" class="btn btn-primary">Update Sale</button>
                        </div>
                    </form>

                    <script>
                        document.addEventListener('DOMContentLoaded', function() {
                            const serviceSelect = document.getElementById('service_id');
                            const qtyInput = document.getElementById('qty');
                            const salesInput = document.getElementById('sales');
                            const totalSalesInput = document.getElementById('total_sales');
                            const paymentInput = document.getElementById('payment');
                            const dueInput = document.getElementById('due');
                            const cogsInput = document.getElementById('cogs');
                            const grossProfitInput = document.getElementById('gross_profit');
                            const percentageInput = document.getElementById('percentage');
                            const paymentMethodSelect = document.getElementById('payment_method');
                            const bankAccountField = document.getElementById('bank_account_field');
                            const digitalPaymentField = document.getElementById('digital_payment_field');

                            function getNumber(value) {
                                const num = parseFloat(value);
                                return isNaN(num) || num < 0 ? 0 : num;
                            }

                            function calculateTotal() {
                                const qty = getNumber(qtyInput.value);
                                const sales = getNumber(salesInput.value);
                                const total = qty * sales;
                                totalSalesInput.value = total.toFixed(2);
                                calculateDue();
                                calculateProfit();
                            }

                            function calculateDue() {
                                const totalSales = getNumber(totalSalesInput.value);
                                const payment = getNumber(paymentInput.value);
                                dueInput.value = Math.max(0, totalSales - payment).toFixed(2);
                            }

                            function calculateProfit() {
                                const totalSales = getNumber(totalSalesInput.value);
                                const cogs = getNumber(cogsInput.value);
                                const profit = totalSales - cogs;
                                grossProfitInput.value = profit.toFixed(2);

                                if (totalSales > 0) {
                                    percentageInput.value = ((profit / totalSales) * 100).toFixed(2);
                                } else {
                                    percentageInput.value = '0.00';
                                }
                            }

                            // Auto-fill when service is selected
                            serviceSelect?.addEventListener('change', function() {
                                const option = this.options[this.selectedIndex];
                                if (option && option.value) {
                                    salesInput.value = option.dataset.price || 0;
                                    cogsInput.value = option.dataset.cost || 0;
                                    calculateTotal();
                                }
                            });

                            // Calculate on input changes
                            qtyInput?.addEventListener('input', calculateTotal);
                            salesInput?.addEventListener('input', calculateTotal);
                            paymentInput?.addEventListener('input', calculateDue);
                            cogsInput?.addEventListener('input', calculateProfit);

                            // Toggle payment method fields
                            paymentMethodSelect?.addEventListener('change', function() {
                                const method = this.value;
                                if (bankAccountField) {
                                    bankAccountField.style.display = method === 'bank' ? 'block' : 'none';
                                }
                                if (digitalPaymentField) {
                                    digitalPaymentField.style.display = method === 'digital' ? 'block' : 'none';
                                }
                            });

                            // Initialize
                            togglePaymentFields();
                            function togglePaymentFields() {
                                const method = paymentMethodSelect.value;
                                if (bankAccountField) bankAccountField.style.display = method === 'bank' ? 'block' : 'none';
                                if (digitalPaymentField) digitalPaymentField.style.display = method === 'digital' ? 'block' : 'none';
                            }

                            // Initialize calculations
                            calculateTotal();
                        });
                    </script>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

