@extends('layouts.dashboard.managerapp')

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

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

    <!-- 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="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                @endif

                @if (session('error'))
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        {{ session('error') }}
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                @endif
                @if ($errors->any())
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <ul>
                            @foreach ($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                @endif

            </div>
            <!-- Project Planning Start -->
            <div class="form-container">
                <h1 class="pt-5 pb-5">Customer/Vendor Registration Form</h1>
                <form id="customerForm" action="{{ route('manager.customer.vendor.store') }}" method="POST"
                    enctype="multipart/form-data">
                    @csrf
                    <div class="row">
                        <div class="col-md-12">
                            <label>Company Role <span class="required">*</span></label>
                            <div class="d-flex">
                                <div class="form-check me-3"
                                    style="padding-left: 11.25rem !important;margin-top: -30px;margin-bottom: 20px;">
                                    <input type="radio" id="customer" name="company_role" value="Customer"
                                        class="form-check-input" {{ old('company_role') == 'Customer' ? 'checked' : '' }}
                                        required>
                                    <label for="customer" class="form-check-label">Customer</label>
                                </div>
                                <div class="form-check me-3"
                                    style="padding-left: 11.25rem !important;margin-top: -30px;margin-bottom: 20px;">
                                    <input type="radio" id="vendor" name="company_role" value="Vendor"
                                        class="form-check-input" {{ old('company_role') == 'Vendor' ? 'checked' : '' }}
                                        required>
                                    <label for="vendor" class="form-check-label">Vendor</label>
                                </div>
                                <div class="form-check"
                                    style="padding-left: 11.25rem !important;margin-top: -30px;margin-bottom: 20px;">
                                    <input type="radio" id="bothCV" name="company_role" value="Both"
                                        class="form-check-input" {{ old('company_role') == 'Both' ? 'checked' : '' }}
                                        required>
                                    <label for="bothCV" class="form-check-label">Customer & Vendor</label>
                                </div>
                            </div>

                            <!-- Laravel Server-Side Validation Error -->
                            @error('company_role')
                                <span class="text-danger">{{ $message }}</span>
                            @enderror

                            <!-- JavaScript Client-Side Validation Error -->
                            <span class="text-danger d-none" id="companyRoleError">Please select a company role.</span>
                        </div>
                    </div>

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

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

                    <!-- <div class="col-md-6">
                                                <br>
                                                <h5>Company Details</h5>
                                                <br>
                                            </div> -->
                    <div class="row">
                        <!-- Company Acronym -->
                        <div class="col-md-6">
                            <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">{{ $message }}</span>
                            @enderror
                        </div>

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

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

                                <div class="col-md-6">
                                    <label for="secondary-contact">Secondary Contact Number</label>
                                    <input type="tel" id="secondary-contact" name="secondary_mobile" class="form-control"
                                        placeholder="Secondary Contact No" value="{{ old('secondary_mobile') }}">
                                    <span class="text-danger d-none" id="secondaryMobileError">Secondary Contact Number is
                                        required.</span>
                                    @error('secondary_mobile')
                                        <span class="text-danger">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <!-- Company Type -->
                        <div class="col-md-6">
                            <label for="company_type">Type of Company <span class="required" title="required">*</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

                                <!-- <option value="Other" {{ old('company_type') == 'Other' ? 'selected' : '' }}>Other</option> -->
                            </select>
                            <span class="text-danger d-none" id="companyTypeError">Please select a company type.</span>
                            @error('company_type')
                                <span class="text-danger">{{ $message }}</span>
                            @enderror
                        </div>
                    </div>

                    <div class="row">
                        <!-- GST No -->
                        <div class="col-md-6">
                            <label for="gstno">GST <span class="required" title="required">*</span></label>
                            <input type="text" id="gstno" name="gstno" class="form-control" placeholder="GST No"
                                value="{{ old('gstno') }}" required>
                            <span class="text-danger d-none" id="gstError">GST No is required.</span>
                            @error('gstno')
                                <span class="text-danger">{{ $message }}</span>
                            @enderror
                        </div>

                        <!-- PAN No -->
                        <div class="col-md-6">
                            <label for="panno">Company PAN <span class="required" title="required">*</span></label>
                            <input type="text" id="panno" name="panno" class="form-control" placeholder="Company PAN"
                                value="{{ old('panno') }}" required>
                            <span class="text-danger d-none" id="panError">Company PAN is required.</span>
                            @error('panno')
                                <span class="text-danger">{{ $message }}</span>
                            @enderror
                        </div>
                    </div>

                    <div class="row mt-3">
                        <!-- MSME/Udyam No -->
                        <div class="col-md-6">
                            <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">{{ $message }}</span>
                            @enderror
                        </div>

                        <!-- IEC No -->
                        <div class="col-md-6">
                            <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">{{ $message }}</span>
                            @enderror
                        </div>
                    </div>

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

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

                    <div class="row mt-3">
                        <!-- Website URL -->
                        <div class="col-md-6">
                            <label for="url">Website URL</label>
                            <input type="url" id="url" name="url" class="form-control" placeholder="http://www.example.com"
                                value="{{ old('url') }}">
                            @error('url')
                                <span class="text-danger">{{ $message }}</span>
                            @enderror
                        </div>
                    </div>
                    <br><br>
                    <!-- Bank Account Details -->
                    <label for="company-account">Bank Account Details :</label><br>
                    <div class="row">
                        <!-- Bank Name -->
                        <div class="col-md-6">
                            <label for="bank_name">Bank Name <span class="required" title="required">*</span></label>
                            <input type="text" id="bank_name" name="bank_name" class="form-control" placeholder="Bank Name"
                                value="{{ old('bank_name') }}" required>
                            <span class="text-danger d-none" id="bankNameError">Bank Name is required.</span>
                            @error('bank_name')
                                <span class="text-danger">{{ $message }}</span>
                            @enderror
                        </div>

                        <!-- Bank Branch Name -->
                        <div class="col-md-6">
                            <label for="branch_name">Bank Branch Name <span class="required"
                                    title="required">*</span></label>
                            <input type="text" id="branch_name" name="branch_name" class="form-control"
                                placeholder="Branch Name" value="{{ old('branch_name') }}" required>
                            <span class="text-danger d-none" id="branchNameError">Bank Branch Name is required.</span>
                            @error('branch_name')
                                <span class="text-danger">{{ $message }}</span>
                            @enderror
                        </div>
                    </div>

                    <div class="row mt-3">
                        <!-- Account Number -->
                        <div class="col-md-6">
                            <label for="account_number">Account Number <span class="required"
                                    title="required">*</span></label>
                            <input type="text" id="account_number" name="account_number" class="form-control"
                                placeholder="Account Number" value="{{ old('account_number') }}" required>
                            <span class="text-danger d-none" id="accountNumberError">Valid Account Number is
                                required.</span>
                            @error('account_number')
                                <span class="text-danger">{{ $message }}</span>
                            @enderror
                        </div>

                        <!-- Account Type -->
                        <div class="col-md-6">
                            <label for="account_type">Account Type <span class="required" title="required">*</span></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>
                            <span class="text-danger d-none" id="accountTypeError">Please select an account type.</span>
                            @error('account_type')
                                <span class="text-danger">{{ $message }}</span>
                            @enderror
                        </div>

                    </div>


                    <div class="row mt-3">
                        <!-- Account Holder Name -->
                        <div class="col-md-6">
                            <label for="account_holder_name">Account Holder Name <span class="required"
                                    title="required">*</span></label>
                            <input type="text" id="account_holder_name" name="account_holder_name" class="form-control"
                                placeholder="Account Holder Name" value="{{ old('account_holder_name') }}" required>
                            <span class="text-danger d-none" id="accountHolderNameError">Account Holder Name is
                                required.</span>
                            @error('account_holder_name')
                                <span class="text-danger">{{ $message }}</span>
                            @enderror
                        </div>

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

                    <div class="row mt-3">
                        <!-- IFSC Code -->
                        <div class="col-md-6">
                            <label for="ifsc-code">IFSC Code <span class="required" title="required">*</span></label>
                            <input type="text" id="ifsc_code" name="ifsc_code" class="form-control" placeholder="IFSC Code"
                                value="{{ old('ifsc_code') }}">
                            <span class="text-danger d-none" id="ifscCodeError">Valid IFSC Code is required.</span>
                            @error('ifsc-code')
                                <span class="text-danger">{{ $message }}</span>
                            @enderror
                        </div>

                        <!-- SWIFT/BIC Code -->
                        <div class="col-md-6">
                            <label for="swift-code">SWIFT/BIC Code</label>
                            <input type="text" id="swift_code" name="swift_code" class="form-control"
                                placeholder="SWIFT/BIC Code" value="{{ old('swift_code') }}">
                            @error('swift-code')
                                <span class="text-danger">{{ $message }}</span>
                            @enderror
                        </div>
                    </div>

                    <br><br>
                    <!-- Contact Persons Section -->
                    <div id="contact-person-container">
                        <h5>Contact Persons</h5>
                        <div class="contact-person row" data-index="0">
                            <div class="col-md-12 text-end d-none">
                                <button type="button" class="btn btn-danger btn-sm remove-contact"
                                    style="    float: right;width: auto;">Remove</button>
                            </div>
                            <div class="col-md-6">
                                <label>Name <span class="required">*</span></label>
                                <input type="text" name="contacts[0][name]" class="form-control person-name"
                                    placeholder="Name" required>
                                <span class="text-danger d-none nameError">Name is required.</span>
                            </div>
                            <div class="col-md-6">
                                <label>Email <span class="required">*</span></label>
                                <input type="email" name="contacts[0][email]" class="form-control person-email"
                                    placeholder="Email" required>
                                <span class="text-danger d-none emailError">Valid Email is required.</span>
                            </div>
                            <div class="col-md-6 mt-2">
                                <label>Mobile <span class="required">*</span></label>
                                <input type="text" name="contacts[0][mobile]" class="form-control person-mobile"
                                    placeholder="Mobile" required>
                                <span class="text-danger d-none mobileError">Mobile is required.</span>
                            </div>
                            <div class="col-md-6 mt-2">
                                <label>Designation</label>
                                <input type="text" name="contacts[0][designation]" class="form-control person-designation"
                                    placeholder="Designation">
                            </div>
                        </div>
                    </div>

                    <!-- Add Another Contact -->
                    <button type="button" class="btn btn-link mt-3" id="add-contact">+ Add Another Contact</button>


                    <div class="row p-5">
                        <!-- Submit Button -->
                        <div class="btn pt-5 pb-5"><button class="btn btn-success" type="submit">Save</button>
                        </div>

                        <div class="btn pt-5 pb-5"><button class="btn btn-danger" type="reset"
                                onclick="resetForm()">Clear</button></div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        document.getElementById("customerForm").addEventListener("submit", function (event) {
            let isValid = true;

            // Validate Company Role
            const companyRole = document.querySelector('input[name="company_role"]:checked');
            if (!companyRole) {
                document.getElementById("companyRoleError").classList.remove("d-none");
                isValid = false;
            } else {
                document.getElementById("companyRoleError").classList.add("d-none");
            }

            // Validate Company Name
            const company = document.getElementById("company").value.trim();
            if (company === "") {
                document.getElementById("companyError").classList.remove("d-none");
                isValid = false;
            } else {
                document.getElementById("companyError").classList.add("d-none");
            }

            // Validate Email
            const email = document.getElementById("email").value.trim();
            const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (email === "" || !emailPattern.test(email)) {
                document.getElementById("emailError").classList.remove("d-none");
                isValid = false;
            } else {
                document.getElementById("emailError").classList.add("d-none");
            }

            // Validate Company Contact Number
            const mobile = document.getElementById("company-contact").value.trim();
            if (mobile === "") {
                document.getElementById("mobileError").classList.remove("d-none");
                isValid = false;
            } else {
                document.getElementById("mobileError").classList.add("d-none");
            }

            // Validate Company Type
            const companyType = document.getElementById("company_type").value;
            if (companyType === "") {
                document.getElementById("companyTypeError").classList.remove("d-none");
                isValid = false;
            } else {
                document.getElementById("companyTypeError").classList.add("d-none");
            }

            // Validate GST No
            const gst = document.getElementById("gstno").value.trim();
            const 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)) {
                document.getElementById("gstError").classList.remove("d-none");
                isValid = false;
            } else {
                document.getElementById("gstError").classList.add("d-none");
            }

            // Validate PAN No
            const pan = document.getElementById("panno").value.trim();
            const panPattern = /^[A-Z]{5}[0-9]{4}[A-Z]{1}$/;
            if (pan === "" || !panPattern.test(pan)) {
                document.getElementById("panError").classList.remove("d-none");
                isValid = false;
            } else {
                document.getElementById("panError").classList.add("d-none");
            }

            // Validate Bank Name
            const bankName = document.getElementById("bank_name").value.trim();
            if (bankName === "") {
                document.getElementById("bankNameError").classList.remove("d-none");
                isValid = false;
            } else {
                document.getElementById("bankNameError").classList.add("d-none");
            }

            // Validate Bank Branch Name
            const branchName = document.getElementById("branch_name").value.trim();
            if (branchName === "") {
                document.getElementById("branchNameError").classList.remove("d-none");
                isValid = false;
            } else {
                document.getElementById("branchNameError").classList.add("d-none");
            }

            // Validate Account Number
            const accountNumber = document.getElementById("account_number").value.trim();
            const accountNumberPattern = /^[0-9]{8,20}$/;
            if (accountNumber === "" || !accountNumberPattern.test(accountNumber)) {
                document.getElementById("accountNumberError").classList.remove("d-none");
                isValid = false;
            } else {
                document.getElementById("accountNumberError").classList.add("d-none");
            }

            // Validate IFSC Code
            const ifscCode = document.getElementById("ifsc-code").value.trim();
            const ifscPattern = /^[A-Z]{4}0[A-Z0-9]{6}$/;
            if (ifscCode === "" || !ifscPattern.test(ifscCode)) {
                document.getElementById("ifscCodeError").classList.remove("d-none");
                isValid = false;
            } else {
                document.getElementById("ifscCodeError").classList.add("d-none");
            }


            // Stop form submission if validation fails
            if (!isValid) {
                event.preventDefault();
            }
        });

        // Show/hide the "Other" input field based on selection
        function toggleOtherInput() {
            let companyType = document.getElementById('company_type').value;
            if (companyType === "Other") {
                document.getElementById('other-input').style.display = "block";
            } else {
                document.getElementById('other-input').style.display = "none";
            }
        }
    </script>
    <script>
        document.addEventListener("DOMContentLoaded", function () {
            // Helper to build a contact person block
            function createContactHTML(idx) {
                return `
            <div class="contact-person row mt-3" data-index="${idx}">
                <div class="col-md-12 text-end">
                    <button type="button" class="btn btn-danger btn-sm remove-contact" style="    float: right;
        width: auto;">Remove</button>
                </div>
                <div class="col-md-6">
                    <label>Name <span class="required">*</span></label>
                    <input type="text" name="contacts[${idx}][name]" class="form-control person-name" placeholder="Name" required>
                </div>
                <div class="col-md-6">
                    <label>Email <span class="required">*</span></label>
                    <input type="email" name="contacts[${idx}][email]" class="form-control person-email" placeholder="Email" required>
                </div>
                <div class="col-md-6 mt-2">
                    <label>Mobile <span class="required">*</span></label>
                    <input type="text" name="contacts[${idx}][mobile]" class="form-control person-mobile" placeholder="Mobile" required>
                </div>
                <div class="col-md-6 mt-2">
                    <label>Designation</label>
                    <input type="text" name="contacts[${idx}][designation]" class="form-control person-designation" placeholder="Designation">
                </div>
            </div>
            `;
            }

            // Add new contact
            document.getElementById("add-contact").addEventListener("click", function () {
                const container = document.getElementById("contact-person-container");
                const contacts = container.querySelectorAll('.contact-person');
                const newIdx = contacts.length;
                container.insertAdjacentHTML("beforeend", createContactHTML(newIdx));
                updateRemoveButtons();
            });

            // Remove a contact
            document.getElementById("contact-person-container").addEventListener("click", function (event) {
                if (event.target.classList.contains("remove-contact")) {
                    event.target.closest('.contact-person').remove();
                    reindexContacts();
                }
            });

            // Reindex all contacts and update names/IDs and remove button visibility
            function reindexContacts() {
                const container = document.getElementById("contact-person-container");
                const contacts = container.querySelectorAll('.contact-person');
                contacts.forEach((person, idx) => {
                    person.setAttribute('data-index', idx);
                    person.querySelectorAll("input").forEach(input => {
                        let field = input.getAttribute('name').replace(/contacts\[\d+\]/,
                            `contacts[${idx}]`);
                        input.setAttribute('name', field);
                    });
                });
                updateRemoveButtons();
            }

            // Hide Remove on first block if only one left
            function updateRemoveButtons() {
                const contacts = document.querySelectorAll('#contact-person-container .contact-person');
                contacts.forEach((c, i) => {
                    const removeBtn = c.querySelector('.remove-contact');
                    if (removeBtn) {
                        removeBtn.style.display = (contacts.length > 1) ? 'inline-block' : 'none';
                    }
                });
            }

            // On load
            updateRemoveButtons();
        });
    </script>
    <!-- Project Planning End-->
@endsection