@extends('layouts.admin-simple')

@section('title', 'Add New Fixed Asset')

@section('breadcrumb')
    <li class="breadcrumb-item">Warehouse</li>
    <li class="breadcrumb-item">Fixed Assets</li>
    <li class="breadcrumb-item"><a href="{{ route('warehouse.fixed-assets.catalog.index') }}">Catalog</a></li>
    <li class="breadcrumb-item active">Add New Asset</li>
@endsection

@section('page-title')
    <div class="d-flex justify-content-between align-items-center w-100">
        <div class="page-title-left">
            <h3 class="mb-1">Add New Fixed Asset</h3>
            <p class="text-muted mb-0" style="font-size: 13px;">Register a new fixed asset in the system</p>
        </div>
        <div class="page-actions-right d-flex align-items-center">
            <a href="{{ route('warehouse.fixed-assets.catalog.index') }}" class="btn btn-sm btn-outline-secondary">
                <i class="material-icons mr-1" style="font-size: 16px;">arrow_back</i>
                Back to Catalog
            </a>
        </div>
    </div>
@endsection

@section('content')
    @if(session('error'))
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            {{ session('error') }}
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    @endif
    @if($errors->any())
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <strong>Please fix the following:</strong>
            <ul class="mb-0 mt-2">
                @foreach($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    @endif

    <form id="assetForm" method="POST" action="{{ route('warehouse.fixed-assets.catalog.store') }}" enctype="multipart/form-data">
        @csrf

        <!-- Asset Identity -->
        <div class="card mb-3">
            <div class="card-header">
                <h6 class="card-title mb-0 d-flex align-items-center">
                    <i class="material-icons mr-2">badge</i>
                    Asset Identity
                </h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="asset_name">Asset Name <span class="text-danger">*</span></label>
                            <input type="text" name="asset_name" id="asset_name" class="form-control @error('asset_name') is-invalid @enderror"
                                   placeholder="Enter asset name" value="{{ old('asset_name') }}" required>
                            @error('asset_name')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="serial_number">Serial Number</label>
                            <input type="text" name="serial_number" id="serial_number" class="form-control @error('serial_number') is-invalid @enderror"
                                   placeholder="Enter serial number" value="{{ old('serial_number') }}">
                            @error('serial_number')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="model_number">Model Number</label>
                            <input type="text" name="model_number" id="model_number" class="form-control @error('model_number') is-invalid @enderror"
                                   placeholder="Enter model number" value="{{ old('model_number') }}">
                            @error('model_number')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="manufacturer">Manufacturer</label>
                            <input type="text" name="manufacturer" id="manufacturer" class="form-control @error('manufacturer') is-invalid @enderror"
                                   placeholder="Enter manufacturer" value="{{ old('manufacturer') }}">
                            @error('manufacturer')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group mb-0">
                            <label for="description">Description</label>
                            <textarea name="description" id="description" rows="2" class="form-control @error('description') is-invalid @enderror"
                                      placeholder="Optional description of the asset">{{ old('description') }}</textarea>
                            @error('description')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Classification -->
        <div class="card mb-3">
            <div class="card-header">
                <h6 class="card-title mb-0 d-flex align-items-center">
                    <i class="material-icons mr-2">category</i>
                    Classification
                </h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="category_id">Category <span class="text-danger">*</span></label>
                            <select name="category_id" id="category_id" class="form-control select2-dropdown @error('category_id') is-invalid @enderror" required>
                                <option value="">Select Category</option>
                                @foreach($categories ?? [] as $category)
                                    <option value="{{ $category->id }}" {{ old('category_id') == $category->id ? 'selected' : '' }}>
                                        {{ $category->category_name }}{{ $category->category_code ? ' (' . $category->category_code . ')' : '' }}
                                    </option>
                                @endforeach
                            </select>
                            @error('category_id')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="condition">Condition <span class="text-danger">*</span></label>
                            <select name="condition" id="condition" class="form-control @error('condition') is-invalid @enderror" required>
                                <option value="">Select Condition</option>
                                <option value="new" {{ old('condition') == 'new' ? 'selected' : '' }}>New</option>
                                <option value="good" {{ old('condition') == 'good' ? 'selected' : '' }}>Good</option>
                                <option value="fair" {{ old('condition') == 'fair' ? 'selected' : '' }}>Fair</option>
                                <option value="poor" {{ old('condition') == 'poor' ? 'selected' : '' }}>Poor</option>
                                <option value="damaged" {{ old('condition') == 'damaged' ? 'selected' : '' }}>Damaged</option>
                                <option value="non_functional" {{ old('condition') == 'non_functional' ? 'selected' : '' }}>Non-Functional</option>
                            </select>
                            @error('condition')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="status">Status</label>
                            <select name="status" id="status" class="form-control @error('status') is-invalid @enderror">
                                <option value="active" {{ old('status', 'active') == 'active' ? 'selected' : '' }}>Active</option>
                                <option value="inactive" {{ old('status') == 'inactive' ? 'selected' : '' }}>Inactive</option>
                            </select>
                            @error('status')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Purchase Information -->
        <div class="card mb-3">
            <div class="card-header">
                <h6 class="card-title mb-0 d-flex align-items-center">
                    <i class="material-icons mr-2">shopping_cart</i>
                    Purchase Information
                </h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="supplier_id">Supplier</label>
                            <select name="supplier_id" id="supplier_id" class="form-control select2-dropdown @error('supplier_id') is-invalid @enderror">
                                <option value="">Select Supplier</option>
                                @foreach($suppliers ?? [] as $supplier)
                                    <option value="{{ $supplier->id }}" {{ old('supplier_id') == $supplier->id ? 'selected' : '' }}>
                                        {{ $supplier->name }} {{ $supplier->supplier_code ? '(' . $supplier->supplier_code . ')' : '' }}
                                    </option>
                                @endforeach
                            </select>
                            @error('supplier_id')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="purchase_order_number">PO Number</label>
                            <input type="text" name="purchase_order_number" id="purchase_order_number" class="form-control @error('purchase_order_number') is-invalid @enderror"
                                   placeholder="Purchase order number" value="{{ old('purchase_order_number') }}">
                            @error('purchase_order_number')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="invoice_number">Invoice Number</label>
                            <input type="text" name="invoice_number" id="invoice_number" class="form-control @error('invoice_number') is-invalid @enderror"
                                   placeholder="Invoice number" value="{{ old('invoice_number') }}">
                            @error('invoice_number')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="invoice_date">Invoice Date</label>
                            <input type="date" name="invoice_date" id="invoice_date" class="form-control @error('invoice_date') is-invalid @enderror"
                                   value="{{ old('invoice_date') }}">
                            @error('invoice_date')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="purchase_date">Purchase Date <span class="text-danger">*</span></label>
                            <input type="date" name="purchase_date" id="purchase_date" class="form-control @error('purchase_date') is-invalid @enderror"
                                   value="{{ old('purchase_date', date('Y-m-d')) }}" required>
                            @error('purchase_date')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="purchase_price">Purchase Price <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <div class="input-group-prepend">
                                    <select name="currency" id="currency" class="form-control" style="border-radius: 4px 0 0 4px;">
                                        <option value="AED" {{ old('currency', 'AED') == 'AED' ? 'selected' : '' }}>AED</option>
                                        <option value="USD" {{ old('currency') == 'USD' ? 'selected' : '' }}>USD</option>
                                        <option value="EUR" {{ old('currency') == 'EUR' ? 'selected' : '' }}>EUR</option>
                                        <option value="GBP" {{ old('currency') == 'GBP' ? 'selected' : '' }}>GBP</option>
                                        <option value="SAR" {{ old('currency') == 'SAR' ? 'selected' : '' }}>SAR</option>
                                    </select>
                                </div>
                                <input type="number" name="purchase_price" id="purchase_price" class="form-control @error('purchase_price') is-invalid @enderror"
                                       placeholder="0.00" step="0.01" min="0" value="{{ old('purchase_price') }}" required>
                            </div>
                            @error('purchase_price')
                                <div class="invalid-feedback d-block">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Depreciation -->
        <div class="card mb-3">
            <div class="card-header">
                <h6 class="card-title mb-0 d-flex align-items-center">
                    <i class="material-icons mr-2">trending_down</i>
                    Depreciation
                </h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="depreciation_method">Depreciation Method <span class="text-danger">*</span></label>
                            <select name="depreciation_method" id="depreciation_method" class="form-control @error('depreciation_method') is-invalid @enderror" required>
                                <option value="straight_line" {{ old('depreciation_method', 'straight_line') == 'straight_line' ? 'selected' : '' }}>Straight Line</option>
                                <option value="declining_balance" {{ old('depreciation_method') == 'declining_balance' ? 'selected' : '' }}>Declining Balance</option>
                            </select>
                            @error('depreciation_method')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="useful_life_years">Useful Life (Years) <span class="text-danger">*</span></label>
                            <input type="number" name="useful_life_years" id="useful_life_years" class="form-control @error('useful_life_years') is-invalid @enderror"
                                   placeholder="e.g. 5" min="1" max="100" value="{{ old('useful_life_years') }}" required>
                            @error('useful_life_years')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="salvage_value">Salvage Value</label>
                            <input type="number" name="salvage_value" id="salvage_value" class="form-control @error('salvage_value') is-invalid @enderror"
                                   placeholder="0.00" step="0.01" min="0" value="{{ old('salvage_value', '0.00') }}">
                            @error('salvage_value')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12">
                        <div class="alert alert-info mb-0" id="depreciationPreview">
                            <small>
                                <strong>Preview:</strong>
                                Monthly depreciation will be calculated after entering Purchase Price, Useful Life, and Salvage Value.
                            </small>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Warranty Information -->
        <div class="card mb-3">
            <div class="card-header">
                <h6 class="card-title mb-0 d-flex align-items-center">
                    <i class="material-icons mr-2">verified_user</i>
                    Warranty Information
                </h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="warranty_start_date">Warranty Start Date</label>
                            <input type="date" name="warranty_start_date" id="warranty_start_date" class="form-control @error('warranty_start_date') is-invalid @enderror"
                                   value="{{ old('warranty_start_date') }}">
                            @error('warranty_start_date')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="warranty_end_date">Warranty End Date</label>
                            <input type="date" name="warranty_end_date" id="warranty_end_date" class="form-control @error('warranty_end_date') is-invalid @enderror"
                                   value="{{ old('warranty_end_date') }}">
                            @error('warranty_end_date')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="warranty_terms">Warranty Terms</label>
                            <input type="text" name="warranty_terms" id="warranty_terms" class="form-control @error('warranty_terms') is-invalid @enderror"
                                   placeholder="e.g. 2 years parts and labor" value="{{ old('warranty_terms') }}">
                            @error('warranty_terms')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Documents & Photo -->
        <div class="card mb-3">
            <div class="card-header">
                <h6 class="card-title mb-0 d-flex align-items-center">
                    <i class="material-icons mr-2">photo_camera</i>
                    Documents & Photo
                </h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="photo">Asset Photo</label>
                            <div class="custom-file">
                                <input type="file" name="photo" class="custom-file-input" id="photo" accept="image/*">
                                <label class="custom-file-label" for="photo">Choose photo...</label>
                            </div>
                            <small class="form-text text-muted">Accepted formats: JPG, PNG, GIF. Max size: 5MB.</small>
                        </div>
                        <div id="photoPreview" style="display: none;" class="mt-2">
                            <img id="photoPreviewImg" src="" alt="Preview" style="max-height: 150px; border-radius: 8px;">
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Notes -->
        <div class="card mb-3">
            <div class="card-header">
                <h6 class="card-title mb-0 d-flex align-items-center">
                    <i class="material-icons mr-2">notes</i>
                    Additional Notes
                </h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group mb-0">
                            <label for="notes">Notes</label>
                            <textarea name="notes" id="notes" rows="3" class="form-control @error('notes') is-invalid @enderror"
                                      placeholder="Any additional notes or remarks about this asset">{{ old('notes') }}</textarea>
                            @error('notes')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Form Actions -->
        <div class="card">
            <div class="card-body text-center py-3">
                <button type="submit" class="btn btn-success mr-3">
                    <i class="material-icons mr-1" style="font-size: 16px;">save</i>
                    Save Asset
                </button>
                <a href="{{ route('warehouse.fixed-assets.catalog.index') }}" class="btn btn-outline-secondary">
                    <i class="material-icons mr-1" style="font-size: 16px;">cancel</i>
                    Cancel
                </a>
            </div>
        </div>
    </form>
@endsection

@push('styles')
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css">
    <style>
        .form-group label { font-weight: 600; color: #495057; font-size: 14px; }
        .card-title { font-size: 16px; font-weight: 600; color: #495057; }
        .select2-container { width: 100% !important; }
        .select2-container--default .select2-selection--single {
            height: 38px; border: 1px solid #ced4da; border-radius: 0.375rem; line-height: 36px;
        }
        .select2-container--default .select2-selection--single .select2-selection__rendered {
            line-height: 36px; padding-left: 12px; color: #495057;
        }
        .select2-container--default .select2-selection--single .select2-selection__arrow { height: 36px; right: 10px; }
    </style>
@endpush

@push('scripts')
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#category_id').select2({ placeholder: 'Select Category', allowClear: true, width: '100%' });
            $('#supplier_id').select2({ placeholder: 'Select Supplier', allowClear: true, width: '100%' });

            // Photo preview
            $('#photo').on('change', function() {
                var fileName = $(this).val().split('\\').pop();
                $(this).next('.custom-file-label').html(fileName || 'Choose photo...');

                if (this.files && this.files[0]) {
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        $('#photoPreviewImg').attr('src', e.target.result);
                        $('#photoPreview').show();
                    };
                    reader.readAsDataURL(this.files[0]);
                }
            });

            // Depreciation preview calculation
            $('#purchase_price, #useful_life_years, #salvage_value, #depreciation_method').on('input change', function() {
                updateDepreciationPreview();
            });
        });

        function updateDepreciationPreview() {
            var price = parseFloat($('#purchase_price').val()) || 0;
            var lifeYears = parseInt($('#useful_life_years').val()) || 0;
            var lifeMonths = lifeYears * 12;
            var salvage = parseFloat($('#salvage_value').val()) || 0;
            var method = $('#depreciation_method').val();

            if (price > 0 && lifeMonths > 0) {
                var depreciable = price - salvage;
                var monthly = depreciable / lifeMonths;
                var annual = monthly * 12;

                $('#depreciationPreview').html(
                    '<small><strong>Preview:</strong> ' +
                    'Depreciable Amount: AED ' + depreciable.toFixed(2) +
                    ' | Monthly: AED ' + monthly.toFixed(2) +
                    ' | Annual: AED ' + annual.toFixed(2) +
                    ' (' + method.replace('_', ' ') + ')' +
                    '</small>'
                );
            } else {
                $('#depreciationPreview').html('<small><strong>Preview:</strong> Monthly depreciation will be calculated after entering Purchase Price, Useful Life, and Salvage Value.</small>');
            }
        }
    </script>
@endpush
