@extends('layouts.app')

@section('title', \App\Helpers\TranslationHelper::transFromDatabase('Customers.CreateTitle', __('Add New Customer')))

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.CreateTitle', __('Add New Customer')) }}</h3>
                    <div class="card-tools">
                        <a href="{{ route('customers.index') }}" class="btn btn-default btn-sm">
                            <i class="fas fa-arrow-right"></i> {{ \App\Helpers\TranslationHelper::transFromDatabase('General.BackToList', __('Back to List')) }}
                        </a>
                    </div>
                </div>
                <div class="card-body">
                    @if($errors->any())
                    <div class="alert alert-danger">
                        <ul class="mb-0">
                            @foreach($errors->all() as $error)
                            <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                    @endif

                    @if(!$parentAccount)
                    <div class="alert alert-warning">
                        <i class="fas fa-exclamation-triangle"></i> 
                        {{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.MissingParentAccount', __('Main Customer Account (10204) is missing. Please create account 10204 - Customers (Debtors) in the Chart of Accounts before saving any customer.')) }}
                    </div>
                    @endif

                    <form action="{{ route('customers.store') }}" method="POST">
                        @csrf
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="name">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Name', __('Customer Name')) }} <span class="text-danger">*</span></label>
                                    <input type="text" name="name" id="name" class="form-control @error('name') is-invalid @enderror" value="{{ old('name') }}" required>
                                    @error('name')
                                    <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="contact_person">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.ContactPerson', __('Contact Person')) }}</label>
                                    <input type="text" name="contact_person" id="contact_person" class="form-control @error('contact_person') is-invalid @enderror" value="{{ old('contact_person') }}">
                                    @error('contact_person')
                                    <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="email">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Email', __('Email')) }}</label>
                                    <input type="email" name="email" id="email" class="form-control @error('email') is-invalid @enderror" value="{{ old('email') }}">
                                    @error('email')
                                    <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="phone">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Phone', __('Phone')) }}</label>
                                    <input type="text" name="phone" id="phone" class="form-control @error('phone') is-invalid @enderror" value="{{ old('phone') }}">
                                    @error('phone')
                                    <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="mobile">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Mobile', __('Mobile')) }}</label>
                                    <input type="text" name="mobile" id="mobile" class="form-control @error('mobile') is-invalid @enderror" value="{{ old('mobile') }}">
                                    @error('mobile')
                                    <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label for="address">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Address', __('Address')) }}</label>
                                    <input type="text" name="address" id="address" class="form-control @error('address') is-invalid @enderror" value="{{ old('address') }}">
                                    @error('address')
                                    <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="country">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Country', __('Country')) }}</label>
                                    <select name="country_id" id="country_id" class="form-control @error('country') is-invalid @enderror">
                                        <option value="">{{ \App\Helpers\TranslationHelper::transFromDatabase('General.SelectCountry', __('Select Country')) }}</option>
                                        @foreach($countries as $country)
                                            <option value="{{ $country->id }}" {{ old('country_id') == $country->id ? 'selected' : '' }}>{{ $country->name }}</option>
                                        @endforeach
                                    </select>
                                    <input type="hidden" name="country" id="country_name" value="{{ old('country') }}">
                                    @error('country')
                                    <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="city">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.City', __('City')) }}</label>
                                    <select name="city_id" id="city_id" class="form-control @error('city') is-invalid @enderror">
                                        <option value="">{{ \App\Helpers\TranslationHelper::transFromDatabase('General.SelectCity', __('Select City')) }}</option>
                                    </select>
                                    <input type="hidden" name="city" id="city_name" value="{{ old('city') }}">
                                    @error('city')
                                    <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="state">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.State', __('Region/State')) }}</label>
                                    <select name="state_id" id="state_id" class="form-control @error('state') is-invalid @enderror">
                                        <option value="">{{ \App\Helpers\TranslationHelper::transFromDatabase('General.SelectRegion', __('Select Region')) }}</option>
                                    </select>
                                    <input type="hidden" name="state" id="state_name" value="{{ old('state') }}">
                                    @error('state')
                                    <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="postal_code">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.PostalCode', __('Postal Code')) }}</label>
                                    <input type="text" name="postal_code" id="postal_code" class="form-control @error('postal_code') is-invalid @enderror" value="{{ old('postal_code') }}">
                                    @error('postal_code')
                                    <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="tax_number">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.TaxNumber', __('Tax Number')) }}</label>
                                    <input type="text" name="tax_number" id="tax_number" class="form-control @error('tax_number') is-invalid @enderror" value="{{ old('tax_number') }}">
                                    @error('tax_number')
                                    <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="commercial_register">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.CommercialRegister', __('Commercial Register')) }}</label>
                                    <input type="text" name="commercial_register" id="commercial_register" class="form-control @error('commercial_register') is-invalid @enderror" value="{{ old('commercial_register') }}">
                                    @error('commercial_register')
                                    <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="website">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Website', __('Website')) }}</label>
                                    <input type="url" name="website" id="website" class="form-control @error('website') is-invalid @enderror" value="{{ old('website') }}">
                                    @error('website')
                                    <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="customer_type">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Type', __('Customer Type')) }} <span class="text-danger">*</span></label>
                                    <select name="customer_type" id="customer_type" class="form-control @error('customer_type') is-invalid @enderror" required>
                                        <option value="company" {{ old('customer_type') == 'company' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Company', __('Company')) }}</option>
                                        <option value="individual" {{ old('customer_type') == 'individual' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Individual', __('Individual')) }}</option>
                                    </select>
                                    @error('customer_type')
                                    <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="category">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Category', __('Customer Category')) }}</label>
                                    <select name="category" id="category" class="form-control @error('category') is-invalid @enderror">
                                        <option value="">{{ \App\Helpers\TranslationHelper::transFromDatabase('General.SelectCategory', __('Select Category')) }}</option>
                                        <option value="retail" {{ old('category') == 'retail' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Category.Retail', __('Retail')) }}</option>
                                        <option value="semi_wholesale" {{ old('category') == 'semi_wholesale' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Category.SemiWholesale', __('Semi-wholesale')) }}</option>
                                        <option value="wholesale" {{ old('category') == 'wholesale' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Category.Wholesale', __('Wholesale')) }}</option>
                                        <option value="key_accounts" {{ old('category') == 'key_accounts' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Category.KeyAccounts', __('Key Accounts')) }}</option>
                                        <option value="online" {{ old('category') == 'online' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Category.Online', __('Online Customer')) }}</option>
                                        <option value="distributor" {{ old('category') == 'distributor' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Category.Distributor', __('Distributor')) }}</option>
                                        <option value="special" {{ old('category') == 'special' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Category.Special', __('Special')) }}</option>
                                    </select>
                                    @error('category')
                                    <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="status">{{ \App\Helpers\TranslationHelper::transFromDatabase('General.Status', __('Status')) }} <span class="text-danger">*</span></label>
                                    <select name="status" id="status" class="form-control @error('status') is-invalid @enderror" required>
                                        <option value="active" {{ old('status') == 'active' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Status.Active', __('Active')) }}</option>
                                        <option value="inactive" {{ old('status') == 'inactive' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Status.Inactive', __('Inactive')) }}</option>
                                    </select>
                                    @error('status')
                                    <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label for="credit_limit">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.CreditLimit', __('Credit Limit')) }}</label>
                                    <input type="number" name="credit_limit" id="credit_limit" class="form-control @error('credit_limit') is-invalid @enderror" value="{{ old('credit_limit', 0) }}" min="0" step="0.01">
                                    @error('credit_limit')
                                    <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label for="chart_of_account_id">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.ChartOfAccountId', __('Link to Account in Chart of Accounts')) }}</label>
                                    <select name="chart_of_account_id" id="chart_of_account_id" class="form-control @error('chart_of_account_id') is-invalid @enderror select2">
                                        <option value="">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.SelectOrLeaveBlankToCreateNew', __('Select or leave blank to create a new account')) }}</option>
                                        @foreach($customerAccounts as $account)
                                            <option value="{{ $account->id }}" {{ old('chart_of_account_id') == $account->id ? 'selected' : '' }}>{{ $account->code }} - {{ $account->name }}</option>
                                        @endforeach
                                    </select>
                                    @error('chart_of_account_id')
                                    <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label for="linked_supplier_id">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.LinkedSupplier', __('Linked Supplier (if this customer is also a supplier)')) }}</label>
                                    <select name="linked_supplier_id" id="linked_supplier_id" class="form-control @error('linked_supplier_id') is-invalid @enderror select2">
                                        <option value="">{{ \App\Helpers\TranslationHelper::transFromDatabase('General.SelectSupplier', __('Select Supplier')) }}</option>
                                        @foreach($suppliers as $supplier)
                                            <option value="{{ $supplier->id }}" {{ old('linked_supplier_id') == $supplier->id ? 'selected' : '' }}>{{ $supplier->name }}</option>
                                        @endforeach
                                    </select>
                                    @error('linked_supplier_id')
                                    <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label for="notes">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customers.Notes', __('Notes')) }}</label>
                                    <textarea name="notes" id="notes" class="form-control @error('notes') is-invalid @enderror" rows="3">{{ old('notes') }}</textarea>
                                    @error('notes')
                                    <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="row mt-3">
                            <div class="col-md-12">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save"></i> {{ \App\Helpers\TranslationHelper::transFromDatabase('General.Save', __('Save')) }}
                                </button>
                                <a href="{{ route('customers.index') }}" class="btn btn-secondary">
                                    <i class="fas fa-times"></i> {{ \App\Helpers\TranslationHelper::transFromDatabase('General.Cancel', __('Cancel')) }}
                                </a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
$(document).ready(function() {
    var initialCountryId = '{{ old("country_id") }}';
    var initialCityId = '{{ old("city_id") }}';
    var initialStateId = '{{ old("state_id") }}';

    function loadCities(countryId, selectedCityId = null) {
        if (!countryId) return;
        
        return $.ajax({
            url: '/api/countries/' + countryId + '/cities',
            type: 'GET',
            success: function(data) {
                $('#city_id').empty().append('<option value="">{{ \App\Helpers\TranslationHelper::transFromDatabase("General.SelectCity", __("Select City")) }}</option>');
                $.each(data, function(key, city) {
                    var selected = (selectedCityId == city.id) ? 'selected' : '';
                    $('#city_id').append('<option value="' + city.id + '" ' + selected + '>' + city.name + '</option>');
                });
                if (selectedCityId) {
                    loadRegions(selectedCityId, initialStateId);
                }
            }
        });
    }

    function loadRegions(cityId, selectedStateId = null) {
        if (!cityId) return;

        return $.ajax({
            url: '/api/cities/' + cityId + '/regions',
            type: 'GET',
            success: function(data) {
                $('#state_id').empty().append('<option value="">{{ \App\Helpers\TranslationHelper::transFromDatabase("General.SelectRegion", __("Select Region")) }}</option>');
                $.each(data, function(key, region) {
                    var selected = (selectedStateId == region.id) ? 'selected' : '';
                    $('#state_id').append('<option value="' + region.id + '" ' + selected + '>' + region.name + '</option>');
                });
            }
        });
    }

    if (initialCountryId) {
        loadCities(initialCountryId, initialCityId);
    }

    $('#country_id').change(function() {
        var countryId = $(this).val();
        var countryName = $(this).find('option:selected').text();
        $('#country_name').val(countryId ? countryName : '');
        
        $('#city_id').empty().append('<option value="">{{ \App\Helpers\TranslationHelper::transFromDatabase("General.SelectCity", __("Select City")) }}</option>');
        $('#state_id').empty().append('<option value="">{{ \App\Helpers\TranslationHelper::transFromDatabase("General.SelectRegion", __("Select Region")) }}</option>');
        $('#city_name').val('');
        $('#state_name').val('');

        if (countryId) {
            loadCities(countryId);
        }
    });

    $('#city_id').change(function() {
        var cityId = $(this).val();
        var cityName = $(this).find('option:selected').text();
        $('#city_name').val(cityId ? cityName : '');

        $('#state_id').empty().append('<option value="">{{ \App\Helpers\TranslationHelper::transFromDatabase("General.SelectRegion", __("Select Region")) }}</option>');
        $('#state_name').val('');

        if (cityId) {
            loadRegions(cityId);
        }
    });

    $('#state_id').change(function() {
        var stateId = $(this).val();
        var stateName = $(this).find('option:selected').text();
        $('#state_name').val(stateId ? stateName : '');
    });
});
</script>
@endpush
