// Clear city error on page load since it's now optional
$(document).ready(function() {
    $('#city_msg').fadeOut(200).hide().removeClass('required');
});

$('#update').on("click",function (e) {
	var base_url=$("#base_url").val();
    //Initially flag set true
    var flag=true;
    
    // Clear city error message since it's now optional
    $('#city_msg').fadeOut(200).hide().removeClass('required');

    function check_field(id)
    {
      var fieldValue = $("#"+id).val();
      if(!fieldValue || fieldValue.trim() === '') //Also check Others????
        {
            console.log("Validation failed for field: " + id); // Debug logging
            $('#'+id+'_msg').fadeIn(200).show().html('Required Field').addClass('required');
           // $('#'+id).css({'background-color' : '#E8E2E9'});
            flag=false;
        }
        else
        {
             $('#'+id+'_msg').fadeOut(200).hide();
             //$('#'+id).css({'background-color' : '#FFFFFF'});    //White color
        }
    }

    //STORE
	check_field("store_code");if(flag==false){console.log("Store code validation failed"); $("#tab_4_btn").trigger('click');}
	check_field("store_name");if(flag==false){console.log("Store name validation failed"); $("#tab_4_btn").trigger('click');}
	check_field("mobile");	if(flag==false){console.log("Mobile validation failed"); $("#tab_4_btn").trigger('click');}
	check_field("email");	if(flag==false){console.log("Email validation failed"); $("#tab_4_btn").trigger('click');}
	//check_field("city");	if(flag==false){$("#tab_4_btn").trigger('click');} // City is now optional
	check_field("address");	if(flag==false){console.log("Address validation failed"); $("#tab_4_btn").trigger('click');}
	if(flag==false){
		console.log("Store validation failed - check which field above");
		toastr["warning"]("You have Missed Something to Fillup!")
		return;
    }
	//PREFIXES
	check_field("category_init");if(flag==false){console.log("Category init validation failed"); $("#tab_3_btn").trigger('click');}
	check_field("item_init");if(flag==false){console.log("Item init validation failed"); $("#tab_3_btn").trigger('click');}
	check_field("supplier_init");if(flag==false){console.log("Supplier init validation failed"); $("#tab_3_btn").trigger('click');}
	check_field("purchase_init");if(flag==false){console.log("Purchase init validation failed"); $("#tab_3_btn").trigger('click');}
	check_field("purchase_return_init");if(flag==false){console.log("Purchase return init validation failed"); $("#tab_3_btn").trigger('click');}
	check_field("customer_init");if(flag==false){console.log("Customer init validation failed"); $("#tab_3_btn").trigger('click');}
	check_field("sales_init");if(flag==false){console.log("Sales init validation failed"); $("#tab_3_btn").trigger('click');}
	check_field("sales_return_init");if(flag==false){console.log("Sales return init validation failed"); $("#tab_3_btn").trigger('click');}
	check_field("expense_init");if(flag==false){console.log("Expense init validation failed"); $("#tab_3_btn").trigger('click');}
	if(flag==false){
		console.log("Prefix validation failed - check which field above");
		toastr["warning"]("You have Missed Something to Fillup!")
		return;
    }
    

    var this_id=this.id;

   
			if(confirm("Do You Wants to "+this_id+" Record ?")){
				e.preventDefault();
				data = new FormData($('#store-form')[0]);//form name
				/*Check XSS Code*/
				if(!xss_validation(data)){ return false; }
				
				$(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
				$("#"+this_id).attr('disabled',true);  //Enable Save or Update button
				$.ajax({
				type: 'POST',
				url: base_url+'store_profile/update_store',
				data: data,
				cache: false,
				contentType: false,
				processData: false,
				success: function(result){
      				//alert(result);return;
					
					// Check if result is JSON (currency blocking response)
					try {
						var jsonResult = JSON.parse(result);
						if (jsonResult.status === 'error') {
							// Show enhanced toast with clickable action
							showCurrencyBlockingToast(jsonResult);
							$("#"+this_id).attr('disabled',false);
							$(".overlay").remove();
							return;
						}
					} catch (e) {
						// Not JSON, continue with regular processing
					}
					
					if(result=="success")
					{
						toastr["success"]("Record Updated Successfully!");
						//return;
					}
					else if(result=="failed")
					{
						toastr["error"]("Sorry! Failed to save Record.Try again!");
					   //	return;
					}
					else
					{
						toastr["error"](result);
					}
					$("#"+this_id).attr('disabled',false);  //Enable Save or Update button
					$(".overlay").remove();
			   },
			   error: function(xhr, status, error) {
			   		console.error("AJAX Error:", status, error);
			   		toastr["error"]("An error occurred while updating. Please check the console for details.");
			   		$("#"+this_id).attr('disabled',false);  //Enable Save or Update button
					$(".overlay").remove();
			   }
			   });
		}

				//e.preventDefault

});


//On Enter Move the cursor to desigtation Id
function shift_cursor(kevent,target){

    if(kevent.keyCode==13){
		$("#"+target).focus();
    }
	
}

// Enhanced currency blocking toast with clickable action
function showCurrencyBlockingToast(jsonResult) {
    // Create custom toast with clickable action
    var toastHtml = `
        <div class="currency-blocking-toast">
            <div class="toast-content">
                <strong>${jsonResult.toast_title}</strong><br>
                ${jsonResult.toast_message}
            </div>
            <div class="toast-actions">
                <button class="btn btn-sm btn-info" onclick="showBlockingTransactionsModal()">
                    <i class="fa fa-list"></i> View Details
                </button>
            </div>
        </div>
    `;
    
    // Show toast with custom HTML
    toastr.options = {
        "closeButton": true,
        "debug": false,
        "newestOnTop": true,
        "progressBar": true,
        "positionClass": "toast-top-right",
        "preventDuplicates": false,
        "onclick": null,
        "showDuration": "300",
        "hideDuration": "1000",
        "timeOut": "8000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    };
    
    toastr.error(toastHtml, '', {
        "escapeHtml": false,
        "timeOut": "0", // Don't auto-hide
        "extendedTimeOut": "0"
    });
}

// Show detailed blocking transactions modal
function showBlockingTransactionsModal() {
    var base_url = $("#base_url").val();
    var store_id = $("#q_id").val() || getCurrentStoreId();
    
    // Show loading
    toastr.info("Loading transaction details...", "Please wait");
    
    $.ajax({
        url: base_url + 'store_profile/check_currency_blockers',
        type: 'GET',
        data: { store_id: store_id },
        dataType: 'json',
        success: function(response) {
            if (response.blocking_tables && response.blocking_tables.length > 0) {
                showBlockingTransactionsDetails(response.blocking_tables);
            } else {
                toastr.success("No blocking transactions found. You can change the currency now.");
            }
        },
        error: function() {
            toastr.error("Failed to load transaction details. Please try again.");
        }
    });
}

// Display blocking transactions in modal
function showBlockingTransactionsDetails(blockingTables) {
    var tableNames = {
        'db_sales': 'Sales Transactions',
        'db_purchase': 'Purchase Transactions', 
        'db_salesreturn': 'Sales Return Transactions',
        'db_purchasereturn': 'Purchase Return Transactions',
        'db_expense': 'Expense Transactions',
        'db_quotation': 'Quotation Transactions',
        'db_salespayments': 'Sales Payment Transactions',
        'db_purchasepayments': 'Purchase Payment Transactions',
        'db_custadvance': 'Customer Advance Transactions',
        'ac_transactions': 'Account Transactions'
    };
    
    var modalHtml = `
        <div class="modal fade" id="blockingTransactionsModal" tabindex="-1" role="dialog">
            <div class="modal-dialog modal-lg" role="document">
                <div class="modal-content">
                    <div class="modal-header bg-danger">
                        <h4 class="modal-title text-white">
                            <i class="fa fa-exclamation-triangle"></i> 
                            Currency Change Blocked
                        </h4>
                        <button type="button" class="close text-white" data-dismiss="modal">
                            <span>&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="alert alert-warning">
                            <strong>Cannot change base currency!</strong><br>
                            The following transaction tables contain data that prevents currency changes:
                        </div>
                        
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead class="bg-primary text-white">
                                    <tr>
                                        <th>Transaction Type</th>
                                        <th>Table Name</th>
                                        <th>Record Count</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
    `;
    
    blockingTables.forEach(function(table) {
        var displayName = tableNames[table.table] || table.table;
        modalHtml += `
            <tr>
                <td><strong>${displayName}</strong></td>
                <td><code>${table.table}</code></td>
                <td><span class="badge badge-warning">${table.count} records</span></td>
                <td>
                    <button class="btn btn-sm btn-info" onclick="viewTableRecords('${table.table}', ${table.count})">
                        <i class="fa fa-eye"></i> View Records
                    </button>
                </td>
            </tr>
        `;
    });
    
    modalHtml += `
                                </tbody>
                            </table>
                        </div>
                        
                        <div class="alert alert-info">
                            <strong>Solution:</strong><br>
                            To change the base currency, you need to delete all records from the above tables first.<br>
                            <small class="text-muted">Note: This action will permanently delete all transaction data.</small>
                        </div>
                        
                        <div class="text-center">
                            <button class="btn btn-danger btn-lg" onclick="clearAllTransactions()" id="clearTransactionsBtn">
                                <i class="fa fa-trash"></i> Clear All Transactions
                            </button>
                            <button class="btn btn-secondary btn-lg" data-dismiss="modal">
                                <i class="fa fa-times"></i> Cancel
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // Remove existing modal if any
    $('#blockingTransactionsModal').remove();
    
    // Add modal to body
    $('body').append(modalHtml);
    
    // Show modal
    $('#blockingTransactionsModal').modal('show');
}

// View specific table records
function viewTableRecords(tableName, recordCount) {
    var base_url = $("#base_url").val();
    var store_id = $("#q_id").val() || getCurrentStoreId();
    
    // Open new window/tab to view records
    var url = base_url + 'reports/transaction_details?table=' + tableName + '&store_id=' + store_id;
    window.open(url, '_blank');
}

// Clear all transactions (Admin only)
function clearAllTransactions() {
    if (!confirm('WARNING: This will permanently delete ALL transaction data. Are you sure you want to continue?')) {
        return;
    }
    
    if (!confirm('This action cannot be undone. Are you absolutely sure?')) {
        return;
    }
    
    var base_url = $("#base_url").val();
    var store_id = $("#q_id").val() || getCurrentStoreId();
    
    // Disable button and show loading
    $('#clearTransactionsBtn').prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Clearing...');
    
    $.ajax({
        url: base_url + 'store_profile/clear_transactions_for_currency_change',
        type: 'POST',
        data: { store_id: store_id },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                toastr.success(response.message, 'Transactions Cleared');
                $('#blockingTransactionsModal').modal('hide');
                // Refresh the page to allow currency change
                setTimeout(function() {
                    location.reload();
                }, 2000);
            } else {
                toastr.error(response.message, 'Error');
                $('#clearTransactionsBtn').prop('disabled', false).html('<i class="fa fa-trash"></i> Clear All Transactions');
            }
        },
        error: function() {
            toastr.error('Failed to clear transactions. Please try again.', 'Error');
            $('#clearTransactionsBtn').prop('disabled', false).html('<i class="fa fa-trash"></i> Clear All Transactions');
        }
    });
}

// Get current store ID (helper function)
function getCurrentStoreId() {
    // Try to get from hidden input or global variable
    return $("#q_id").val() || (typeof current_store_id !== 'undefined' ? current_store_id : 1);
}

