@extends('layouts.dashboard.superadminapp')

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

@section('content')
    <!-- Page Heading -->
    <div class="bg-white p-2 d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h5 mb-0 text-gray-800">UEPL | Customer/Vendor Registration</h1>
        <div class="display-date">
            <span id="day">day</span>,
            <span id="daynum">00</span>
            <span id="month">month</span>
            <span id="year">0000</span>
        </div>
        <div class="display-time"></div>
    </div>

    <!-- Content Row -->
    <div class="row">
        <div class="col-lg-12">
            <div class="projects-section-header">
                @if (session('success'))
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        {{ 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">
                        {{ 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
            </div>

            <!-- Customer Registration Form -->
            <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-user-plus mr-2"></i>Customer/Vendor Registration Form
                    </h6>
                </div>
                <div class="card-body">
                    <form id="customerForm" action="{{ route('superadmin.customer.vendor.store') }}" method="POST"
                        enctype="multipart/form-data">
                        @csrf

                        <!-- 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">
                                <div class="custom-control custom-radio mr-4">
                                    <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">Customer</label>
                                </div>
                                <div class="custom-control custom-radio mr-4">
                                    <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">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">Customer & Vendor</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>

                        <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">
                            <!-- Company Name -->
                            <div class="col-md-6 mb-3">
                                <label for="company">Company Name <span class="text-danger">*</span></label>
                                <input type="text" id="company" name="company" class="form-control" placeholder="Company Name"
                                    value="{{ old('company') }}" required>
                                <span class="text-danger small d-none" id="companyError">Company Name is required.</span>
                                @error('company')
                                    <span class="text-danger small">{{ $message }}</span>
                                @enderror
                            </div>

                            <!-- Email -->
                            <div class="col-md-6 mb-3">
                                <label for="email">Company Email <span class="text-danger">*</span></label>
                                <input type="email" id="email" name="email" class="form-control" placeholder="Company Email"
                                    value="{{ old('email') }}" required>
                                <span class="text-danger small d-none" id="emailError">Valid Email is required.</span>
                                @error('email')
                                    <span class="text-danger small">{{ $message }}</span>
                                @enderror
                            </div>
                        </div>

                        <div class="row">
                            <!-- Company Acronym -->
                            <div class="col-md-6 mb-3">
                                <label for="company_nickname">Company Acronym</label>
                                <input type="text" id="company_nickname" name="company_nickname" class="form-control"
                                    placeholder="Company Acronym" value="{{ old('company_nickname') }}">
                                @error('company_nickname')
                                    <span class="text-danger small">{{ $message }}</span>
                                @enderror
                            </div>

                            <!-- Upload Logo -->
                            <div class="col-md-6 mb-3">
                                <label for="image">Company Logo</label>
                                <div class="custom-file">
                                    <input type="file" id="image" name="image" accept="image/*" class="custom-file-input">
                                    <label class="custom-file-label" for="image">Choose file...</label>
                                </div>
                                @error('image')
                                    <span class="text-danger small">{{ $message }}</span>
                                @enderror
                            </div>
                        </div>

                        <div class="row">
                            <!-- Mobile -->
                            <div class="col-md-3 mb-3">
                                <label for="mobile">Company Contact Number <span class="text-danger">*</span></label>
                                <input type="tel" id="mobile" name="mobile" class="form-control"
                                    placeholder="Company Contact No" value="{{ old('mobile') }}" required>
                                <span class="text-danger small d-none" id="mobileError">Company Contact Number is required.</span>
                                @error('mobile')
                                    <span class="text-danger small">{{ $message }}</span>
                                @enderror
                            </div>

                            <!-- Secondary Mobile -->
                            <div class="col-md-3 mb-3">
                                <label for="secondary_mobile">Secondary Contact Number</label>
                                <input type="tel" id="secondary_mobile" name="secondary_mobile" class="form-control"
                                    placeholder="Secondary Contact No" value="{{ old('secondary_mobile') }}">
                                @error('secondary_mobile')
                                    <span class="text-danger small">{{ $message }}</span>
                                @enderror
                            </div>

                            <!-- Company Type -->
                            <div class="col-md-6 mb-3">
                                <label for="company_type">Type of Company <span class="text-danger">*</span></label>
                                <select id="company_type" name="company_type" class="form-control" required>
                                    <option value="" disabled {{ old('company_type') ? '' : 'selected' }}>Select Company Type</option>
                                    @foreach($companyTypes as $type)
                                        <option value="{{ $type->companytype }}"
                                            {{ old('company_type') == $type->companytype ? 'selected' : '' }}>
                                            {{ $type->companytype }}
                                        </option>
                                    @endforeach
                                </select>
                                <span class="text-danger small d-none" id="companyTypeError">Please select a company type.</span>
                                @error('company_type')
                                    <span class="text-danger small">{{ $message }}</span>
                                @enderror
                            </div>
                        </div>

                        <div class="row">
                            <!-- GST No -->
                            <div class="col-md-6 mb-3">
                                <label for="gstno">GST <span class="text-danger">*</span></label>
                                <input type="text" id="gstno" name="gstno" class="form-control text-uppercase" placeholder="GST No"
                                    value="{{ old('gstno') }}" required maxlength="15">
                                <span class="text-danger small d-none" id="gstError">Valid GST No is required (e.g., 22AAAAA0000A1Z5).</span>
                                @error('gstno')
                                    <span class="text-danger small">{{ $message }}</span>
                                @enderror
                            </div>

                            <!-- PAN No -->
                            <div class="col-md-6 mb-3">
                                <label for="panno">Company PAN <span class="text-danger">*</span></label>
                                <input type="text" id="panno" name="panno" class="form-control text-uppercase" placeholder="Company PAN"
                                    value="{{ old('panno') }}" required maxlength="10">
                                <span class="text-danger small d-none" id="panError">Valid Company PAN is required (e.g., ABCDE1234F).</span>
                                @error('panno')
                                    <span class="text-danger small">{{ $message }}</span>
                                @enderror
                            </div>
                        </div>

                        <div class="row">
                            <!-- MSME/Udyam No -->
                            <div class="col-md-6 mb-3">
                                <label for="msmeno">MSME/Udyam</label>
                                <input type="text" id="msmeno" name="msmeno" class="form-control" placeholder="MSME/Udyam No"
                                    value="{{ old('msmeno') }}">
                                @error('msmeno')
                                    <span class="text-danger small">{{ $message }}</span>
                                @enderror
                            </div>

                            <!-- IEC No -->
                            <div class="col-md-6 mb-3">
                                <label for="iecno">IEC</label>
                                <input type="text" id="iecno" name="iecno" class="form-control" placeholder="IEC No"
                                    value="{{ old('iecno') }}">
                                @error('iecno')
                                    <span class="text-danger small">{{ $message }}</span>
                                @enderror
                            </div>
                        </div>

                        <div class="row">
                            <!-- Billing Address -->
                            <div class="col-md-6 mb-3">
                                <label for="billing_address">Billing Address</label>
                                <textarea id="billing_address" name="billing_address" class="form-control" rows="2"
                                    placeholder="Billing Address">{{ old('billing_address') }}</textarea>
                                @error('billing_address')
                                    <span class="text-danger small">{{ $message }}</span>
                                @enderror
                            </div>

                            <!-- Shipping Address -->
                            <div class="col-md-6 mb-3">
                                <label for="shipping_address">Shipping Address</label>
                                <textarea id="shipping_address" name="shipping_address" class="form-control" rows="2"
                                    placeholder="Shipping Address">{{ old('shipping_address') }}</textarea>
                                @error('shipping_address')
                                    <span class="text-danger small">{{ $message }}</span>
                                @enderror
                            </div>
                        </div>

                        <div class="row">
                            <!-- Website URL -->
                            <div class="col-md-6 mb-3">
                                <label for="url">Website URL</label>
                                <input type="url" id="url" name="url" class="form-control" placeholder="https://www.example.com"
                                    value="{{ old('url') }}">
                                @error('url')
                                    <span class="text-danger small">{{ $message }}</span>
                                @enderror
                            </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">
                            <!-- Bank Name -->
                            <div class="col-md-6 mb-3">
                                <label for="bank_name">Bank Name</label>
                                <input type="text" id="bank_name" name="bank_name" class="form-control" placeholder="Bank Name"
                                    value="{{ old('bank_name') }}">
                                @error('bank_name')
                                    <span class="text-danger small">{{ $message }}</span>
                                @enderror
                            </div>

                            <!-- Bank Branch Name -->
                            <div class="col-md-6 mb-3">
                                <label for="branch_name">Bank Branch Name</label>
                                <input type="text" id="branch_name" name="branch_name" class="form-control"
                                    placeholder="Branch Name" value="{{ old('branch_name') }}">
                                @error('branch_name')
                                    <span class="text-danger small">{{ $message }}</span>
                                @enderror
                            </div>
                        </div>

                        <div class="row">
                            <!-- Account Number -->
                            <div class="col-md-6 mb-3">
                                <label for="account_number">Account Number</label>
                                <input type="text" id="account_number" name="account_number" class="form-control"
                                    placeholder="Account Number" value="{{ old('account_number') }}">
                                @error('account_number')
                                    <span class="text-danger small">{{ $message }}</span>
                                @enderror
                            </div>

                            <!-- Account Type -->
                            <div class="col-md-6 mb-3">
                                <label for="account_type">Account Type</label>
                                <select name="account_type" id="account_type" class="form-control">
                                    <option value="" disabled {{ old('account_type') ? '' : 'selected' }}>Select account type</option>
                                    @foreach($accountTypes as $type)
                                        <option value="{{ $type->accounttype }}"
                                            {{ old('account_type') == $type->accounttype ? 'selected' : '' }}>
                                            {{ $type->accounttype }}
                                        </option>
                                    @endforeach
                                </select>
                                @error('account_type')
                                    <span class="text-danger small">{{ $message }}</span>
                                @enderror
                            </div>
                        </div>

                        <div class="row">
                            <!-- Account Holder Name -->
                            <div class="col-md-6 mb-3">
                                <label for="account_holder_name">Account Holder Name</label>
                                <input type="text" id="account_holder_name" name="account_holder_name" class="form-control"
                                    placeholder="Account Holder Name" value="{{ old('account_holder_name') }}">
                                @error('account_holder_name')
                                    <span class="text-danger small">{{ $message }}</span>
                                @enderror
                            </div>

                            <!-- Account Currency -->
                            <div class="col-md-6 mb-3">
                                <label for="account_currency">Account Currency</label>
                                <input type="text" id="account_currency" name="account_currency" class="form-control"
                                    value="{{ old('account_currency', 'INR') }}">
                                @error('account_currency')
                                    <span class="text-danger small">{{ $message }}</span>
                                @enderror
                            </div>
                        </div>

                        <div class="row">
                            <!-- IFSC Code -->
                            <div class="col-md-6 mb-3">
                                <label for="ifsc_code">IFSC Code</label>
                                <input type="text" id="ifsc_code" name="ifsc_code" class="form-control text-uppercase" placeholder="IFSC Code"
                                    value="{{ old('ifsc_code') }}" maxlength="11">
                                @error('ifsc_code')
                                    <span class="text-danger small">{{ $message }}</span>
                                @enderror
                            </div>

                            <!-- SWIFT/BIC Code -->
                            <div class="col-md-6 mb-3">
                                <label for="swift_code">SWIFT/BIC Code</label>
                                <input type="text" id="swift_code" name="swift_code" class="form-control text-uppercase"
                                    placeholder="SWIFT/BIC Code" value="{{ old('swift_code') }}">
                                @error('swift_code')
                                    <span class="text-danger small">{{ $message }}</span>
                                @enderror
                            </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">
                            <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 person-name" 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 person-email" 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 person-mobile" 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 person-designation" placeholder="Designation">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </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">Save</span>
                            </button>
                            <button class="btn btn-secondary" type="reset" id="resetBtn">
                                <i class="fas fa-undo mr-1"></i> Clear
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </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;

        // Hide all error messages first
        $('.text-danger.small').filter('[id]').addClass('d-none');

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

        // Validate Company Name
        if ($('#company').val().trim() === '') {
            $('#companyError').removeClass('d-none');
            isValid = false;
        }

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

        // Validate Mobile
        if ($('#mobile').val().trim() === '') {
            $('#mobileError').removeClass('d-none');
            isValid = false;
        }

        // Validate Company Type
        if ($('#company_type').val() === '' || $('#company_type').val() === null) {
            $('#companyTypeError').removeClass('d-none');
            isValid = false;
        }

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

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

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

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

    // Reset form
    $('#resetBtn').on('click', function() {
        // Reset custom file input label
        $('.custom-file-label').html('Choose file...');
        // Hide all error messages
        $('.text-danger.small').filter('[id]').addClass('d-none');
        // Remove extra contact persons (keep only first one)
        $('#contact-person-container .contact-person:not(:first)').remove();
        updateContactNumbers();
    });

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

    // Contact Person Management
    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 person-name" 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 person-email" 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 person-mobile" 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 person-designation" placeholder="Designation">
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    // Add contact
    $('#add-contact').on('click', function() {
        var contacts = $('#contact-person-container .contact-person');
        var newIdx = contacts.length;
        $('#contact-person-container').append(createContactHTML(newIdx));
        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 + ']'));
            });
        });
        updateRemoveButtons();
    }

    function updateContactNumbers() {
        $('#contact-person-container .contact-person').each(function(idx) {
            $(this).find('.badge').text('Contact #' + (idx + 1));
        });
        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
