<!-- Add Supplier Modal -->
<div class="modal fade" id="addSupplierModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content shadow-lg border-0">
            <div class="modal-header bg-gradient-success text-white py-2">
                <h6 class="modal-title mb-0"><i class="fas fa-user-plus"></i> <span data-translate="newSupplierTitle">New Supplier</span></h6>
                <button type="button" class="close text-white" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body p-3" style="max-height: 70vh; overflow-y: auto;">
                <form id="addSupplierForm">
                    <!-- Basic Information -->
                    <div class="row">
                        <div class="col-md-6 mb-2">
                            <label class="small font-weight-bold mb-1"><i class="fas fa-user text-primary"></i> <span data-translate="supplierNameLabel">Supplier Name</span> <span class="text-danger" data-translate="required">*</span></label>
                            <input type="text" class="form-control form-control-sm" id="newSupplierName" required>
                        </div>
                        <div class="col-md-6 mb-2">
                            <label class="small font-weight-bold mb-1"><i class="fas fa-phone text-success"></i> <span data-translate="phoneLabel">Phone Number</span> <span class="text-danger" data-translate="required">*</span></label>
                            <input type="text" class="form-control form-control-sm" id="newSupplierPhone" required>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-2">
                            <label class="small font-weight-bold mb-1"><i class="fas fa-user-tie text-info"></i> <span data-translate="contactPerson">Contact Person</span></label>
                            <input type="text" class="form-control form-control-sm" id="newContactPerson">
                        </div>
                        <div class="col-md-6 mb-2">
                            <label class="small font-weight-bold mb-1"><i class="fas fa-envelope text-warning"></i> <span data-translate="email">Email</span></label>
                            <input type="email" class="form-control form-control-sm" id="newSupplierEmail">
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-3 mb-2">
                            <label class="small font-weight-bold mb-1"><i class="fas fa-users text-secondary"></i> <span data-translate="supplierType">Supplier Type</span></label>
                            <select class="form-control form-control-sm" id="newSupplierType">
                                <option value="Individual" data-translate="individual">Individual</option>
                                <option value="Business" data-translate="business">Business</option>
                                <option value="Manufacturer" data-translate="manufacturer">Manufacturer</option>
                                <option value="Wholesaler" data-translate="wholesaler">Wholesaler</option>
                            </select>
                        </div>
                        <div class="col-md-9 mb-2">
                            <label class="small font-weight-bold mb-1"><i class="fas fa-map-marker-alt text-danger"></i> <span data-translate="addressLabel">Address</span></label>
                            <input type="text" class="form-control form-control-sm" id="newSupplierAddress">
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-4 mb-2">
                            <label class="small font-weight-bold mb-1"><i class="fas fa-city text-primary"></i> <span data-translate="city">City</span></label>
                            <input type="text" class="form-control form-control-sm" id="newSupplierCity">
                        </div>
                        <div class="col-md-4 mb-2">
                            <label class="small font-weight-bold mb-1"><i class="fas fa-map text-info"></i> <span data-translate="state">State</span></label>
                            <input type="text" class="form-control form-control-sm" id="newSupplierState">
                        </div>
                        <div class="col-md-4 mb-2">
                            <label class="small font-weight-bold mb-1"><i class="fas fa-mail-bulk text-secondary"></i> <span data-translate="pincode">Pin Code</span></label>
                            <input type="text" class="form-control form-control-sm" id="newSupplierPinCode" maxlength="10">
                        </div>
                    </div>

                    <!-- Tax & Business Details -->
                    <div class="row mt-2 pt-2" style="border-top: 1px dashed #dee2e6;">
                        <div class="col-md-6 mb-2">
                            <label class="small font-weight-bold mb-1"><i class="fas fa-file-invoice text-success"></i> <span data-translate="gstNumber">GST Number</span></label>
                            <input type="text" class="form-control form-control-sm text-uppercase" id="newSupplierGST" maxlength="15" placeholder="33XXXX7777XXXU">
                        </div>
                        <div class="col-md-6 mb-2">
                            <label class="small font-weight-bold mb-1"><i class="fas fa-id-card text-warning"></i> <span data-translate="panNumber">PAN Number</span></label>
                            <input type="text" class="form-control form-control-sm text-uppercase" id="newSupplierPAN" maxlength="10" placeholder="PMXXXXXX7H">
                        </div>
                    </div>
                    
                    <!-- Credit Information -->
                    <div class="row mt-2 pt-2" style="border-top: 1px dashed #dee2e6;">
                        <div class="col-md-6 mb-2">
                            <label class="small font-weight-bold mb-1"><i class="fas fa-rupee-sign text-danger"></i> <span data-translate="creditLimit">Credit Limit (₹)</span></label>
                            <input type="number" class="form-control form-control-sm" id="newCreditLimit" value="0.00" step="0.01" min="0">
                        </div>
                        <div class="col-md-6 mb-2">
                            <label class="small font-weight-bold mb-1"><i class="fas fa-calendar-alt text-primary"></i> <span data-translate="creditDays">Credit Days</span></label>
                            <input type="number" class="form-control form-control-sm" id="newCreditDays" value="0" min="0">
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer py-2 bg-light">
                <button type="button" class="btn btn-sm btn-secondary" data-dismiss="modal">
                    <i class="fas fa-times"></i> <span data-translate="close">Close</span>
                </button>
                <button type="button" class="btn btn-sm btn-success" id="btnSaveSupplier">
                    <i class="fas fa-save"></i> <span data-translate="save">Save Supplier</span>
                </button>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Save new supplier
    $('#btnSaveSupplier').on('click', async function() {
        // Basic validation
        var supplierName = $('#newSupplierName').val().trim();
        var supplierPhone = $('#newSupplierPhone').val().trim();

        if (!supplierName || !supplierPhone) {
            await MsgBox.alert('Supplier Name and Phone Number are required.');
            return;
        }

        // Create supplier data object
        var supplierData = {
            supplierName: supplierName,
            supplierPhone: supplierPhone,
            contactPerson: $('#newContactPerson').val().trim(),
            email: $('#newSupplierEmail').val().trim(),
            supplierType: $('#newSupplierType').val(),
            address: $('#newSupplierAddress').val().trim(),
            city: $('#newSupplierCity').val().trim(),
            state: $('#newSupplierState').val().trim(),
            pinCode: $('#newSupplierPinCode').val().trim(),
            gstNumber: $('#newSupplierGST').val().trim(),
            panNumber: $('#newSupplierPAN').val().trim(),
            creditLimit: $('#newCreditLimit').val(),
            creditDays: $('#newCreditDays').val()
        };

        // AJAX call to save supplier
        $.ajax({
            url: 'api/add_supplier.php',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(supplierData),
            dataType: 'json',
            success: async function(response) {
                if (response.success) {
                    await MsgBox.alert(response.message);
                    
                    // Create a new option element
                    var newOption = new Option(response.supplier.code + ' - ' + response.supplier.name, response.supplier.id, true, true);
                    
                    // Add data attributes to the new option
                    $(newOption).data('name', response.supplier.name);
                    $(newOption).data('code', response.supplier.code);
                    $(newOption).data('phone', response.supplier.phone);
                    $(newOption).data('gst', response.supplier.gst);

                    // Append the new option to the select dropdown and select it
                    $('#supplierSelect').append(newOption).trigger('change');

                    // Manually update the supplier info display
                    if ($('#supplierNameDisplay').length) {
                        $('#supplierNameDisplay').text(response.supplier.name);
                        $('#supplierPhoneDisplay').text(response.supplier.phone);
                        $('#supplierGSTDisplay').text(response.supplier.gst || 'N/A');
                        $('#supplierBalance').text('₹0.00'); // New supplier has 0 balance
                        $('#supplierLoyalty').html('<i class="fas fa-star"></i> 0');
                        $('#supplierInfoCard').show();
                    }
                    
                    // Close the modal
                    $('#addSupplierModal').modal('hide');
                    
                    // Reset the form
                    $('#addSupplierForm')[0].reset();

                } else {
                    await MsgBox.alert('Error: ' + response.message, 'Error');
                }
            },
            error: async function(xhr, status, error) {
                await MsgBox.alert('An unexpected error occurred: ' + error, 'Error');
            }
        });
    });
});
</script>
