@extends('layouts.main')

@section('content')
<div class="d-flex justify-content-between align-items-center mb-4">
    <h4>Price Adjustment</h4>
    <a href="{{ route('inventory.price-adjustment') }}" class="btn btn-secondary">
        <i class="bi bi-arrow-counterclockwise"></i> Reset
    </a>
</div>

@if(session('success'))
<div class="alert alert-success">{{ session('success') }}</div>
@endif

<div class="row">
    <div class="col-lg-4">
        <div class="card">
            <div class="card-body">
                <form method="POST" action="{{ route('inventory.price-adjustment') }}" id="priceForm">
                    @csrf
                    
                    <div class="mb-3">
                        <label class="form-label">Select Product</label>
                        <select class="form-select select2" id="productSelect">
                            <option value="">-- Select a product --</option>
                            @foreach($products as $product)
                                <option value="{{ $product->id }}" 
                                    data-cost="{{ $product->cost_price }}" 
                                    data-selling="{{ $product->selling_price }}"
                                    data-price2="{{ $product->price_2 ?? 0 }}"
                                    data-price3="{{ $product->price_3 ?? 0 }}"
                                    data-category="{{ $product->category->name ?? 'Uncategorized' }}">
                                    {{ $product->name }} ({{ $product->category->name ?? 'Uncategorized' }})
                                </option>
                            @endforeach
                        </select>
                    </div>

                    <div class="row mb-3">
                        <div class="col-6">
                            <label class="form-label">Current Cost</label>
                            <input type="text" class="form-control" id="currentCost" readonly>
                        </div>
                        <div class="col-6">
                            <label class="form-label">Current Selling</label>
                            <input type="text" class="form-control" id="currentSelling" readonly>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Price Change</label>
                        <div class="btn-group w-100" role="group">
                            <input type="radio" class="btn-check" name="operation" value="increase" id="increase" checked>
                            <label class="btn btn-outline-success" for="increase">
                                <i class="bi bi-arrow-up"></i> Increase
                            </label>
                            <input type="radio" class="btn-check" name="operation" value="decrease" id="decrease">
                            <label class="btn btn-outline-danger" for="decrease">
                                <i class="bi bi-arrow-down"></i> Decrease
                            </label>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Amount</label>
                        <div class="input-group">
                            <input type="number" class="form-control" id="adjustmentValue" placeholder="0.00" step="any" required>
                            <select class="form-select" style="max-width: 100px;" id="adjustmentType">
                                <option value="percentage">%</option>
                                <option value="fixed">Kes</option>
                            </select>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Apply To</label>
                        <select class="form-select" id="priceType">
                            <option value="selling">Selling Price</option>
                            <option value="cost">Cost Price</option>
                            <option value="price2">Price 2</option>
                            <option value="price3">Price 3</option>
                            <option value="both">All Prices</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">New Price Preview</label>
                        <div class="row">
                            <div class="col-6">
                                <input type="text" class="form-control" id="newCost" readonly placeholder="New Cost">
                            </div>
                            <div class="col-6">
                                <input type="text" class="form-control" id="newSelling" readonly placeholder="New Selling">
                            </div>
                            <div class="col-6 mt-2">
                                <input type="text" class="form-control" id="newPrice2" readonly placeholder="New Price 2">
                            </div>
                            <div class="col-6 mt-2">
                                <input type="text" class="form-control" id="newPrice3" readonly placeholder="New Price 3">
                            </div>
                        </div>
                    </div>

                    <button type="submit" class="btn btn-primary" id="applyBtn">
                        <i class="bi bi-check-lg"></i> Apply Price Change
                    </button>
                </form>
            </div>
        </div>

        <div class="card mt-3">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <strong>Bulk Price Update</strong>
                    <span class="badge bg-primary" id="selectedCount">0 selected</span>
                </div>
                <p class="small text-muted mb-2">Check products in the list, then click Apply to update all at once.</p>
                <button type="button" class="btn btn-warning w-100" id="bulkApplyBtn" disabled>
                    <i class="bi bi-collection"></i> Apply to Selected
                </button>
            </div>
        </div>
    </div>

    <div class="col-lg-8">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="selectAll">
                    <label class="form-check-label" for="selectAll">
                        <strong>Select All</strong>
                    </label>
                </div>
                <div class="d-flex gap-2">
                    <input type="text" class="form-control" placeholder="Search products..." id="searchProducts">
                    <select class="form-select" style="width: auto;" id="categoryFilter">
                        <option value="">All Categories</option>
                        @foreach($categories as $category)
                            <option value="{{ $category->id }}">{{ $category->name }}</option>
                        @endforeach
                    </select>
                </div>
            </div>
            <div class="card-body table-responsive" style="max-height: 700px;">
                <table class="table table-sm table-hover mb-0">
                    <thead class="sticky-top bg-white">
                        <tr>
                            <th width="40"></th>
                            <th>Product</th>
                            <th>Current Cost</th>
                            <th>Current Selling</th>
                            <th>Price 2</th>
                            <th>Price 3</th>
                            <th>New Cost</th>
                            <th>New Selling</th>
                            <th>Margin</th>
                        </tr>
                    </thead>
                    <tbody id="productTable">
                        @foreach($products as $product)
                        <tr data-id="{{ $product->id }}" 
                            data-cost="{{ $product->cost_price }}" 
                            data-selling="{{ $product->selling_price }}" 
                            data-price2="{{ $product->price_2 ?? 0 }}"
                            data-price3="{{ $product->price_3 ?? 0 }}"
                            data-name="{{ strtolower($product->name) }}"
                            data-category="{{ $product->category_id }}">
                            <td>
                                <input class="form-check-input product-checkbox" type="checkbox" value="{{ $product->id }}">
                            </td>
                            <td>
                                <strong>{{ $product->name }}</strong>
                                <div class="small text-muted">{{ $product->category->name ?? 'Uncategorized' }}</div>
                            </td>
                            <td class="current-cost">Kes {{ number_format($product->cost_price, 2) }}</td>
                            <td class="current-selling">Kes {{ number_format($product->selling_price, 2) }}</td>
                            <td class="current-price2">Kes {{ number_format($product->price_2 ?? 0, 2) }}</td>
                            <td class="current-price3">Kes {{ number_format($product->price_3 ?? 0, 2) }}</td>
                            <td class="new-cost text-muted">-</td>
                            <td class="new-selling text-muted">-</td>
                            <td>
                                @php $margin = $product->cost_price > 0 ? (($product->selling_price - $product->cost_price) / $product->cost_price) * 100 : 0; @endphp
                                <span class="badge bg-{{ $margin > 20 ? 'success' : ($margin > 0 ? 'warning' : 'danger') }} margin-badge">
                                    {{ number_format($margin, 1) }}%
                                </span>
                            </td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<form method="POST" action="{{ route('inventory.price-adjustment') }}" id="bulkForm" style="display: none;">
    @csrf
    <input type="hidden" name="bulk_update" value="1">
    <input type="hidden" name="product_ids" id="bulkProductIds">
    <input type="hidden" name="adjustment_type" id="bulkAdjustmentType">
    <input type="hidden" name="adjustment_value" id="bulkAdjustmentValue">
    <input type="hidden" name="operation" id="bulkOperation">
    <input type="hidden" name="price_type" id="bulkPriceType">
</form>

@section('scripts')
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
$(document).ready(function() {
    $('.select2').select2({
        placeholder: '-- Select a product --',
        width: '100%'
    });

    function calculateNewPrice(currentPrice, value, type, operation) {
        if (!value || value <= 0) return null;
        
        if (type === 'percentage') {
            return operation === 'increase' 
                ? currentPrice * (1 + value / 100)
                : currentPrice * (1 - value / 100);
        } else {
            return operation === 'increase' 
                ? currentPrice + value
                : Math.max(0, currentPrice - value);
        }
    }

    function updatePreview() {
        const option = $('#productSelect option:selected');
        const cost = parseFloat(option.data('cost')) || 0;
        const selling = parseFloat(option.data('selling')) || 0;
        const price2 = parseFloat(option.data('price2')) || 0;
        const price3 = parseFloat(option.data('price3')) || 0;
        const value = parseFloat($('#adjustmentValue').val()) || 0;
        const type = $('#adjustmentType').val();
        const operation = $('input[name="operation"]:checked').val();
        const priceType = $('#priceType').val();

        $('#currentCost').val(cost > 0 ? 'Kes ' + cost.toFixed(2) : '-');
        $('#currentSelling').val(selling > 0 ? 'Kes ' + selling.toFixed(2) : '-');

        let newCost = null;
        let newSelling = null;
        let newPrice2 = null;
        let newPrice3 = null;

        if (value > 0) {
            newCost = calculateNewPrice(cost, value, type, operation);
            newSelling = calculateNewPrice(selling, value, type, operation);
            newPrice2 = calculateNewPrice(price2, value, type, operation);
            newPrice3 = calculateNewPrice(price3, value, type, operation);
        }

        if (priceType === 'cost') {
            newSelling = null;
            newPrice2 = null;
            newPrice3 = null;
        } else if (priceType === 'selling') {
            newCost = null;
            newPrice2 = null;
            newPrice3 = null;
        } else if (priceType === 'price2') {
            newCost = null;
            newSelling = null;
            newPrice3 = null;
        } else if (priceType === 'price3') {
            newCost = null;
            newSelling = null;
            newPrice2 = null;
        }

        $('#newCost').val(newCost !== null ? 'Kes ' + newCost.toFixed(2) : '-');
        $('#newSelling').val(newSelling !== null ? 'Kes ' + newSelling.toFixed(2) : '-');
        $('#newPrice2').val(newPrice2 !== null ? 'Kes ' + newPrice2.toFixed(2) : '-');
        $('#newPrice3').val(newPrice3 !== null ? 'Kes ' + newPrice3.toFixed(2) : '-');
    }

    function updateTablePreview() {
        const value = parseFloat($('#adjustmentValue').val()) || 0;
        const type = $('#adjustmentType').val();
        const operation = $('input[name="operation"]:checked').val();
        const priceType = $('#priceType').val();

        $('#productTable tr').each(function() {
            const row = $(this);
            const cost = parseFloat(row.data('cost')) || 0;
            const selling = parseFloat(row.data('selling')) || 0;
            const price2 = parseFloat(row.data('price2')) || 0;
            const price3 = parseFloat(row.data('price3')) || 0;

            let newCost = null;
            let newSelling = null;
            let newPrice2 = null;
            let newPrice3 = null;

            if (value > 0) {
                newCost = calculateNewPrice(cost, value, type, operation);
                newSelling = calculateNewPrice(selling, value, type, operation);
                newPrice2 = calculateNewPrice(price2, value, type, operation);
                newPrice3 = calculateNewPrice(price3, value, type, operation);
            }

            if (priceType === 'cost') {
                newSelling = null;
                newPrice2 = null;
                newPrice3 = null;
            } else if (priceType === 'selling') {
                newCost = null;
                newPrice2 = null;
                newPrice3 = null;
            } else if (priceType === 'price2') {
                newCost = null;
                newSelling = null;
                newPrice3 = null;
            } else if (priceType === 'price3') {
                newCost = null;
                newSelling = null;
                newPrice2 = null;
            }

            row.find('.new-cost').text(newCost !== null ? 'Kes ' + newCost.toFixed(2) : '-');
            row.find('.new-selling').text(newSelling !== null ? 'Kes ' + newSelling.toFixed(2) : '-');

            if (newCost !== null || newSelling !== null) {
                row.find('.new-cost').removeClass('text-muted').addClass('text-success');
                row.find('.new-selling').removeClass('text-muted').addClass('text-success');
            } else {
                row.find('.new-cost, .new-selling').addClass('text-muted').removeClass('text-success');
            }
        });
    }

    $('#adjustmentValue, #adjustmentType').on('input change', function() {
        updatePreview();
        updateTablePreview();
    });
    $('input[name="operation"], #priceType').on('change', function() {
        updatePreview();
        updateTablePreview();
    });
    
    $('#productSelect').on('change', function() {
        const productId = $(this).val();
        if (productId) {
            $('#productTable tr').removeClass('table-active');
            $(`tr[data-id="${productId}"]`).addClass('table-active');
        }
    });

    $('#searchProducts, #categoryFilter').on('input change', function() {
        const search = $('#searchProducts').val().toLowerCase();
        const categoryId = $('#categoryFilter').val();

        $('#productTable tr').filter(function() {
            const row = $(this);
            const matchSearch = row.data('name').includes(search);
            const matchCategory = !categoryId || row.data('category') == categoryId;
            row.toggle(matchSearch && matchCategory);
        });
    });

    $('#selectAll').on('change', function() {
        const visibleRows = $('#productTable tr:visible');
        visibleRows.find('.product-checkbox').prop('checked', $(this).prop('checked'));
        updateSelectedCount();
    });

    $('.product-checkbox').on('change', function() {
        const allVisible = $('#productTable tr:visible .product-checkbox').length;
        const checked = $('#productTable tr:visible .product-checkbox:checked').length;
        $('#selectAll').prop('checked', allVisible > 0 && allVisible === checked);
        updateSelectedCount();
    });

    $('#bulkApplyBtn').on('click', function() {
        if (confirm('Apply price change to ' + $('.product-checkbox:checked').length + ' selected products?')) {
            applyToSelected();
        }
    });

    function updateSelectedCount() {
        const count = $('.product-checkbox:checked').length;
        $('#selectedCount').text(count + ' selected');
        $('#bulkApplyBtn').prop('disabled', count === 0);
    }

    function applyToSelected() {
        const selectedIds = $('.product-checkbox:checked').map(function() { return $(this).val(); }).get();
        if (selectedIds.length === 0) {
            alert('Please select at least one product.');
            return;
        }

        $('#bulkProductIds').val(JSON.stringify(selectedIds));
        $('#bulkAdjustmentType').val($('#adjustmentType').val());
        $('#bulkAdjustmentValue').val($('#adjustmentValue').val());
        $('#bulkOperation').val($('input[name="operation"]:checked').val());
        $('#bulkPriceType').val($('#priceType').val());
        $('#bulkForm').submit();
    }

    $('#applyBtn').on('click', function(e) {
        const productId = $('#productSelect').val();
        if (!productId) {
            e.preventDefault();
            alert('Please select a product first.');
            return;
        }

        const selectedIds = $('.product-checkbox:checked').map(function() { return $(this).val(); }).get();
        
        let idsToUpdate = [productId];
        if (selectedIds.length > 0) {
            idsToUpdate = [...new Set([productId, ...selectedIds])];
        }

        $('#priceForm').append($('<input>').attr({type: 'hidden', name: 'product_ids', value: JSON.stringify(idsToUpdate)}));
        $('#priceForm').append($('<input>').attr({type: 'hidden', name: 'adjustment_type', value: $('#adjustmentType').val()}));
        $('#priceForm').append($('<input>').attr({type: 'hidden', name: 'adjustment_value', value: $('#adjustmentValue').val()}));
        $('#priceForm').append($('<input>').attr({type: 'hidden', name: 'operation', value: $('input[name="operation"]:checked').val()}));
        $('#priceForm').append($('<input>').attr({type: 'hidden', name: 'price_type', value: $('#priceType').val()}));
    });

    function resetForm() {
        $('#productSelect').val('').trigger('change');
        $('#currentCost').val('');
        $('#currentSelling').val('');
        $('#adjustmentValue').val('');
        $('#adjustmentType').val('percentage');
        $('input[name="operation"][value="increase"]').prop('checked', true);
        $('#priceType').val('selling');
        $('#newCost').val('');
        $('#newSelling').val('');
        $('#newPrice2').val('');
        $('#newPrice3').val('');
    }
});
</script>
@endsection
@endsection
