@extends('layouts.dashboard.superadminapp')

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

@section('styles')
<style>
    /* Compact Form Styling */
    .compact-form .form-group { margin-bottom: 0.75rem; }
    .compact-form label { font-size: 0.8rem; margin-bottom: 0.25rem; font-weight: 500; color: #4a5568; }
    .compact-form .form-control { padding: 0.5rem 0.75rem; font-size: 0.875rem; }
    .compact-form .form-control-sm { padding: 0.375rem 0.625rem; font-size: 0.8125rem; }
    .compact-form textarea.form-control { min-height: 60px; }

    /* Section Headers */
    .section-header {
        background: linear-gradient(135deg, #f8fafc 0%, #edf2f7 100%);
        padding: 0.75rem 1rem;
        margin: 0 -1.25rem 1rem -1.25rem;
        border-bottom: 2px solid #e2e8f0;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }
    .section-header h6 {
        margin: 0;
        font-size: 0.875rem;
        font-weight: 600;
        color: #2d3748;
    }
    .section-header i { color: #4299e1; font-size: 1rem; }
    .section-header .badge { font-size: 0.7rem; padding: 0.25rem 0.5rem; }

    /* Compact Card */
    .compact-card { border-radius: 0.75rem; }
    .compact-card .card-header {
        padding: 0.875rem 1.25rem;
        background: linear-gradient(135deg, #667eea 0%, #4f46e5 100%);
        border-radius: 0.75rem 0.75rem 0 0;
    }
    .compact-card .card-header h6 { color: #fff; margin: 0; font-size: 0.95rem; }
    .compact-card .card-header i { color: rgba(255,255,255,0.9); }
    .compact-card .card-body { padding: 1.25rem; }

    /* Radio Buttons Inline */
    .role-selector {
        display: flex;
        gap: 0.5rem;
        flex-wrap: wrap;
    }
    .role-selector .custom-control {
        padding: 0.5rem 1rem 0.5rem 2rem;
        background: #f7fafc;
        border: 2px solid #e2e8f0;
        border-radius: 0.5rem;
        margin: 0;
        transition: all 0.2s;
        cursor: pointer;
    }
    .role-selector .custom-control:hover { border-color: #4299e1; background: #ebf8ff; }
    .role-selector .custom-control-input:checked ~ .custom-control-label::before { display: none; }
    .role-selector .custom-control-input:checked + .custom-control-label { color: #2b6cb0; }
    .role-selector .custom-control:has(.custom-control-input:checked) {
        border-color: #4299e1;
        background: #ebf8ff;
        box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.15);
    }

    /* Contact Person Card */
    .contact-card {
        background: #f7fafc;
        border: 1px solid #e2e8f0;
        border-radius: 0.5rem;
        padding: 0.875rem;
        margin-bottom: 0.75rem;
    }
    .contact-card .contact-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 0.625rem;
        padding-bottom: 0.5rem;
        border-bottom: 1px dashed #cbd5e0;
    }
    .contact-card .badge { font-size: 0.7rem; }

    /* Compact Alert */
    .alert-compact { padding: 0.625rem 1rem; font-size: 0.875rem; margin-bottom: 1rem; }
    .alert-compact ul { margin-bottom: 0; padding-left: 1.25rem; }

    /* Submit Section */
    .submit-section {
        background: #f7fafc;
        margin: 0 -1.25rem -1.25rem -1.25rem;
        padding: 1rem 1.25rem;
        border-top: 1px solid #e2e8f0;
        border-radius: 0 0 0.75rem 0.75rem;
    }

    /* Custom File Input */
    .custom-file-sm .custom-file-label {
        padding: 0.375rem 0.625rem;
        font-size: 0.8125rem;
        height: calc(1.5em + 0.75rem + 2px);
    }
    .custom-file-sm .custom-file-label::after {
        padding: 0.375rem 0.625rem;
        height: calc(1.5em + 0.75rem);
    }

    /* Required Asterisk */
    .req::after { content: " *"; color: #e53e3e; }
</style>
@endsection

@section('content')
    <!-- Page Header Component -->
    <x-layout.page-header title="UEPL | Customer/Vendor Registration" icon="user-plus" iconColor="primary" />

    <!-- Alerts -->
    @if (session('success'))
        <div class="alert alert-success alert-compact alert-dismissible fade show">
            <i class="fas fa-check-circle mr-2"></i>{{ session('success') }}
            <button type="button" class="close" data-dismiss="alert"><span>&times;</span></button>
        </div>
    @endif
    @if (session('error'))
        <div class="alert alert-danger alert-compact alert-dismissible fade show">
            <i class="fas fa-exclamation-circle mr-2"></i>{{ session('error') }}
            <button type="button" class="close" data-dismiss="alert"><span>&times;</span></button>
        </div>
    @endif
    @if ($errors->any())
        <div class="alert alert-danger alert-compact alert-dismissible fade show">
            <ul class="mb-0">@foreach ($errors->all() as $error)<li>{{ $error }}</li>@endforeach</ul>
            <button type="button" class="close" data-dismiss="alert"><span>&times;</span></button>
        </div>
    @endif

    <!-- Main Form Card -->
    <div class="card compact-card shadow-sm">
        <div class="card-header">
            <h6><i class="fas fa-building mr-2"></i>New Customer/Vendor Registration</h6>
        </div>
        <div class="card-body compact-form">
            <form id="customerForm" action="{{ route('superadmin.customer.vendor.store') }}" method="POST" enctype="multipart/form-data">
                @csrf

                <!-- Company Role Section -->
                <div class="form-group mb-3">
                    <label class="req">Company Role</label>
                    <div class="role-selector mt-1">
                        <div class="custom-control custom-radio">
                            <input type="radio" id="customer" name="company_role" value="Customer" class="custom-control-input" {{ old('company_role') == 'Customer' ? 'checked' : '' }} required>
                            <label for="customer" class="custom-control-label"><i class="fas fa-user-tie mr-1"></i>Customer</label>
                        </div>
                        <div class="custom-control custom-radio">
                            <input type="radio" id="vendor" name="company_role" value="Vendor" class="custom-control-input" {{ old('company_role') == 'Vendor' ? 'checked' : '' }} required>
                            <label for="vendor" class="custom-control-label"><i class="fas fa-truck mr-1"></i>Vendor</label>
                        </div>
                        <div class="custom-control custom-radio">
                            <input type="radio" id="bothCV" name="company_role" value="Both" class="custom-control-input" {{ old('company_role') == 'Both' ? 'checked' : '' }} required>
                            <label for="bothCV" class="custom-control-label"><i class="fas fa-exchange-alt mr-1"></i>Both</label>
                        </div>
                    </div>
                    @error('company_role')<span class="text-danger small">{{ $message }}</span>@enderror
                    <span class="text-danger small d-none" id="companyRoleError">Please select a company role.</span>
                </div>

                <!-- Company Information Section -->
                <div class="section-header">
                    <i class="fas fa-building"></i>
                    <h6>Company Information</h6>
                </div>

                <div class="row">
                    <div class="col-md-4 col-sm-6 form-group">
                        <label for="company" class="req">Company Name</label>
                        <input type="text" id="company" name="company" class="form-control form-control-sm" placeholder="Enter company name" value="{{ old('company') }}" required>
                        @error('company')<span class="text-danger small">{{ $message }}</span>@enderror
                        <span class="text-danger small d-none" id="companyError">Company Name is required.</span>
                    </div>
                    <div class="col-md-4 col-sm-6 form-group">
                        <label for="email" class="req">Company Email</label>
                        <input type="email" id="email" name="email" class="form-control form-control-sm" placeholder="email@company.com" value="{{ old('email') }}" required>
                        @error('email')<span class="text-danger small">{{ $message }}</span>@enderror
                        <span class="text-danger small d-none" id="emailError">Valid Email is required.</span>
                    </div>
                    <div class="col-md-4 col-sm-6 form-group">
                        <label for="company_type" class="req">Company Type</label>
                        <select id="company_type" name="company_type" class="form-control form-control-sm" required>
                            <option value="" disabled {{ old('company_type') ? '' : 'selected' }}>Select type</option>
                            @foreach($companyTypes as $type)
                                <option value="{{ $type->companytype }}" {{ old('company_type') == $type->companytype ? 'selected' : '' }}>{{ $type->companytype }}</option>
                            @endforeach
                        </select>
                        @error('company_type')<span class="text-danger small">{{ $message }}</span>@enderror
                        <span class="text-danger small d-none" id="companyTypeError">Please select a company type.</span>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-3 col-sm-6 form-group">
                        <label for="company_nickname">Acronym</label>
                        <input type="text" id="company_nickname" name="company_nickname" class="form-control form-control-sm" placeholder="e.g. ABC" value="{{ old('company_nickname') }}">
                    </div>
                    <div class="col-md-3 col-sm-6 form-group">
                        <label for="mobile" class="req">Contact No.</label>
                        <input type="tel" id="mobile" name="mobile" class="form-control form-control-sm" placeholder="Primary contact" value="{{ old('mobile') }}" required>
                        @error('mobile')<span class="text-danger small">{{ $message }}</span>@enderror
                        <span class="text-danger small d-none" id="mobileError">Contact number is required.</span>
                    </div>
                    <div class="col-md-3 col-sm-6 form-group">
                        <label for="secondary_mobile">Secondary No.</label>
                        <input type="tel" id="secondary_mobile" name="secondary_mobile" class="form-control form-control-sm" placeholder="Optional" value="{{ old('secondary_mobile') }}">
                    </div>
                    <div class="col-md-3 col-sm-6 form-group">
                        <label for="image">Logo</label>
                        <div class="custom-file custom-file-sm">
                            <input type="file" id="image" name="image" accept="image/*" class="custom-file-input">
                            <label class="custom-file-label" for="image">Choose file...</label>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-3 col-sm-6 form-group">
                        <label for="gstno" class="req">GST No.</label>
                        <input type="text" id="gstno" name="gstno" class="form-control form-control-sm text-uppercase" placeholder="22AAAAA0000A1Z5" value="{{ old('gstno') }}" required maxlength="15">
                        @error('gstno')<span class="text-danger small">{{ $message }}</span>@enderror
                        <span class="text-danger small d-none" id="gstError">Valid GST required.</span>
                    </div>
                    <div class="col-md-3 col-sm-6 form-group">
                        <label for="panno" class="req">PAN No.</label>
                        <input type="text" id="panno" name="panno" class="form-control form-control-sm text-uppercase" placeholder="ABCDE1234F" value="{{ old('panno') }}" required maxlength="10">
                        @error('panno')<span class="text-danger small">{{ $message }}</span>@enderror
                        <span class="text-danger small d-none" id="panError">Valid PAN required.</span>
                    </div>
                    <div class="col-md-3 col-sm-6 form-group">
                        <label for="msmeno">MSME/Udyam</label>
                        <input type="text" id="msmeno" name="msmeno" class="form-control form-control-sm" placeholder="Optional" value="{{ old('msmeno') }}">
                    </div>
                    <div class="col-md-3 col-sm-6 form-group">
                        <label for="iecno">IEC No.</label>
                        <input type="text" id="iecno" name="iecno" class="form-control form-control-sm" placeholder="Optional" value="{{ old('iecno') }}">
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6 form-group">
                        <label for="billing_address">Billing Address</label>
                        <textarea id="billing_address" name="billing_address" class="form-control form-control-sm" rows="2" placeholder="Full billing address">{{ old('billing_address') }}</textarea>
                    </div>
                    <div class="col-md-6 form-group">
                        <label for="shipping_address">Shipping Address</label>
                        <textarea id="shipping_address" name="shipping_address" class="form-control form-control-sm" rows="2" placeholder="Full shipping address">{{ old('shipping_address') }}</textarea>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6 form-group">
                        <label for="url">Website</label>
                        <input type="url" id="url" name="url" class="form-control form-control-sm" placeholder="https://www.example.com" value="{{ old('url') }}">
                    </div>
                </div>

                <!-- Bank Details Section -->
                <div class="section-header">
                    <i class="fas fa-university"></i>
                    <h6>Bank Account Details</h6>
                    <span class="badge badge-secondary">Optional</span>
                </div>

                <div class="row">
                    <div class="col-md-3 col-sm-6 form-group">
                        <label for="bank_name">Bank Name</label>
                        <input type="text" id="bank_name" name="bank_name" class="form-control form-control-sm" placeholder="Bank name" value="{{ old('bank_name') }}">
                    </div>
                    <div class="col-md-3 col-sm-6 form-group">
                        <label for="branch_name">Branch</label>
                        <input type="text" id="branch_name" name="branch_name" class="form-control form-control-sm" placeholder="Branch name" value="{{ old('branch_name') }}">
                    </div>
                    <div class="col-md-3 col-sm-6 form-group">
                        <label for="account_number">Account No.</label>
                        <input type="text" id="account_number" name="account_number" class="form-control form-control-sm" placeholder="Account number" value="{{ old('account_number') }}">
                    </div>
                    <div class="col-md-3 col-sm-6 form-group">
                        <label for="account_type">Account Type</label>
                        <select name="account_type" id="account_type" class="form-control form-control-sm">
                            <option value="" disabled {{ old('account_type') ? '' : 'selected' }}>Select type</option>
                            @foreach($accountTypes as $type)
                                <option value="{{ $type->accounttype }}" {{ old('account_type') == $type->accounttype ? 'selected' : '' }}>{{ $type->accounttype }}</option>
                            @endforeach
                        </select>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-3 col-sm-6 form-group">
                        <label for="account_holder_name">Account Holder</label>
                        <input type="text" id="account_holder_name" name="account_holder_name" class="form-control form-control-sm" placeholder="Holder name" value="{{ old('account_holder_name') }}">
                    </div>
                    <div class="col-md-3 col-sm-6 form-group">
                        <label for="ifsc_code">IFSC Code</label>
                        <input type="text" id="ifsc_code" name="ifsc_code" class="form-control form-control-sm text-uppercase" placeholder="ABCD0001234" value="{{ old('ifsc_code') }}" maxlength="11">
                    </div>
                    <div class="col-md-3 col-sm-6 form-group">
                        <label for="swift_code">SWIFT/BIC</label>
                        <input type="text" id="swift_code" name="swift_code" class="form-control form-control-sm text-uppercase" placeholder="Optional" value="{{ old('swift_code') }}">
                    </div>
                    <div class="col-md-3 col-sm-6 form-group">
                        <label for="account_currency">Currency</label>
                        <input type="text" id="account_currency" name="account_currency" class="form-control form-control-sm" value="{{ old('account_currency', 'INR') }}">
                    </div>
                </div>

                <!-- Contact Persons Section -->
                <div class="section-header">
                    <i class="fas fa-users"></i>
                    <h6>Contact Persons</h6>
                    <span class="badge badge-secondary">Optional</span>
                </div>

                <div id="contact-person-container">
                    <div class="contact-card" data-index="0">
                        <div class="contact-header">
                            <span class="badge badge-primary"><i class="fas fa-user mr-1"></i>Contact #1</span>
                            <button type="button" class="btn btn-outline-danger btn-sm py-0 px-2 remove-contact d-none" style="font-size: 0.75rem;">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                        <div class="row">
                            <div class="col-md-3 col-6 form-group mb-2">
                                <input type="text" name="contacts[0][name]" class="form-control form-control-sm person-name" placeholder="Name">
                            </div>
                            <div class="col-md-3 col-6 form-group mb-2">
                                <input type="email" name="contacts[0][email]" class="form-control form-control-sm person-email" placeholder="Email">
                            </div>
                            <div class="col-md-3 col-6 form-group mb-2">
                                <input type="text" name="contacts[0][mobile]" class="form-control form-control-sm person-mobile" placeholder="Mobile">
                            </div>
                            <div class="col-md-3 col-6 form-group mb-2">
                                <input type="text" name="contacts[0][designation]" class="form-control form-control-sm person-designation" placeholder="Designation">
                            </div>
                        </div>
                    </div>
                </div>

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

                <!-- Submit Section -->
                <div class="submit-section">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <button class="btn btn-primary" 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">Save Customer</span>
                            </button>
                            <button class="btn btn-outline-secondary ml-2" type="reset" id="resetBtn">
                                <i class="fas fa-undo mr-1"></i>Reset
                            </button>
                        </div>
                        <a href="{{ route('superadmin.customer.customerlist') }}" class="btn btn-link text-muted">
                            <i class="fas fa-arrow-left mr-1"></i>Back to List
                        </a>
                    </div>
                </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 file...');
    });

    // Form validation
    $('#customerForm').on('submit', function(e) {
        let isValid = true;
        $('.text-danger.small').filter('[id]').addClass('d-none');

        if (!$('input[name="company_role"]:checked').val()) { $('#companyRoleError').removeClass('d-none'); isValid = false; }
        if ($('#company').val().trim() === '') { $('#companyError').removeClass('d-none'); isValid = false; }

        var email = $('#email').val().trim();
        if (email === '' || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { $('#emailError').removeClass('d-none'); isValid = false; }
        if ($('#mobile').val().trim() === '') { $('#mobileError').removeClass('d-none'); isValid = false; }
        if (!$('#company_type').val()) { $('#companyTypeError').removeClass('d-none'); isValid = false; }

        var gst = $('#gstno').val().trim().toUpperCase();
        if (gst === '' || !/^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$/.test(gst)) {
            $('#gstError').removeClass('d-none'); isValid = false;
        }

        var pan = $('#panno').val().trim().toUpperCase();
        if (pan === '' || !/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/.test(pan)) {
            $('#panError').removeClass('d-none'); isValid = false;
        }

        if (!isValid) {
            e.preventDefault();
            var firstError = $('.text-danger.small:not(.d-none)').first();
            if (firstError.length) {
                $('html, body').animate({ scrollTop: firstError.offset().top - 100 }, 300);
            }
            return false;
        }

        $('#submitBtn').prop('disabled', true);
        $('#submitSpinner').removeClass('d-none');
        $('#submitIcon').addClass('d-none');
        $('#submitText').text('Saving...');
    });

    // Reset form
    $('#resetBtn').on('click', function() {
        $('.custom-file-label').html('Choose file...');
        $('.text-danger.small').filter('[id]').addClass('d-none');
        $('#contact-person-container .contact-card:not(:first)').remove();
        updateRemoveButtons();
    });

    // Convert to uppercase
    $('#gstno, #panno, #ifsc_code, #swift_code').on('input', function() {
        $(this).val($(this).val().toUpperCase());
    });

    // Contact Person Management
    function createContactHTML(idx) {
        return `
            <div class="contact-card" data-index="${idx}">
                <div class="contact-header">
                    <span class="badge badge-primary"><i class="fas fa-user mr-1"></i>Contact #${idx + 1}</span>
                    <button type="button" class="btn btn-outline-danger btn-sm py-0 px-2 remove-contact" style="font-size: 0.75rem;">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="row">
                    <div class="col-md-3 col-6 form-group mb-2">
                        <input type="text" name="contacts[${idx}][name]" class="form-control form-control-sm" placeholder="Name">
                    </div>
                    <div class="col-md-3 col-6 form-group mb-2">
                        <input type="email" name="contacts[${idx}][email]" class="form-control form-control-sm" placeholder="Email">
                    </div>
                    <div class="col-md-3 col-6 form-group mb-2">
                        <input type="text" name="contacts[${idx}][mobile]" class="form-control form-control-sm" placeholder="Mobile">
                    </div>
                    <div class="col-md-3 col-6 form-group mb-2">
                        <input type="text" name="contacts[${idx}][designation]" class="form-control form-control-sm" placeholder="Designation">
                    </div>
                </div>
            </div>
        `;
    }

    $('#add-contact').on('click', function() {
        var newIdx = $('#contact-person-container .contact-card').length;
        $('#contact-person-container').append(createContactHTML(newIdx));
        updateRemoveButtons();
    });

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

    function reindexContacts() {
        $('#contact-person-container .contact-card').each(function(idx) {
            $(this).attr('data-index', idx);
            $(this).find('.badge').html('<i class="fas fa-user mr-1"></i>Contact #' + (idx + 1));
            $(this).find('input').each(function() {
                var name = $(this).attr('name');
                $(this).attr('name', name.replace(/contacts\[\d+\]/, 'contacts[' + idx + ']'));
            });
        });
        updateRemoveButtons();
    }

    function updateRemoveButtons() {
        var contacts = $('#contact-person-container .contact-card');
        contacts.each(function() {
            $(this).find('.remove-contact').toggleClass('d-none', contacts.length <= 1);
        });
    }

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