@extends('layouts.app')

@section('content')
<div class="card">
    <div class="card-header">
        <h5>Edit Company</h5>
    </div>

    <div class="card-body">
        <form id="editForm" enctype="multipart/form-data">
            @csrf
            @method('PUT')

            {{-- BASIC INFO --}}
            <div class="row">
                <div class="col-md-4 mb-3">
                    <label class="form-label">Company Code <span class="text-danger">*</span></label>
                    <input type="text" name="company_code"
                           value="{{ $company->company_code }}"
                           class="form-control" maxlength="50" required>
                </div>

                <div class="col-md-4 mb-3">
                    <label class="form-label">Legal Name <span class="text-danger">*</span></label>
                    <input type="text" name="legal_name"
                           value="{{ $company->legal_name }}"
                           class="form-control" maxlength="255" required>
                </div>

                <div class="col-md-4 mb-3">
                    <label class="form-label">Display Name <span class="text-danger">*</span></label>
                    <input type="text" name="display_name"
                           value="{{ $company->display_name }}"
                           class="form-control" maxlength="255" required>
                </div>
            </div>

            {{-- REGISTRATION --}}
            <div class="row">
                <div class="col-md-4 mb-3">
                    <label class="form-label">Registration Number</label>
                    <input type="text" name="registration_number"
                           value="{{ $company->registration_number }}"
                           class="form-control" maxlength="100">
                </div>

                <div class="col-md-4 mb-3">
                    <label class="form-label">Tax Number</label>
                    <input type="text" name="tax_number"
                           value="{{ $company->tax_number }}"
                           class="form-control" maxlength="100">
                </div>

                <div class="col-md-4 mb-3">
                    <label class="form-label">Industry Type</label>
                    <input type="text" name="industry_type"
                           value="{{ $company->industry_type }}"
                           class="form-control" maxlength="100">
                </div>
            </div>

            {{-- TYPE --}}
            <div class="row">
                <div class="col-md-4 mb-3">
                    <label class="form-label">Company Type</label>
                    <input type="text" name="company_type"
                           value="{{ $company->company_type }}"
                           class="form-control" maxlength="100">
                </div>
            </div>

            {{-- FINANCE --}}
            <div class="row">
                <div class="col-md-4 mb-3">
                    <label class="form-label">Base Currency</label>
                    <select name="base_currency_id" class="form-control">
                        <option value="">-- Select --</option>
                        @foreach($currencies as $currency)
                            <option value="{{ $currency->id }}"
                                {{ $company->base_currency_id == $currency->id ? 'selected' : '' }}>
                                {{ $currency->iso_code }} - {{ $currency->name }}
                            </option>
                        @endforeach
                    </select>
                </div>

                <div class="col-md-4 mb-3">
                    <label class="form-label">Fiscal Year Start</label>
                    <input type="date" name="fiscal_year_start"
                           value="{{ $company->fiscal_year_start }}"
                           class="form-control">
                </div>

                <div class="col-md-4 mb-3">
                    <label class="form-label">Time Zone</label>
                    <select name="time_zone_id" class="form-control">
                        <option value="">-- Select --</option>
                        @foreach($timeZones as $tz)
                            <option value="{{ $tz->id }}"
                                {{ $company->time_zone_id == $tz->id ? 'selected' : '' }}>
                                {{ $tz->name }} ({{ $tz->utc_offset }})
                            </option>
                        @endforeach
                    </select>
                </div>
            </div>

            {{-- ADDRESS --}}
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label">Address Line 1</label>
                    <input type="text" name="address_line1"
                           value="{{ $company->address_line1 }}"
                           class="form-control" maxlength="255">
                </div>

                <div class="col-md-6 mb-3">
                    <label class="form-label">Address Line 2</label>
                    <input type="text" name="address_line2"
                           value="{{ $company->address_line2 }}"
                           class="form-control" maxlength="255">
                </div>
            </div>

            <div class="row">
                <div class="col-md-4 mb-3">
                    <label class="form-label">City</label>
                    <select name="city_id" class="form-control">
                        <option value="">-- Select --</option>
                        @foreach($cities as $city)
                            <option value="{{ $city->id }}"
                                {{ $company->city_id == $city->id ? 'selected' : '' }}>
                                {{ $city->name }}
                            </option>
                        @endforeach
                    </select>
                </div>

                <div class="col-md-4 mb-3">
                    <label class="form-label">Postal Code</label>
                    <input type="text" name="postal_code"
                           value="{{ $company->postal_code }}"
                           class="form-control" maxlength="20">
                </div>
            </div>

            {{-- LOGO --}}
            <div class="row mb-3">
                <div class="col-md-6">
                    <label class="form-label">Company Logo</label>
                    <input type="file" name="logo" class="form-control" accept="image/*" id="logoInput">
                    <small class="text-muted">Max 2MB. JPEG, PNG, JPG, GIF or SVG.</small>
                </div>
                <div class="col-md-3">
                    @if($company->logo)
                        <label class="form-label">Current Logo</label><br>
                        <img id="logoPreview" src="{{ asset($company->logo) }}"
                             style="max-height:80px; max-width:200px; border:1px solid #dee2e6; padding:4px; border-radius:4px;">
                    @else
                        <img id="logoPreview" src="" style="max-height:80px; max-width:200px; display:none; border:1px solid #dee2e6; padding:4px; border-radius:4px;">
                    @endif
                </div>
            </div>

            {{-- STATUS --}}
            <div class="form-check mb-3">
                <input type="checkbox" name="status"
                       class="form-check-input"
                       {{ $company->status ? 'checked' : '' }}>
                <label class="form-check-label">Active</label>
            </div>

            {{-- ACTIONS --}}
            <button type="submit" class="btn btn-primary">Update</button>
            <a href="{{ route('settings.companies.index') }}" class="btn btn-secondary">Back</a>
        </form>
    </div>
</div>
@endsection

@section('scripts')
<script>
// Postal code validation - only allow alphanumeric, spaces, and hyphens
$('input[name="postal_code"]').on('input', function() {
    this.value = this.value.replace(/[^A-Z0-9\s\-]/gi, '');
});

// Logo preview
$('#logoInput').on('change', function () {
    const file = this.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = e => { $('#logoPreview').attr('src', e.target.result).show(); };
        reader.readAsDataURL(file);
    }
});

$('#editForm').on('submit', function (e) {
    e.preventDefault();

    let btn = $(this).find('button[type=submit]');
    btn.prop('disabled', true);

    const formData = new FormData(this);

    $.ajax({
        url: "{{ route('settings.companies.update', $company->id) }}",
        type: "POST",
        data: formData,
        processData: false,
        contentType: false,
        success: function (res) {
            Swal.fire('Success', res.message, 'success')
                .then(() => window.location.href = "{{ route('settings.companies.index') }}");
        },
        error: function (xhr) {
            btn.prop('disabled', false);

            if (xhr.status === 422) {
                let errors = xhr.responseJSON.errors;
                let errorList = '<ul style="text-align: left;">';

                $.each(errors, function(field, messages) {
                    $.each(messages, function(index, message) {
                        errorList += '<li>' + message + '</li>';
                    });
                });

                errorList += '</ul>';

                Swal.fire({
                    title: 'Validation Error',
                    html: errorList,
                    icon: 'error'
                });
            } else {
                Swal.fire('Error', 'An error occurred. Please try again.', 'error');
            }
        }
    });
});
</script>
@endsection
