@extends('layouts.app')

@section('page-title', 'Add Sales Dashboard Record')

@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>Add New Sales Dashboard Record</h4>
                </div>
                <div class="card-body">
                    <form action="{{ route('sales-dashboard.store') }}" method="POST">
                        @csrf

                        <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') }}">
                            </div>
                            <div class="col-md-6">
                                <label for="invoice" class="form-label">Invoice</label>
                                <input type="text" class="form-control" id="invoice" name="invoice" value="{{ old('invoice') }}">
                            </div>
                        </div>

                        <div class="row mb-3">
                            <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') == $customer->id ? 'selected' : '' }}>
                                            {{ $customer->name }} - {{ $customer->company_name ?? 'N/A' }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label for="quotation_id" class="form-label">Quotation</label>
                                <select class="form-control" id="quotation_id" name="quotation_id">
                                    <option value="">Select Quotation</option>
                                    @foreach($quotations as $quotation)
                                        <option value="{{ $quotation->id }}" {{ old('quotation_id') == $quotation->id ? 'selected' : '' }}>
                                            {{ $quotation->quotation_number }} - {{ $quotation->company_name ?? 'N/A' }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="product" class="form-label">Product</label>
                                <select class="form-control" id="product" name="product">
                                    <option value="">Select Product</option>
                                    @foreach($products as $product)
                                        <option value="{{ $product->name }}" {{ old('product') == $product->name ? 'selected' : '' }}>{{ $product->name }}</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') }}" min="0">
                            </div>

                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="sales" class="form-label">Sale per product</label>
                                <input type="number" step="0.01" class="form-control" id="sales" name="sales" value="{{ old('sales') }}" 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') }}" 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') }}">
                            </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') }}" min="0">
                            </div>
                            <div class="col-md-6">
                                <label for="payment_method" class="form-label">Cash Received By</label>
                                <select class="form-select" id="payment_method" name="payment_method">
                                    <option value="">Select Method</option>
                                    <option value="cash" {{ old('payment_method') == 'cash' ? 'selected' : '' }}>Cash</option>
                                    <option value="bank" {{ old('payment_method') == 'bank' ? 'selected' : '' }}>Bank</option>
                                    <option value="digital" {{ old('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') == $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') == $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') }}" 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') }}" min="0">
                            </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" 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" readonly style="background-color: #e9ecef;">
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="segment" class="form-label">Segment</label>
                                <select class="form-select" id="segment" name="segment">
                                    <option value="">Select Segment</option>
                                    @foreach($segments as $segment)
                                        <option value="{{ $segment->name }}" {{ old('segment') == $segment->name ? 'selected' : '' }}>{{ $segment->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                           <!-- <div class="col-md-6">
                                <label for="amount" class="form-label">KPI Target Amount</label>
                                <input type="number" step="0.01" class="form-control" id="amount" name="amount" value="{{ old('amount') }}" placeholder="Enter target amount for KPI calculation" min="0">
                            </div>-->
                        </div>

                        <!--<div class="row mb-3">
                            <div class="col-md-6">
                                <label for="kpi" class="form-label">KPI Target (Reference)</label>
                                <input type="number" step="0.01" class="form-control" id="kpi" name="kpi" readonly style="background-color: #e9ecef;" placeholder="Auto-filled from Target Amount">
                            </div>
                            <div class="col-md-6">
                                <label for="revenue" class="form-label">Revenue</label>
                                <input type="number" step="0.01" class="form-control" id="revenue" name="revenue" readonly style="background-color: #e9ecef;">
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="achiv" class="form-label">Achievement (%)</label>
                                <input type="number" step="0.01" class="form-control" id="achiv" name="achiv" readonly style="background-color: #e9ecef;">
                            </div>
                        </div>-->

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

                    <script>
                        document.addEventListener('DOMContentLoaded', function() {
                            // Get all input elements
                            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 kpiInput = document.getElementById('kpi');
                            const revenueInput = document.getElementById('revenue');
                            const achivInput = document.getElementById('achiv');
                            const amountInput = document.getElementById('amount');
                            const paymentMethodSelect = document.getElementById('payment_method');
                            const bankAccountField = document.getElementById('bank_account_field');
                            const digitalPaymentField = document.getElementById('digital_payment_field');

                            // Helper: Safe number parsing
                            function getNumber(value) {
                                const num = parseFloat(value);
                                return isNaN(num) || num < 0 ? 0 : num;
                            }

                            // Calculate Total Sales = Qty × Price per unit
                            function calculateTotalSales() {
                                const qty = getNumber(qtyInput.value);
                                const sales = getNumber(salesInput.value);
                                const total = qty * sales;
                                totalSalesInput.value = total.toFixed(2);

                                // Trigger dependent calculations
                                calculateDue();
                                calculateGrossProfit();
                                calculateKPIAndAchievement();
                            }

                            // Calculate Due = Total Sales - Payment
                            function calculateDue() {
                                const totalSales = getNumber(totalSalesInput.value);
                                const payment = getNumber(paymentInput.value);
                                const due = totalSales - payment;
                                dueInput.value = Math.max(0, due).toFixed(2);
                            }

                            // Calculate Gross Profit = Total Sales - COGS
                            function calculateGrossProfit() {
                                const totalSales = getNumber(totalSalesInput.value);
                                const cogs = getNumber(cogsInput.value);
                                const profit = totalSales - cogs;
                                grossProfitInput.value = profit.toFixed(2);
                                calculatePercentage();
                            }

                            // Calculate Profit Margin % = (Gross Profit / Total Sales) × 100
                            function calculatePercentage() {
                                const totalSales = getNumber(totalSalesInput.value);
                                const grossProfit = getNumber(grossProfitInput.value);

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

                            // Calculate KPI Reference, Revenue, and Achievement %
                            function calculateKPIAndAchievement() {
                                // Revenue = Total Sales (business logic)
                                const totalSales = getNumber(totalSalesInput.value);
                                revenueInput.value = totalSales.toFixed(2);

                                // KPI Target = Amount input by user (for reference)
                                const targetAmount = getNumber(amountInput.value);
                                kpiInput.value = targetAmount > 0 ? targetAmount.toFixed(2) : '0.00';

                                // Achievement % = (Revenue / Target) × 100
                                if (targetAmount > 0) {
                                    const achievement = (totalSales / targetAmount) * 100;
                                    achivInput.value = achievement.toFixed(2);
                                } else {
                                    achivInput.value = '0.00';
                                }
                            }

                            // Toggle payment method fields (for display only, not submitted)
                            function togglePaymentFields() {
                                const method = paymentMethodSelect.value;

                                if (bankAccountField) {
                                    bankAccountField.style.display = (method === 'bank') ? 'block' : 'none';
                                }

                                if (digitalPaymentField) {
                                    digitalPaymentField.style.display = (method === 'digital') ? 'block' : 'none';
                                }
                            }

                            // Attach event listeners
                            qtyInput?.addEventListener('input', calculateTotalSales);
                            salesInput?.addEventListener('input', calculateTotalSales);
                            paymentInput?.addEventListener('input', calculateDue);
                            cogsInput?.addEventListener('input', calculateGrossProfit);
                            amountInput?.addEventListener('input', calculateKPIAndAchievement);
                            paymentMethodSelect?.addEventListener('change', togglePaymentFields);

                            // Allow manual total_sales edit (recalculates downstream values)
                            totalSalesInput?.addEventListener('change', function() {
                                calculateGrossProfit();
                                calculateKPIAndAchievement();
                            });

                            // Initialize on load
                            togglePaymentFields();

                            // Pre-fill calculations if form has old values (after validation error)
                            if (totalSalesInput.value || amountInput.value) {
                                calculateGrossProfit();
                                calculateKPIAndAchievement();
                            }
                        });
                    </script>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection
