@extends('layouts.app')

@section('title', __('report.stock_report'))

@section('content')

<section class="content-header">
    <h1>@lang('report.stock_report') 
        <small></small>
    </h1>
</section>

<section class="content">
    <div class="box box-primary">
        <div class="box-header with-border">
            <h3 class="box-title">@lang('report.stock_report')</h3>
        </div>
        <div class="box-body">
            <!-- Filter Form -->
            <div class="row">
                <div class="col-md-12">
                    <form method="GET" action="{{ route('custom-stock-report.get') }}" class="form-inline">
                        <div class="form-group">
                            {!! Form::label('location_id', __('sale.location') . ':') !!}
                            {!! Form::select('location_id', $business_locations, request()->location_id, ['class' => 'form-control select2', 'style' => 'width:200px', 'placeholder' => __('report.all')]); !!}
                        </div>
                        <div class="form-group">
                            {!! Form::label('category_id', __('product.category') . ':') !!}
                            {!! Form::select('category_id', $categories, request()->category_id, ['class' => 'form-control select2', 'style' => 'width:200px', 'placeholder' => __('report.all')]); !!}
                        </div>
                        <div class="form-group">
                            {!! Form::label('brand_id', __('product.brand') . ':') !!}
                            {!! Form::select('brand_id', $brands, request()->brand_id, ['class' => 'form-control select2', 'style' => 'width:200px', 'placeholder' => __('report.all')]); !!}
                        </div>
                        <div class="form-group">
                            {!! Form::label('unit_id', __('product.unit') . ':') !!}
                            {!! Form::select('unit_id', $units, request()->unit_id, ['class' => 'form-control select2', 'style' => 'width:200px', 'placeholder' => __('report.all')]); !!}
                        </div>
                         
                        <div class="form-group">
                            {!! Form::label('product_id', __('Products') . ':') !!}
                            {!! Form::select('product_id', $productDropdown, request()->product_id, ['class' => 'form-control select2', 'style' => 'width:250px', 'placeholder' => __('report.all')]); !!}
                        </div>
                        <button type="submit" class="btn btn-primary">Filter</button>
                        <a href="{{ route('custom-stock-report.get') }}" class="btn btn-default">Clear</a>
                    </form>
                </div>
            </div>
            <br>
            
            <!-- Stock Report Table -->
            <div class="table-responsive">
                <table class="table table-bordered table-striped" id="custom_stock_report_table">
                    <thead>
                        <tr>
                            <th>SKU</th>
                            <th>@lang('business.product')</th>
                            <th>@lang('product.category')</th>
                            <th>@lang('sale.location')</th>
                            <th>@lang('report.current_stock') (KG)</th>
                            <th>Price (KG)</th>
                            <th>@lang('report.current_stock') (Meter)</th>
                            <th>Price (Meter)</th>
                            <th>Feet</th>
                            <th>Yard</th>
                            <th>Lot Number</th>
                            <th>PCS</th>
                            <th>Cut PCS</th>
                            <th>{{$product_custom_field1}}</th>
                            <th>{{$product_custom_field2}}</th>
                        </tr>
                    </thead>
                    <tbody>
                        @php
                            $total_stock_kg = 0;
                            $total_stock_meter = 0;
                            $total_price_kg = 0;
                            $total_price_meter = 0;
                            $total_feet = 0;
                            $total_yard = 0;
                            $total_pcs = 0;
                            $total_cut_pcs = 0;
                            $total_cut_meter = 0;
                            $total_cut_kg = 0;
                        @endphp
                        
                        @foreach($products as $row)
                            @php
                                // Current Stock KG (from query)
                                $current_stock_kg = (float)($row->current_stock_kg ?? 0);
                                
                                // Purchase Price KG
                                $purchase_price_kg = (float)($row->purchase_price ?? 0);
                                
                                // Product Custom Field 2 (KG per Meter)
                                $product_custom_field2_val = (float)($row->product_custom_field2 ?? 0);
                                
                                // Lot Number
                                $lot_number = $row->lot_number ?? '';
                                
                                // ============================================
                                // CALCULATIONS
                                // ============================================
                                
                                // 1. Current Stock Meter = Current Stock KG / product_custom_field2
                                $current_stock_meter = 0;
                                if ($product_custom_field2_val > 0 && $current_stock_kg > 0) {
                                    $current_stock_meter = $current_stock_kg / $product_custom_field2_val;
                                }
                                
                                // 2. Price Meter = Purchase Price KG * product_custom_field2
                                $price_meter = 0;
                                if ($purchase_price_kg > 0 && $product_custom_field2_val > 0) {
                                    $price_meter = $purchase_price_kg * $product_custom_field2_val;
                                }
                                
                                // 3. Feet = Current Stock Meter * 3.28084
                                $feet = $current_stock_meter * 3.28084;
                                
                                // 4. Yard = Current Stock Meter * 1.09361
                                $yard = $current_stock_meter * 1.09361;
                                
                                // ============================================
                                // 5. PCS and Cut PCS Calculation based on Lot Number type
                                //    If lot number ends with 'M' -> Use Meter
                                //    If lot number ends with 'K' -> Use KG
                                // ============================================
                                $current_stock_pcs = 0;
                                $current_stock_cut_pcs = 0;
                                $current_stock_cut_value = 0;
                                $cut_unit = '';
                                
                                if (!empty($lot_number) && $current_stock_kg > 0) {
                                    // Extract numeric value from lot_number (e.g., "100M" -> 100, "5K" -> 5)
                                    $lot_numeric = preg_replace('/[^0-9.]/', '', $lot_number);
                                    $lot_numeric = (float)$lot_numeric;
                                    
                                    // Determine unit type (M or K)
                                    $lot_unit = strtoupper(substr(trim($lot_number), -1));
                                    
                                    if ($lot_numeric > 0) {
                                        // Calculate based on unit type
                                        if ($lot_unit == 'M') {
                                            // Use Meter for calculation
                                            $value_to_use = $current_stock_meter;
                                            $cut_unit = 'M';
                                        } elseif ($lot_unit == 'K') {
                                            // Use KG for calculation
                                            $value_to_use = $current_stock_kg;
                                            $cut_unit = 'K';
                                        } else {
                                            // Default: Use Meter (backward compatibility)
                                            $value_to_use = $current_stock_meter;
                                            $cut_unit = 'M';
                                        }
                                        
                                        if ($value_to_use > 0) {
                                            // Calculate PCS
                                            $pcs_calculated = $value_to_use / $lot_numeric;
                                            
                                            // Get whole number part (floor)
                                            $current_stock_pcs = floor($pcs_calculated);
                                            
                                            // Check if there is a remainder (decimal part)
                                            $remainder = $pcs_calculated - $current_stock_pcs;
                                            
                                            if ($remainder > 0) {
                                                // Calculate cut value (keep exact decimal)
                                                $current_stock_cut_value = $remainder * $lot_numeric;
                                                $current_stock_cut_pcs = 1; // There is a cut piece
                                                
                                                // If whole number part is 0, show PCS as 1 (minimum 1)
                                                if ($current_stock_pcs < 1) {
                                                    $current_stock_pcs = 1;
                                                }
                                            } else {
                                                // No remainder, no cut piece
                                                $current_stock_cut_pcs = 0;
                                                $current_stock_cut_value = 0;
                                                
                                                // If whole number part is 0, show PCS as 1 (minimum 1)
                                                if ($current_stock_pcs < 1) {
                                                    $current_stock_pcs = 1;
                                                }
                                            }
                                        }
                                    }
                                }
                                
                                // Format Cut PCS display as: 1/50M or 1/2.5K or 0
                                $cut_pcs_display = '0';
                                if (!empty($lot_number) && $row->enable_stock) {
                                    if ($current_stock_cut_pcs > 0 && $current_stock_cut_value > 0) {
                                        // Show cut value with proper decimal places (max 2 decimal places)
                                        $cut_value_formatted = number_format($current_stock_cut_value, 2, '.', '');
                                        // Remove trailing zeros if any
                                        $cut_value_formatted = rtrim(rtrim($cut_value_formatted, '0'), '.');
                                        $cut_pcs_display = $current_stock_cut_pcs . '/' . $cut_value_formatted . $cut_unit;
                                    } elseif ($current_stock_cut_pcs == 0) {
                                        $cut_pcs_display = '0';
                                    }
                                }
                                
                                // Totals for footer
                                $total_stock_kg += $current_stock_kg;
                                $total_stock_meter += $current_stock_meter;
                                $total_price_kg += $purchase_price_kg;
                                $total_price_meter += $price_meter;
                                $total_feet += $feet;
                                $total_yard += $yard;
                                $total_pcs += $current_stock_pcs;
                                $total_cut_pcs += $current_stock_cut_pcs;
                                
                                // Add cut value to appropriate total based on unit
                                if ($cut_unit == 'M') {
                                    $total_cut_meter += $current_stock_cut_value;
                                } elseif ($cut_unit == 'K') {
                                    $total_cut_kg += $current_stock_cut_value;
                                }
                                
                                $row_class = $row->enable_stock && $current_stock_kg <= $row->alert_quantity ? 'bg-danger' : '';
                            @endphp
                            <tr class="{{ $row_class }}">
                                <td>{{ $row->sku ?? '' }}</td>
                                <td>{{ $row->product ?? '' }}</td>
                                <td>{{ $row->category ?? '' }}</td>
                                <td>{{ $row->location_name ?? '' }}</td>
                                
                                <!-- Current Stock KG -->
                                <td>
                                    @if($row->enable_stock)
                                        <span class="current_stock" data-is_quantity="true" 
                                            data-orig-value="{{ (float)$current_stock_kg }}" 
                                            data-unit="{{ $row->unit ?? '' }}">
                                            {{ number_format($current_stock_kg, 2) }}
                                        </span> KG
                                    @else
                                        --
                                    @endif
                                </td>
                                
                                <!-- Price KG -->
                                <td>
                                    @if($row->enable_stock)
                                        {{ number_format($purchase_price_kg, 2) }}
                                    @else
                                        --
                                    @endif
                                </td>
                                
                                <!-- Current Stock Meter -->
                                <td>
                                    @if($row->enable_stock && $product_custom_field2_val > 0 && $current_stock_meter > 0)
                                        <span class="custom_field_3_value" 
                                            data-orig-value="{{ (float)$current_stock_meter }}" 
                                            data-unit="{{ $row->unit ?? '' }}">
                                            {{ number_format($current_stock_meter, 2) }}
                                        </span> Meter
                                    @else
                                        --
                                    @endif
                                </td>
                                
                                <!-- Price Meter -->
                                <td>
                                    @if($row->enable_stock && $product_custom_field2_val > 0 && $price_meter > 0)
                                        {{ number_format($price_meter, 2) }}
                                    @else
                                        --
                                    @endif
                                </td>
                                
                                <!-- Feet -->
                                <td>
                                    @if($row->enable_stock && $product_custom_field2_val > 0 && $feet > 0)
                                        {{ number_format($feet, 2) }}
                                    @else
                                        --
                                    @endif
                                </td>
                                
                                <!-- Yard -->
                                <td>
                                    @if($row->enable_stock && $product_custom_field2_val > 0 && $yard > 0)
                                        {{ number_format($yard, 2) }}
                                    @else
                                        --
                                    @endif
                                </td>
                                
                                <!-- Lot Number -->
                                <td>
                                    @if(!empty($lot_number))
                                        {{ $lot_number }}
                                    @else
                                        --
                                    @endif
                                </td>
                                
                                <!-- PCS (Whole pieces) -->
                                <td>
                                    @if(!empty($lot_number) && $row->enable_stock && $current_stock_pcs > 0)
                                        {{ number_format($current_stock_pcs, 0) }}
                                    @else
                                        --
                                    @endif
                                </td>
                                
                                <!-- Cut PCS (1/50M or 1/2.5K or 0) -->
                                <td>
                                    @if(!empty($lot_number) && $row->enable_stock)
                                        {{ $cut_pcs_display }}
                                    @else
                                        --
                                    @endif
                                </td>
                                
                                <!-- Custom Fields -->
                                <td>{{ $row->product_custom_field1 ?? '' }}</td>
                                <td>{{ $row->product_custom_field2 ?? 0 }}</td>
                            </tr>
                        @endforeach
                    </tbody>
                    <tfoot>
                        <tr class="bg-gray font-17 text-center footer-total">
                            <td colspan="4"><strong>@lang('sale.total'):</strong></td>
                            <td>{{ number_format($total_stock_kg, 2) }}</td>
                            <td>{{ number_format($total_price_kg, 2) }}</td>
                            <td>{{ number_format($total_stock_meter, 2) }}</td>
                            <td>{{ number_format($total_price_meter, 2) }}</td>
                            <td>{{ number_format($total_feet, 2) }}</td>
                            <td>{{ number_format($total_yard, 2) }}</td>
                            <td></td>
                            <td>{{ number_format($total_pcs, 0) }}</td>
                            <td>{{ number_format($total_cut_pcs, 0) }} ({{ number_format($total_cut_meter, 2) }}M / {{ number_format($total_cut_kg, 2) }}K)</td>
                            <td colspan="2"></td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
    </div>
</section>

@endsection

@section('javascript')
<script>
    $(document).ready(function() {
        // Initialize Select2
        $('.select2').select2();
    });
</script>
@endsection