@extends('layouts.dashboard.superadminapp')

@section('title', 'Edit Customer/Vendor')

@section('content')
    <!-- Page Heading -->
    <x-layout.page-header title="UEPL | Edit Customer/Vendor" icon="users" iconColor="primary" />

    <!-- Alerts -->
    @if(session('success'))
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle mr-2"></i>{{ session('success') }}
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    @endif
    @if(session('error'))
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-circle mr-2"></i>{{ 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">
            <ul class="mb-0">
                @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

    <!-- Edit Form Card -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">
                <i class="fas fa-edit mr-2"></i>Edit Customer/Vendor: {{ $customer->company }}
            </h6>
        </div>
        <div class="card-body">
            <form id="customerForm" action="{{ route('superadmin.customer.update', $customer->id) }}" method="POST" enctype="multipart/form-data">
                @csrf
                @method('PUT')

                <!-- Company Role Section -->
                <div class="form-group">
                    <label class="font-weight-bold">Company Role <span class="text-danger">*</span></label>
                    <div class="d-flex flex-wrap mt-2">
                        @foreach(['Customer', 'Vendor', 'Both'] as $role)
                            <div class="custom-control custom-radio mr-4">
                                <input type="radio" id="{{ strtolower($role) }}" name="company_role" value="{{ $role }}"
                                    class="custom-control-input" {{ $customer->company_role == $role ? 'checked' : '' }} required>
                                <label for="{{ strtolower($role) }}" class="custom-control-label">
                                    {{ $role == 'Both' ? 'Customer & Vendor' : $role }}
                                </label>
                            </div>
                        @endforeach
                    </div>
                    @error('company_role')
                        <span class="text-danger small">{{ $message }}</span>
                    @enderror
                </div>

                <hr>

                <!-- Company Information Section -->
                <h6 class="font-weight-bold text-primary mb-3"><i class="fas fa-building mr-2"></i>Company Information</h6>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label>Company Name <span class="text-danger">*</span></label>
                        <input type="text" name="company" class="form-control" value="{{ old('company', $customer->company) }}" required>
                        @error('company') <span class="text-danger small">{{ $message }}</span> @enderror
                    </div>
                    <div class="col-md-6 mb-3">
                        <label>Company Email <span class="text-danger">*</span></label>
                        <input type="email" name="email" class="form-control" value="{{ old('email', $customer->email) }}" required>
                        @error('email') <span class="text-danger small">{{ $message }}</span> @enderror
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label>Company Acronym</label>
                        <input type="text" name="company_nickname" class="form-control" value="{{ old('company_nickname', $customer->company_nickname) }}">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label>Company Logo</label>
                        @if($customer->image)
                            <div class="mb-2">
                                <img src="{{ asset('storage/'.$customer->image) }}" width="60" class="rounded">
                                <small class="text-muted ml-2">Current logo</small>
                            </div>
                        @endif
                        <div class="custom-file">
                            <input type="file" name="image" accept="image/*" class="custom-file-input" id="image">
                            <label class="custom-file-label" for="image">Choose new file...</label>
                        </div>
                        <small class="text-muted">Leave blank to keep existing</small>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-3 mb-3">
                        <label>Company Contact <span class="text-danger">*</span></label>
                        <input type="tel" name="mobile" class="form-control" value="{{ old('mobile', $customer->mobile) }}" required>
                        @error('mobile') <span class="text-danger small">{{ $message }}</span> @enderror
                    </div>
                    <div class="col-md-3 mb-3">
                        <label>Secondary Contact</label>
                        <input type="tel" name="secondary_mobile" class="form-control" value="{{ old('secondary_mobile', $customer->secondary_mobile) }}">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label>Type of Company <span class="text-danger">*</span></label>
                        <select name="company_type" class="form-control" required>
                            <option value="" disabled>Select company type</option>
                            @foreach($companyTypes as $type)
                                <option value="{{ $type->companytype }}" {{ $customer->company_type == $type->companytype ? 'selected' : '' }}>
                                    {{ $type->companytype }}
                                </option>
                            @endforeach
                        </select>
                        @error('company_type') <span class="text-danger small">{{ $message }}</span> @enderror
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label>GST <span class="text-danger">*</span></label>
                        <input type="text" name="gstno" class="form-control text-uppercase" value="{{ old('gstno', $customer->gstno) }}" required maxlength="15">
                        @error('gstno') <span class="text-danger small">{{ $message }}</span> @enderror
                    </div>
                    <div class="col-md-6 mb-3">
                        <label>Company PAN <span class="text-danger">*</span></label>
                        <input type="text" name="panno" class="form-control text-uppercase" value="{{ old('panno', $customer->panno) }}" required maxlength="10">
                        @error('panno') <span class="text-danger small">{{ $message }}</span> @enderror
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label>MSME/Udyam</label>
                        <input type="text" name="msmeno" class="form-control" value="{{ old('msmeno', $customer->msmeno) }}">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label>IEC</label>
                        <input type="text" name="iecno" class="form-control" value="{{ old('iecno', $customer->iecno) }}">
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label>Billing Address</label>
                        <textarea name="billing_address" class="form-control" rows="2">{{ old('billing_address', $customer->billing_address) }}</textarea>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label>Shipping Address</label>
                        <textarea name="shipping_address" class="form-control" rows="2">{{ old('shipping_address', $customer->shipping_address) }}</textarea>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label>Website URL</label>
                        <input type="url" name="url" class="form-control" value="{{ old('url', $customer->url) }}">
                    </div>
                </div>

                <hr>

                <!-- Bank Account Details Section -->
                <h6 class="font-weight-bold text-primary mb-3"><i class="fas fa-university mr-2"></i>Bank Account Details <small class="text-muted">(Optional)</small></h6>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label>Bank Name</label>
                        <input type="text" name="bank_name" class="form-control" value="{{ old('bank_name', $customer->bank_name) }}">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label>Bank Branch Name</label>
                        <input type="text" name="branch_name" class="form-control" value="{{ old('branch_name', $customer->branch_name) }}">
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label>Account Number</label>
                        <input type="text" name="account_number" class="form-control" value="{{ old('account_number', $customer->account_number) }}">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label>Account Type</label>
                        <select name="account_type" class="form-control">
                            <option value="">Select account type</option>
                            @foreach($accountTypes as $type)
                                <option value="{{ $type->accounttype }}" {{ $customer->account_type == $type->accounttype ? 'selected' : '' }}>
                                    {{ $type->accounttype }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label>Account Holder Name</label>
                        <input type="text" name="account_holder_name" class="form-control" value="{{ old('account_holder_name', $customer->account_holder_name) }}">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label>Account Currency</label>
                        <input type="text" name="account_currency" class="form-control" value="{{ old('account_currency', $customer->account_currency ?? 'INR') }}">
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label>IFSC Code</label>
                        <input type="text" name="ifsc_code" class="form-control text-uppercase" value="{{ old('ifsc_code', $customer->ifsc_code) }}" maxlength="11">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label>SWIFT/BIC Code</label>
                        <input type="text" name="swift_code" class="form-control text-uppercase" value="{{ old('swift_code', $customer->swift_code) }}">
                    </div>
                </div>

                <hr>

                <!-- Contact Persons Section -->
                <h6 class="font-weight-bold text-primary mb-3"><i class="fas fa-users mr-2"></i>Contact Persons <small class="text-muted">(Optional)</small></h6>

                <div id="contact-person-container">
                    @forelse ($customer->contactPersons as $i => $person)
                        <div class="contact-person card mb-3" data-index="{{ $i }}">
                            <div class="card-body py-3">
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <span class="badge badge-primary">Contact #{{ $i + 1 }}</span>
                                    @if($i > 0 || $customer->contactPersons->count() > 1)
                                        <button type="button" class="btn btn-danger btn-sm remove-contact">
                                            <i class="fas fa-times"></i> Remove
                                        </button>
                                    @else
                                        <button type="button" class="btn btn-danger btn-sm remove-contact d-none">
                                            <i class="fas fa-times"></i> Remove
                                        </button>
                                    @endif
                                </div>
                                <div class="row">
                                    <div class="col-md-6 mb-2">
                                        <label class="small">Name</label>
                                        <input type="text" name="contacts[{{ $i }}][name]" class="form-control form-control-sm" value="{{ old("contacts.$i.name", $person->name) }}" placeholder="Name">
                                    </div>
                                    <div class="col-md-6 mb-2">
                                        <label class="small">Email</label>
                                        <input type="email" name="contacts[{{ $i }}][email]" class="form-control form-control-sm" value="{{ old("contacts.$i.email", $person->email) }}" placeholder="Email">
                                    </div>
                                    <div class="col-md-6 mb-2">
                                        <label class="small">Mobile</label>
                                        <input type="text" name="contacts[{{ $i }}][mobile]" class="form-control form-control-sm" value="{{ old("contacts.$i.mobile", $person->mobile) }}" placeholder="Mobile">
                                    </div>
                                    <div class="col-md-6 mb-2">
                                        <label class="small">Designation</label>
                                        <input type="text" name="contacts[{{ $i }}][designation]" class="form-control form-control-sm" value="{{ old("contacts.$i.designation", $person->designation) }}" placeholder="Designation">
                                    </div>
                                </div>
                            </div>
                        </div>
                    @empty
                        <div class="contact-person card mb-3" data-index="0">
                            <div class="card-body py-3">
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <span class="badge badge-primary">Contact #1</span>
                                    <button type="button" class="btn btn-danger btn-sm remove-contact d-none">
                                        <i class="fas fa-times"></i> Remove
                                    </button>
                                </div>
                                <div class="row">
                                    <div class="col-md-6 mb-2">
                                        <label class="small">Name</label>
                                        <input type="text" name="contacts[0][name]" class="form-control form-control-sm" placeholder="Name">
                                    </div>
                                    <div class="col-md-6 mb-2">
                                        <label class="small">Email</label>
                                        <input type="email" name="contacts[0][email]" class="form-control form-control-sm" placeholder="Email">
                                    </div>
                                    <div class="col-md-6 mb-2">
                                        <label class="small">Mobile</label>
                                        <input type="text" name="contacts[0][mobile]" class="form-control form-control-sm" placeholder="Mobile">
                                    </div>
                                    <div class="col-md-6 mb-2">
                                        <label class="small">Designation</label>
                                        <input type="text" name="contacts[0][designation]" class="form-control form-control-sm" placeholder="Designation">
                                    </div>
                                </div>
                            </div>
                        </div>
                    @endforelse
                </div>

                <button type="button" class="btn btn-outline-primary btn-sm mb-4" id="add-contact">
                    <i class="fas fa-plus mr-1"></i> Add Another Contact
                </button>

                <hr>

                <!-- Submit Buttons -->
                <div class="d-flex">
                    <button class="btn btn-success mr-2" type="submit" id="submitBtn">
                        <span class="spinner-border spinner-border-sm d-none" role="status" id="submitSpinner"></span>
                        <i class="fas fa-save mr-1" id="submitIcon"></i>
                        <span id="submitText">Update</span>
                    </button>
                    <a href="{{ route('superadmin.customer.customerlist') }}" class="btn btn-secondary">
                        <i class="fas fa-arrow-left mr-1"></i> Back to List
                    </a>
                </div>
            </form>
        </div>
    </div>
@endsection

@section('scripts')
<script>
$(document).ready(function() {
    // Custom file input label update
    $('.custom-file-input').on('change', function() {
        var fileName = $(this).val().split('\\').pop();
        $(this).next('.custom-file-label').html(fileName || 'Choose new file...');
    });

    // Auto uppercase for GST, PAN, IFSC
    $('input[name="gstno"], input[name="panno"], input[name="ifsc_code"], input[name="swift_code"]').on('input', function() {
        $(this).val($(this).val().toUpperCase());
    });

    // Form submit loading state
    $('#customerForm').on('submit', function() {
        $('#submitBtn').prop('disabled', true);
        $('#submitSpinner').removeClass('d-none');
        $('#submitIcon').addClass('d-none');
        $('#submitText').text('Updating...');
    });

    // Contact Person Management
    var contactIndex = {{ $customer->contactPersons->count() ?: 1 }};

    function createContactHTML(idx) {
        return `
            <div class="contact-person card mb-3" data-index="${idx}">
                <div class="card-body py-3">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span class="badge badge-primary">Contact #${idx + 1}</span>
                        <button type="button" class="btn btn-danger btn-sm remove-contact">
                            <i class="fas fa-times"></i> Remove
                        </button>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-2">
                            <label class="small">Name</label>
                            <input type="text" name="contacts[${idx}][name]" class="form-control form-control-sm" placeholder="Name">
                        </div>
                        <div class="col-md-6 mb-2">
                            <label class="small">Email</label>
                            <input type="email" name="contacts[${idx}][email]" class="form-control form-control-sm" placeholder="Email">
                        </div>
                        <div class="col-md-6 mb-2">
                            <label class="small">Mobile</label>
                            <input type="text" name="contacts[${idx}][mobile]" class="form-control form-control-sm" placeholder="Mobile">
                        </div>
                        <div class="col-md-6 mb-2">
                            <label class="small">Designation</label>
                            <input type="text" name="contacts[${idx}][designation]" class="form-control form-control-sm" placeholder="Designation">
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    // Add contact
    $('#add-contact').on('click', function() {
        $('#contact-person-container').append(createContactHTML(contactIndex));
        contactIndex++;
        updateRemoveButtons();
    });

    // Remove contact
    $('#contact-person-container').on('click', '.remove-contact', function() {
        $(this).closest('.contact-person').remove();
        reindexContacts();
    });

    // Reindex contacts
    function reindexContacts() {
        $('#contact-person-container .contact-person').each(function(idx) {
            $(this).attr('data-index', idx);
            $(this).find('.badge').text('Contact #' + (idx + 1));
            $(this).find('input').each(function() {
                var name = $(this).attr('name');
                $(this).attr('name', name.replace(/contacts\[\d+\]/, 'contacts[' + idx + ']'));
            });
        });
        contactIndex = $('#contact-person-container .contact-person').length;
        updateRemoveButtons();
    }

    // Show/hide remove buttons
    function updateRemoveButtons() {
        var contacts = $('#contact-person-container .contact-person');
        contacts.each(function(i) {
            var removeBtn = $(this).find('.remove-contact');
            if (contacts.length > 1) {
                removeBtn.removeClass('d-none');
            } else {
                removeBtn.addClass('d-none');
            }
        });
    }

    // Initial setup
    updateRemoveButtons();
});
</script>
@endsection
