@extends('layouts.app')

@section('content')
<div class="card">
    <div class="card-header">
        <h3 class="card-title"><i class="fas fa-plus-circle"></i> New Production Batch</h3>
        <a href="{{ route('production.index') }}" class="btn btn-outline">
            <i class="fas fa-arrow-left"></i> Back
        </a>
    </div>
    <div class="card-body">
        @if($errors->any())
            <div style="background-color: #f8d7da; border: 1px solid #f5c6cb; color: #721c24; padding: 1rem; border-radius: 4px; margin-bottom: 1rem;">
                <strong><i class="fas fa-exclamation-triangle"></i> Please fix the following errors:</strong>
                <ul style="margin: 0.5rem 0 0 1.5rem;">
                    @foreach($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif

        @if(session('error'))
            <div style="background-color: #f8d7da; border: 1px solid #f5c6cb; color: #721c24; padding: 1rem; border-radius: 4px; margin-bottom: 1rem;">
                <i class="fas fa-exclamation-circle"></i> {{ session('error') }}
            </div>
        @endif

        <form action="{{ route('production.store') }}" method="POST" id="productionForm">
            @csrf

            <!-- Production Header -->
            <div class="form-row">
                <div class="form-group" style="flex: 0 0 180px;">
                    <label class="form-label" for="batch_no">Batch No</label>
                    <input type="text" class="form-control" id="batch_no" value="{{ $nextBatchNo }}" readonly style="background-color: #f8f9fa; font-weight: 600;">
                </div>
                <div class="form-group" style="flex: 0 0 180px;">
                    <label class="form-label" for="date">Date <span class="text-danger">*</span></label>
                    <input type="date" class="form-control" id="date" name="date" value="{{ old('date', date('Y-m-d')) }}" required>
                </div>
                <div class="form-group" style="flex: 1;">
                    <label class="form-label" for="machine">Machine / Process</label>
                    <input type="text" class="form-control" id="machine" name="machine" value="{{ old('machine') }}" placeholder="e.g., Machine A, Carding Unit">
                </div>
            </div>

            <!-- Raw Materials Input Section -->
            <div style="background: #fff3e0; padding: 1rem; border-radius: 8px; margin-bottom: 1.5rem; border: 1px solid #ffcc80;">
                <h4 style="margin: 0 0 1rem 0; color: #e65100;"><i class="fas fa-arrow-right"></i> Raw Materials Input</h4>
                
                <table id="inputItemsTable" style="width: 100%; border: 1px solid #ffcc80;">
                    <thead>
                        <tr style="background: #ffe0b2;">
                            <th style="width: 50px;">#</th>
                            <th>Raw Material Item <span class="text-danger">*</span></th>
                            <th style="width: 120px;">Available Stock</th>
                            <th style="width: 150px;">Quantity (KG) <span class="text-danger">*</span></th>
                            <th style="width: 120px;">Rate</th>
                            <th style="width: 150px;">Amount</th>
                            <th style="width: 50px;"></th>
                        </tr>
                    </thead>
                    <tbody id="inputItemsBody">
                        <tr class="input-row">
                            <td class="text-center">1</td>
                            <td>
                                <select class="form-control input-item-select" name="input_items[0][item_id]" required>
                                    <option value="">Select Raw Material</option>
                                    @foreach($rawItems as $item)
                                        <option value="{{ $item->id }}" data-stock="{{ $item->current_stock }}" data-rate="{{ $item->purchase_price }}" data-unit="{{ $item->unit }}">
                                            {{ $item->name }} ({{ $item->code }})
                                        </option>
                                    @endforeach
                                </select>
                            </td>
                            <td class="text-center input-stock">-</td>
                            <td>
                                <input type="number" class="form-control input-qty" name="input_items[0][quantity]" step="0.001" min="0.001" required>
                            </td>
                            <td class="text-right input-rate">Rs. 0.00</td>
                            <td class="text-right input-amount">Rs. 0.00</td>
                            <td class="text-center">
                                <button type="button" class="btn btn-outline remove-input-row" style="padding: 0.25rem 0.5rem; color: var(--danger-color);" disabled>
                                    <i class="fas fa-times"></i>
                                </button>
                            </td>
                        </tr>
                    </tbody>
                    <tfoot>
                        <tr>
                            <td colspan="7" style="padding: 0.5rem;">
                                <button type="button" class="btn btn-outline" id="addInputRow" style="color: #e65100; border-color: #e65100;">
                                    <i class="fas fa-plus"></i> Add Raw Material
                                </button>
                            </td>
                        </tr>
                        <tr style="background: #ffe0b2;">
                            <td colspan="5" class="text-right"><strong>Total Raw Material Cost:</strong></td>
                            <td class="text-right"><strong id="totalRawMaterialCost">Rs. 0.00</strong></td>
                            <td></td>
                        </tr>
                    </tfoot>
                </table>
            </div>

            <!-- Finished Goods Output Section -->
            <div style="background: #e8f5e9; padding: 1rem; border-radius: 8px; margin-bottom: 1.5rem; border: 1px solid #a5d6a7;">
                <h4 style="margin: 0 0 1rem 0; color: #2e7d32;"><i class="fas fa-arrow-left"></i> Finished Goods Output</h4>
                
                <table id="outputItemsTable" style="width: 100%; border: 1px solid #a5d6a7;">
                    <thead>
                        <tr style="background: #c8e6c9;">
                            <th style="width: 50px;">#</th>
                            <th>Finished Item <span class="text-danger">*</span></th>
                            <th style="width: 150px;">Quantity (KG) <span class="text-danger">*</span></th>
                            <th style="width: 150px;">Cost/Unit</th>
                            <th style="width: 150px;">Amount</th>
                            <th style="width: 50px;"></th>
                        </tr>
                    </thead>
                    <tbody id="outputItemsBody">
                        <tr class="output-row">
                            <td class="text-center">1</td>
                            <td>
                                <select class="form-control output-item-select" name="output_items[0][item_id]" required>
                                    <option value="">Select Finished Item</option>
                                    @foreach($finishItems as $item)
                                        <option value="{{ $item->id }}">{{ $item->name }} ({{ $item->code }})</option>
                                    @endforeach
                                </select>
                            </td>
                            <td>
                                <input type="number" class="form-control output-qty" name="output_items[0][quantity]" step="0.001" min="0.001" required>
                            </td>
                            <td class="text-right output-rate">Rs. 0.00</td>
                            <td class="text-right output-amount">Rs. 0.00</td>
                            <td class="text-center">
                                <button type="button" class="btn btn-outline remove-output-row" style="padding: 0.25rem 0.5rem; color: var(--danger-color);" disabled>
                                    <i class="fas fa-times"></i>
                                </button>
                            </td>
                        </tr>
                    </tbody>
                    <tfoot>
                        <tr>
                            <td colspan="6" style="padding: 0.5rem;">
                                <button type="button" class="btn btn-outline" id="addOutputRow" style="color: #2e7d32; border-color: #2e7d32;">
                                    <i class="fas fa-plus"></i> Add Finished Item
                                </button>
                            </td>
                        </tr>
                        <tr style="background: #c8e6c9;">
                            <td colspan="2" class="text-right"><strong>Total Output Quantity:</strong></td>
                            <td class="text-center"><strong id="totalOutputQty">0.000 KG</strong></td>
                            <td></td>
                            <td class="text-right"><strong id="totalOutputValue">Rs. 0.00</strong></td>
                            <td></td>
                        </tr>
                    </tfoot>
                </table>
            </div>

            <!-- Additional Costs Section -->
            <div style="background: #fce4ec; padding: 1rem; border-radius: 8px; margin-bottom: 1.5rem; border: 1px solid #f8bbd9;">
                <h4 style="margin: 0 0 1rem 0; color: #c2185b;"><i class="fas fa-coins"></i> Additional Production Costs</h4>
                
                <div class="form-row">
                    <div class="form-group" style="flex: 1;">
                        <label class="form-label" for="agent_commission">Agent Commission</label>
                        <input type="number" class="form-control cost-input" id="agent_commission" name="agent_commission" step="0.01" min="0" value="{{ old('agent_commission', 0) }}">
                    </div>
                    <div class="form-group" style="flex: 1;">
                        <label class="form-label" for="transportation_cost">Transportation Cost</label>
                        <input type="number" class="form-control cost-input" id="transportation_cost" name="transportation_cost" step="0.01" min="0" value="{{ old('transportation_cost', 0) }}">
                    </div>
                    <div class="form-group" style="flex: 1;">
                        <label class="form-label" for="labor_cost">Labor Cost</label>
                        <input type="number" class="form-control cost-input" id="labor_cost" name="labor_cost" step="0.01" min="0" value="{{ old('labor_cost', 0) }}">
                    </div>
                    <div class="form-group" style="flex: 1;">
                        <label class="form-label" for="electricity_cost">Electricity Cost</label>
                        <input type="number" class="form-control cost-input" id="electricity_cost" name="electricity_cost" step="0.01" min="0" value="{{ old('electricity_cost', 0) }}">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group" style="flex: 0 0 200px;">
                        <label class="form-label" for="other_expenses">Other Expenses</label>
                        <input type="number" class="form-control cost-input" id="other_expenses" name="other_expenses" step="0.01" min="0" value="{{ old('other_expenses', 0) }}">
                    </div>
                    <div class="form-group" style="flex: 1;">
                        <label class="form-label" for="other_expenses_description">Other Expenses Description</label>
                        <input type="text" class="form-control" id="other_expenses_description" name="other_expenses_description" value="{{ old('other_expenses_description') }}" placeholder="Describe other expenses...">
                    </div>
                </div>
            </div>

            <!-- Cost Summary -->
            <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 1.5rem; border-radius: 8px; margin-bottom: 1rem; color: white;">
                <h4 style="margin: 0 0 1rem 0;"><i class="fas fa-calculator"></i> Production Cost Summary</h4>
                
                <div class="form-row" style="justify-content: space-between;">
                    <div style="text-align: center; flex: 1;">
                        <div style="font-size: 0.875rem; opacity: 0.9;">Raw Material Cost</div>
                        <div style="font-size: 1.5rem; font-weight: 700;" id="summaryRawCost">Rs. 0.00</div>
                    </div>
                    <div style="text-align: center; flex: 1;">
                        <div style="font-size: 0.875rem; opacity: 0.9;">Additional Costs</div>
                        <div style="font-size: 1.5rem; font-weight: 700;" id="summaryAddCost">Rs. 0.00</div>
                    </div>
                    <div style="text-align: center; flex: 1;">
                        <div style="font-size: 0.875rem; opacity: 0.9;">Total Production Cost</div>
                        <div style="font-size: 1.75rem; font-weight: 700;" id="summaryTotalCost">Rs. 0.00</div>
                    </div>
                    <div style="text-align: center; flex: 1;">
                        <div style="font-size: 0.875rem; opacity: 0.9;">Output Quantity</div>
                        <div style="font-size: 1.5rem; font-weight: 700;" id="summaryOutputQty">0.000 KG</div>
                    </div>
                    <div style="text-align: center; flex: 1; background: rgba(255,255,255,0.2); padding: 0.5rem; border-radius: 8px;">
                        <div style="font-size: 0.875rem;">COST PER UNIT</div>
                        <div style="font-size: 2rem; font-weight: 700;" id="summaryCostPerUnit">Rs. 0.00</div>
                    </div>
                </div>
            </div>

            <!-- Wastage Calculation Row -->
            <div style="background: linear-gradient(135deg, #f39c12, #e67e22); color: white; padding: 1rem; border-radius: 8px; margin-bottom: 1.5rem;">
                <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 1rem;">
                    <div style="text-align: center; flex: 1; min-width: 100px;">
                        <div style="font-size: 0.8rem; opacity: 0.9;"><i class="fas fa-arrow-right"></i> Input Weight</div>
                        <div style="font-size: 1.25rem; font-weight: 700;" id="wastageInputWeight">0 KG</div>
                    </div>
                    <div style="font-size: 1.5rem; opacity: 0.7;">−</div>
                    <div style="text-align: center; flex: 1; min-width: 100px;">
                        <div style="font-size: 0.8rem; opacity: 0.9;"><i class="fas fa-arrow-left"></i> Output Weight</div>
                        <div style="font-size: 1.25rem; font-weight: 700;" id="wastageOutputWeight">0 KG</div>
                    </div>
                    <div style="font-size: 1.5rem; opacity: 0.7;">=</div>
                    <div style="text-align: center; flex: 1; min-width: 100px;">
                        <div style="font-size: 0.8rem; opacity: 0.9;"><i class="fas fa-trash-alt"></i> Wastage</div>
                        <div style="font-size: 1.25rem; font-weight: 700;" id="wastageWeight">0 KG</div>
                    </div>
                    <div style="font-size: 1.5rem; opacity: 0.7;">|</div>
                    <div style="text-align: center; flex: 1; min-width: 80px;">
                        <div style="font-size: 0.8rem; opacity: 0.9;"><i class="fas fa-percent"></i> Wastage %</div>
                        <div style="font-size: 1.25rem; font-weight: 700;" id="wastagePercent">0.00%</div>
                    </div>
                    <div style="font-size: 1.5rem; opacity: 0.7;">|</div>
                    <div style="text-align: center; flex: 1; min-width: 110px;">
                        <div style="font-size: 0.8rem; opacity: 0.9;"><i class="fas fa-coins"></i> Wastage Cost</div>
                        <div style="font-size: 1.25rem; font-weight: 700;" id="wastageCost">Rs. 0</div>
                    </div>
                    <div style="font-size: 1.5rem; opacity: 0.7;">|</div>
                    <div style="text-align: center; flex: 1; min-width: 120px; background: rgba(0,0,0,0.2); padding: 0.5rem; border-radius: 6px;">
                        <div style="font-size: 0.8rem; opacity: 0.9;"><i class="fas fa-recycle"></i> Waste Per Unit</div>
                        <div style="font-size: 1.25rem; font-weight: 700;" id="wastePerUnit">Rs. 0.00/KG</div>
                    </div>
                </div>
            </div>

            <!-- Narration -->
            <div class="form-group">
                <label class="form-label" for="narration">Narration / Notes</label>
                <textarea class="form-control" id="narration" name="narration" rows="2" placeholder="Optional notes about this production batch...">{{ old('narration') }}</textarea>
            </div>

            <div style="display: flex; gap: 0.5rem; margin-top: 1.5rem; padding-top: 1rem; border-top: 1px solid var(--border-color);">
                <button type="submit" class="btn btn-success">
                    <i class="fas fa-save"></i> Save Production
                </button>
                <a href="{{ route('production.index') }}" class="btn btn-outline">
                    <i class="fas fa-times"></i> Cancel
                </a>
            </div>
        </form>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    let inputRowCount = 1;
    let outputRowCount = 1;

    // Add Input Row
    document.getElementById('addInputRow').addEventListener('click', function() {
        const tbody = document.getElementById('inputItemsBody');
        const newRow = document.createElement('tr');
        newRow.className = 'input-row';
        newRow.innerHTML = `
            <td class="text-center">${inputRowCount + 1}</td>
            <td>
                <select class="form-control input-item-select" name="input_items[${inputRowCount}][item_id]" required>
                    <option value="">Select Raw Material</option>
                    @foreach($rawItems as $item)
                        <option value="{{ $item->id }}" data-stock="{{ $item->current_stock }}" data-rate="{{ $item->purchase_price }}" data-unit="{{ $item->unit }}">
                            {{ $item->name }} ({{ $item->code }})
                        </option>
                    @endforeach
                </select>
            </td>
            <td class="text-center input-stock">-</td>
            <td>
                <input type="number" class="form-control input-qty" name="input_items[${inputRowCount}][quantity]" step="0.001" min="0.001" required>
            </td>
            <td class="text-right input-rate">Rs. 0.00</td>
            <td class="text-right input-amount">Rs. 0.00</td>
            <td class="text-center">
                <button type="button" class="btn btn-outline remove-input-row" style="padding: 0.25rem 0.5rem; color: var(--danger-color);">
                    <i class="fas fa-times"></i>
                </button>
            </td>
        `;
        tbody.appendChild(newRow);
        inputRowCount++;
        updateRemoveButtons();
        attachInputEvents(newRow);
    });

    // Add Output Row
    document.getElementById('addOutputRow').addEventListener('click', function() {
        const tbody = document.getElementById('outputItemsBody');
        const newRow = document.createElement('tr');
        newRow.className = 'output-row';
        newRow.innerHTML = `
            <td class="text-center">${outputRowCount + 1}</td>
            <td>
                <select class="form-control output-item-select" name="output_items[${outputRowCount}][item_id]" required>
                    <option value="">Select Finished Item</option>
                    @foreach($finishItems as $item)
                        <option value="{{ $item->id }}">{{ $item->name }} ({{ $item->code }})</option>
                    @endforeach
                </select>
            </td>
            <td>
                <input type="number" class="form-control output-qty" name="output_items[${outputRowCount}][quantity]" step="0.001" min="0.001" required>
            </td>
            <td class="text-right output-rate">Rs. 0.00</td>
            <td class="text-right output-amount">Rs. 0.00</td>
            <td class="text-center">
                <button type="button" class="btn btn-outline remove-output-row" style="padding: 0.25rem 0.5rem; color: var(--danger-color);">
                    <i class="fas fa-times"></i>
                </button>
            </td>
        `;
        tbody.appendChild(newRow);
        outputRowCount++;
        updateRemoveButtons();
        attachOutputEvents(newRow);
    });

    function updateRemoveButtons() {
        const inputRows = document.querySelectorAll('.input-row');
        const outputRows = document.querySelectorAll('.output-row');
        
        inputRows.forEach((row, index) => {
            const btn = row.querySelector('.remove-input-row');
            btn.disabled = inputRows.length === 1;
        });
        
        outputRows.forEach((row, index) => {
            const btn = row.querySelector('.remove-output-row');
            btn.disabled = outputRows.length === 1;
        });
    }

    function attachInputEvents(row) {
        const select = row.querySelector('.input-item-select');
        const qtyInput = row.querySelector('.input-qty');
        
        select.addEventListener('change', function() {
            const option = this.options[this.selectedIndex];
            const stock = option.dataset.stock || 0;
            const rate = option.dataset.rate || 0;
            row.querySelector('.input-stock').textContent = parseFloat(stock).toFixed(3);
            row.querySelector('.input-rate').textContent = 'Rs. ' + parseFloat(rate).toFixed(2);
            calculateInputAmount(row);
        });
        
        qtyInput.addEventListener('input', function() {
            calculateInputAmount(row);
        });
        
        row.querySelector('.remove-input-row').addEventListener('click', function() {
            row.remove();
            renumberRows();
            calculateTotals();
        });
    }

    function attachOutputEvents(row) {
        const qtyInput = row.querySelector('.output-qty');
        
        qtyInput.addEventListener('input', function() {
            calculateTotals();
        });
        
        row.querySelector('.remove-output-row').addEventListener('click', function() {
            row.remove();
            renumberRows();
            calculateTotals();
        });
    }

    function calculateInputAmount(row) {
        const select = row.querySelector('.input-item-select');
        const option = select.options[select.selectedIndex];
        const rate = parseFloat(option.dataset.rate) || 0;
        const qty = parseFloat(row.querySelector('.input-qty').value) || 0;
        const amount = rate * qty;
        row.querySelector('.input-amount').textContent = 'Rs. ' + amount.toFixed(2);
        calculateTotals();
    }

    function calculateTotals() {
        // Calculate raw material total and input weight
        let rawMaterialCost = 0;
        let inputWeight = 0;
        document.querySelectorAll('.input-row').forEach(row => {
            const select = row.querySelector('.input-item-select');
            const option = select.options[select.selectedIndex];
            const rate = parseFloat(option?.dataset?.rate) || 0;
            const qty = parseFloat(row.querySelector('.input-qty').value) || 0;
            rawMaterialCost += rate * qty;
            inputWeight += qty;
        });
        document.getElementById('totalRawMaterialCost').textContent = 'Rs. ' + rawMaterialCost.toFixed(2);
        document.getElementById('summaryRawCost').textContent = 'Rs. ' + rawMaterialCost.toFixed(2);

        // Calculate output quantity
        let outputQty = 0;
        document.querySelectorAll('.output-row').forEach(row => {
            const qty = parseFloat(row.querySelector('.output-qty').value) || 0;
            outputQty += qty;
        });
        document.getElementById('totalOutputQty').textContent = outputQty.toFixed(3) + ' KG';
        document.getElementById('summaryOutputQty').textContent = outputQty.toFixed(3) + ' KG';

        // Calculate additional costs
        const agentCommission = parseFloat(document.getElementById('agent_commission').value) || 0;
        const transportCost = parseFloat(document.getElementById('transportation_cost').value) || 0;
        const laborCost = parseFloat(document.getElementById('labor_cost').value) || 0;
        const electricityCost = parseFloat(document.getElementById('electricity_cost').value) || 0;
        const otherExpenses = parseFloat(document.getElementById('other_expenses').value) || 0;
        const additionalCosts = agentCommission + transportCost + laborCost + electricityCost + otherExpenses;
        document.getElementById('summaryAddCost').textContent = 'Rs. ' + additionalCosts.toFixed(2);

        // Calculate total cost
        const totalCost = rawMaterialCost + additionalCosts;
        document.getElementById('summaryTotalCost').textContent = 'Rs. ' + totalCost.toFixed(2);

        // Calculate cost per unit
        const costPerUnit = outputQty > 0 ? totalCost / outputQty : 0;
        document.getElementById('summaryCostPerUnit').textContent = 'Rs. ' + costPerUnit.toFixed(2);

        // Calculate wastage
        const wastageWeight = inputWeight - outputQty;
        const wastagePercent = inputWeight > 0 ? (wastageWeight / inputWeight) * 100 : 0;
        const wastageCost = inputWeight > 0 ? (wastageWeight / inputWeight) * rawMaterialCost : 0;
        const wastePerUnit = outputQty > 0 ? wastageCost / outputQty : 0;

        // Update wastage row
        document.getElementById('wastageInputWeight').textContent = inputWeight.toFixed(0) + ' KG';
        document.getElementById('wastageOutputWeight').textContent = outputQty.toFixed(0) + ' KG';
        document.getElementById('wastageWeight').textContent = wastageWeight.toFixed(0) + ' KG';
        document.getElementById('wastagePercent').textContent = wastagePercent.toFixed(2) + '%';
        document.getElementById('wastageCost').textContent = 'Rs. ' + wastageCost.toFixed(0);
        document.getElementById('wastePerUnit').textContent = 'Rs. ' + wastePerUnit.toFixed(2) + '/KG';

        // Update output rows with calculated cost per unit
        document.querySelectorAll('.output-row').forEach(row => {
            const qty = parseFloat(row.querySelector('.output-qty').value) || 0;
            row.querySelector('.output-rate').textContent = 'Rs. ' + costPerUnit.toFixed(2);
            row.querySelector('.output-amount').textContent = 'Rs. ' + (qty * costPerUnit).toFixed(2);
        });

        // Update total output value
        document.getElementById('totalOutputValue').textContent = 'Rs. ' + totalCost.toFixed(2);
    }

    function renumberRows() {
        document.querySelectorAll('.input-row').forEach((row, index) => {
            row.querySelector('td:first-child').textContent = index + 1;
        });
        document.querySelectorAll('.output-row').forEach((row, index) => {
            row.querySelector('td:first-child').textContent = index + 1;
        });
        updateRemoveButtons();
    }

    // Attach events to initial rows
    document.querySelectorAll('.input-row').forEach(attachInputEvents);
    document.querySelectorAll('.output-row').forEach(attachOutputEvents);

    // Cost inputs trigger recalculation
    document.querySelectorAll('.cost-input').forEach(input => {
        input.addEventListener('input', calculateTotals);
    });
});
</script>
@endsection
