<div class="wrap">
    <h1>Inception H-Card Generator</h1>
    <p>Please fill out all fields below to generate your Local Business Schema.</p>
</div>

<style>
    label {
        display: block;
        margin-top: 10px;
    }
    input, textarea, select {
        width: 500px;
        padding: 8px;
        margin-top: 5px;
    }
    textarea {
        height: 100px;
    }
    button {
        margin-top: 20px;
        padding: 10px 20px;
        border: none;
        cursor: pointer;
    }
    #generateCopyContainer {
        display: flex;
        gap: 10px; /* Space between the buttons */
    }
    .output {
        margin-top: 20px;
        padding: 10px;
        background-color: #f8f9fa;
        border: 1px solid #ced4da;
    }
    .time-container {
        display: flex;
        align-items: center;
        gap: 10px;
    }
    .time-container select {
        width: auto;
    }
    .day-container {
        margin-bottom: 10px;
    }
    .time-dropdowns {
        display: none; /* Hidden by default */
    }
    .sameAsContainer {
        margin-bottom: 10px;
    }
    /* Button Customizations */
    .save-data-btn {
        background-color: #f28b82; /* Light red */
        color: white;
    }
    .copy-clipboard-btn {
        background-color: #aecbfa; /* Light blue */
        color: white;
    }
    .search-schema-btn {
        background-color: #DAB1DA; /* Light purple */
        color: white;
    }
    .add-location-btn {
        background-color: #28a745; /* Green */
        color: white;
    }
    .remove-location-btn {
        background-color: #f28b82; /* Light Red */
        color: white;
    }
    .sameAs-btn {
        background-color: #28a745; /* Default green for sameAs buttons */
        color: white;
    }
    #times {
      width: 100px;
    }
    
    input[type="text"][list="times"] {
      width: 100px;
      margin-top: 10px;
    }
    
    #monday-fields label {
      display: inline-block;
      margin-right: 10px;
    }
    
    #monday-fields input {
      display: inline-block;
      margin-right: 10px;
      vertical-align: middle;
    }
    #tuesday-fields label {
      display: inline-block;
      margin-right: 10px;
    }
    
    #tuesday-fields input {
      display: inline-block;
      margin-right: 10px;
      vertical-align: middle;
    }
    #wednesday-fields label {
      display: inline-block;
      margin-right: 10px;
    }
    
    #wednesday-fields input {
      display: inline-block;
      margin-right: 10px;
      vertical-align: middle;
    }
    #thursday-fields label {
      display: inline-block;
      margin-right: 10px;
    }
    
    #thursday-fields input {
      display: inline-block;
      margin-right: 10px;
      vertical-align: middle;
    }
    #friday-fields label {
      display: inline-block;
      margin-right: 10px;
    }
    
    #friday-fields input {
      display: inline-block;
      margin-right: 10px;
      vertical-align: middle;
    }
    #saturday-fields label {
      display: inline-block;
      margin-right: 10px;
    }
    
    #saturday-fields input {
      display: inline-block;
      margin-right: 10px;
      vertical-align: middle;
    }
    #sunday-fields label {
      display: inline-block;
      margin-right: 10px;
    }
    
    #sunday-fields input {
      display: inline-block;
      margin-right: 10px;
      vertical-align: middle;
    }
    
    .container {
        display: flex; /* Enable flexbox layout */
        flex-wrap: wrap; /* Allow flex items to wrap */
        max-width: 100%; /* Ensure the container doesn't exceed the viewport width */
    }
    
    #schemaForm {
        flex: 0 0 30%; /* Form takes up 30% of the width */
        max-width: 100%; /* Prevents the form from exceeding the viewport */
        box-sizing: border-box; /* Include padding and border in the element's total width */
    }
    
    .schemaDisplay {
        flex: 0 0 50%; /* Schema output takes up 50% of the width */
        max-width: 1000px; /* Limits the width to 1000px */
        background-color: #f9f9f9; /* Optional: background color for visibility */
        padding: 15px; /* Optional: padding for the schema output */
        border: 1px solid #ccc; /* Optional: border for the schema output */
        overflow-wrap: break-word; /* Forces long words to wrap */
        word-wrap: break-word; /* Compatibility for older browsers */
        white-space: normal; /* Ensures text wraps to the next line */
        margin-top: 20px;
    }
    
    #schemaJSONLD {
        white-space: pre-wrap; /* Ensures long text inside the pre block wraps */
    }
    
    label, input, textarea {
        max-width: 100%; /* Ensures labels and inputs do not exceed the container */
        word-wrap: break-word; /* Ensures that words break onto the next line if necessary */
        white-space: normal; /* Ensures text wraps and doesn't stay on one line */
        overflow: hidden; /* Prevents overflowing content */
    }
    
    textarea {
        resize: none; /* Optional: disable resizing of text areas */
    }
</style>

<?php
    global $wpdb;
    
    // Define the table name
    $table_name = $wpdb->prefix . 'business_info';
    
    // Fetch the most recent entry from the table
    $latest_entry = $wpdb->get_row("SELECT * FROM $table_name ORDER BY id DESC LIMIT 1");
    
    // Set default values for each field
    $business_type = '';
    $name = '';
    $url = '';
    $logo = '';
    $image = '';
    $description = '';
    $street_address = '';
    $address_locality = '';
    $address_region = '';
    $postal_code = '';
    $address_country = '';
    $latitude = '';
    $longitude = '';
    $has_map = '';
    $telephone = '';
    $opening_hours = [];
    $monday_open = '';
    $monday_close = '';
    $tuesday_open = '';
    $tuesday_close = '';
    $wednesday_open = '';
    $wednesday_close = '';
    $thursday_open = '';
    $thursday_close = '';
    $friday_open = '';
    $friday_close = '';
    $saturday_open = '';
    $saturday_close = '';
    $sunday_open = '';
    $sunday_close = '';
    $monday_open2 = '';
    $monday_close2 = '';
    $tuesday_open2 = '';
    $tuesday_close2 = '';
    $wednesday_open2 = '';
    $wednesday_close2 = '';
    $thursday_open2 = '';
    $thursday_close2 = '';
    $friday_open2 = '';
    $friday_close2 = '';
    $saturday_open2 = '';
    $saturday_close2 = '';
    $sunday_open2 = '';
    $sunday_close2 = '';
    $social_profiles_str = '';
    
    // If an entry is found, populate the fields with its values
    if ($latest_entry) {
        $business_type = $latest_entry->business_type;
        $name = $latest_entry->name;
        $url = $latest_entry->url;
        $logo = $latest_entry->logo;
        $image = $latest_entry->image;
        $description = $latest_entry->description;
        $street_address = $latest_entry->street_address;
        $address_locality = $latest_entry->address_locality;
        $address_region = $latest_entry->address_region;
        $postal_code = $latest_entry->postal_code;
        $address_country = $latest_entry->address_country;
        $latitude = $latest_entry->latitude;
        $longitude = $latest_entry->longitude;
        $has_map = $latest_entry->has_map;
        $telephone = $latest_entry->telephone;
        $social_profiles_str = $latest_entry->social_profiles;
    
        // Parse the opening hours into a usable format
        if (!empty($latest_entry->opening_hours)) {
            $opening_hours = explode(', ', $latest_entry->opening_hours);
        }
        $monday_open = $latest_entry->monday_open;
        $monday_close = $latest_entry->monday_close;
        $tuesday_open = $latest_entry->tuesday_open;
        $tuesday_close = $latest_entry->tuesday_close;
        $wednesday_open = $latest_entry->wednesday_open;
        $wednesday_close = $latest_entry->wednesday_close;
        $thursday_open = $latest_entry->thursday_open;
        $thursday_close = $latest_entry->thursday_close;
        $friday_open = $latest_entry->friday_open;
        $friday_close = $latest_entry->friday_close;
        $saturday_open = $latest_entry->saturday_open;
        $saturday_close = $latest_entry->saturday_close;
        $sunday_open = $latest_entry->sunday_open;
        $sunday_close = $latest_entry->sunday_close;
        $monday_open2 = $latest_entry->monday_open2;
        $monday_close2 = $latest_entry->monday_close2;
        $tuesday_open2 = $latest_entry->tuesday_open2;
        $tuesday_close2 = $latest_entry->tuesday_close2;
        $wednesday_open2 = $latest_entry->wednesday_open2;
        $wednesday_close2 = $latest_entry->wednesday_close2;
        $thursday_open2 = $latest_entry->thursday_open2;
        $thursday_close2 = $latest_entry->thursday_close2;
        $friday_open2 = $latest_entry->friday_open2;
        $friday_close2 = $latest_entry->friday_close2;
        $saturday_open2 = $latest_entry->saturday_open2;
        $saturday_close2 = $latest_entry->saturday_close2;
        $sunday_open2 = $latest_entry->sunday_open2;
        $sunday_close2 = $latest_entry->sunday_close2;
    }
    
    // Parse the opening hours into a usable format
    if (!empty($latest_entry->opening_hours)) {
        $opening_hours = explode(', ', $latest_entry->opening_hours);
    
        // Clear previous values to avoid appending incorrectly
        $monday_open = $monday_close = '';
        $tuesday_open = $tuesday_close = '';
        $wednesday_open = $wednesday_close = '';
        $thursday_open = $thursday_close = '';
        $friday_open = $friday_close = '';
        $saturday_open = $saturday_close = '';
        $sunday_open = $sunday_close = '';
    
        foreach ($opening_hours as $hours) {
            list($day, $time_sets) = explode(' ', $hours, 2);
            $time_ranges = explode(', ', $time_sets); // Split multiple time ranges
    
            foreach ($time_ranges as $time_range) {
                list($open, $close) = explode(' - ', $time_range);
    
                // Assign to the correct day
                switch ($day) {
                    case 'Mo':
                        $monday_open = $open;
                        $monday_close = $close;
                        break;
                    case 'Tu':
                        $tuesday_open = $open;
                        $tuesday_close = $close;
                        break;
                    case 'We':
                        $wednesday_open = $open;
                        $wednesday_close = $close;
                        break;
                    case 'Th':
                        $thursday_open = $open;
                        $thursday_close = $close;
                        break;
                    case 'Fr':
                        $friday_open = $open;
                        $friday_close = $close;
                        break;
                    case 'Sa':
                        $saturday_open = $open;
                        $saturday_close = $close;
                        break;
                    case 'Su':
                        $sunday_open = $open;
                        $sunday_close = $close;
                        break;
                }
            }
        }
    }
?>

<?php
// Handle form submission to add a new location
if (isset($_POST['add_location_btn'])) {
    // Check if the location name is provided
    if (!empty($_POST['location_name'])) {
        $location_name = sanitize_text_field($_POST['location_name']);
    } else {
        $location_name = "Additional Location"; // Default name if not provided
    }

    global $wpdb;
    $table_prefix = $wpdb->prefix . 'business_info';
    $next_index = 1;

    // Find the next available table number
    while ($wpdb->get_var("SHOW TABLES LIKE '{$table_prefix}{$next_index}'") === "{$table_prefix}{$next_index}") {
        $next_index++;
    }

    // Create the new location table
    $new_table_name = "{$table_prefix}{$next_index}";
    $charset_collate = $wpdb->get_charset_collate();
    $sql = "CREATE TABLE {$new_table_name} (
        location varchar(255) NOT NULL,
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        business_type varchar(100) NOT NULL,
        name varchar(255) NOT NULL,
        url varchar(255) NOT NULL,
        logo varchar(255),
        image varchar(255),
        description text,
        street_address varchar(255),
        address_locality varchar(100),
        address_region varchar(100),
        postal_code varchar(20),
        address_country varchar(100),
        latitude varchar(50),
        longitude varchar(50),
        has_map varchar(255),
        telephone varchar(50),
        opening_hours text,
        monday_open varchar(50),
        monday_close varchar(50),
        tuesday_open varchar(50),
        tuesday_close varchar(50),
        wednesday_open varchar(50),
        wednesday_close varchar(50),
        thursday_open varchar(50),
        thursday_close varchar(50),
        friday_open varchar(50),
        friday_close varchar(50),
        saturday_open varchar(50),
        saturday_close varchar(50),
        sunday_open varchar(50),
        sunday_close varchar(50),
        monday_open2 varchar(50),
        monday_close2 varchar(50),
        tuesday_open2 varchar(50),
        tuesday_close2 varchar(50),
        wednesday_open2 varchar(50),
        wednesday_close2 varchar(50),
        thursday_open2 varchar(50),
        thursday_close2 varchar(50),
        friday_open2 varchar(50),
        friday_close2 varchar(50),
        saturday_open2 varchar(50),
        saturday_close2 varchar(50),
        sunday_open2 varchar(50),
        sunday_close2 varchar(50),
        social_profiles text,
        PRIMARY KEY  (id)
        ) $charset_collate;";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);

    // Insert the location name into the new table's 'location' column
    $wpdb->insert($new_table_name, [
        'location' => $location_name, // Store the location name in the 'location' column
    ]);

    // Store the location name in a transient for later use in the dropdown
    set_transient('location_name_' . $next_index, $location_name, 0); // Store it temporarily

    // Optionally, redirect to refresh the page
    wp_redirect($_SERVER['REQUEST_URI']);
    exit;
}
?>

<script type="text/javascript">
    // Pass PHP values to JavaScript
    const lastEntry = <?php echo json_encode([
        'business_type' => $business_type,
        'name' => $name,
        'url' => $url,
        'logo' => $logo,
        'image' => $image,
        'description' => $description,
        'street_address' => $street_address,
        'address_locality' => $address_locality,
        'address_region' => $address_region,
        'postal_code' => $postal_code,
        'address_country' => $address_country,
        'latitude' => $latitude,
        'longitude' => $longitude,
        'has_map' => $has_map,
        'telephone' => $telephone,
        'monday_open' => $monday_open,
        'monday_close' => $monday_close,
        'tuesday_open' => $tuesday_open,
        'tuesday_close' => $tuesday_close,
        'wednesday_open' => $wednesday_open,
        'wednesday_close' => $wednesday_close,
        'thursday_open' => $thursday_open,
        'thursday_close' => $thursday_close,
        'friday_open' => $friday_open,
        'friday_close' => $friday_close,
        'saturday_open' => $saturday_open,
        'saturday_close' => $saturday_close,
        'sunday_open' => $sunday_open,
        'sunday_close' => $sunday_close,
        'monday_open2' => $monday_open2,
        'monday_close2' => $monday_close2,
        'tuesday_open2' => $tuesday_open2,
        'tuesday_close2' => $tuesday_close2,
        'wednesday_open2' => $wednesday_open2,
        'wednesday_close2' => $wednesday_close2,
        'thursday_open2' => $thursday_open2,
        'thursday_close2' => $thursday_close2,
        'friday_open2' => $friday_open2,
        'friday_close2' => $friday_close2,
        'saturday_open2' => $saturday_open2,
        'saturday_close2' => $saturday_close2,
        'sunday_open2' => $sunday_open2,
        'sunday_close2' => $sunday_close2,
        'social_profiles' => $social_profiles_str
    ]); ?>;
</script>

<div class="container">
    <form method="post" action="" id="schemaForm">
        <div id="additionalLocation">
            <!-- Location Name Textbox -->
            <input type="text" id="location_name" name="location_name" style="width:250px; margin-right: 5px" placeholder="Enter Additional Location Name" />
            
            <!-- Add Location Button -->
            <button type="submit" class="add-location-btn" name="add_location_btn">Add A Location</button>
            
            <!-- Remove Location Button (Initially Hidden) -->
            <button type="button" class="remove-location-btn" name="remove_location_btn" style="display: none;" onclick="confirmRemoveLocation()">Remove Location</button>
            
            <?php
            global $wpdb;
            $table_prefix = $wpdb->prefix . 'business_info';
            $location_tables = [];
            $location_data = [];
            $next_index = 1;
            
            // Fetch data for all tables
            while ($wpdb->get_var("SHOW TABLES LIKE '{$table_prefix}{$next_index}'") === "{$table_prefix}{$next_index}") {
                $table_name = $table_prefix . $next_index;
                $location_tables[] = $table_name;
            
                // Get the most recent entry for this location
                $latest_entry = $wpdb->get_row("SELECT * FROM $table_name ORDER BY id DESC LIMIT 1", ARRAY_A);
                if ($latest_entry) {
                    $location_data[$table_name] = $latest_entry;
                }
                $next_index++;
            }
            
            // Display the dropdown
            if (!empty($location_tables)) {
                echo '<select name="additional_location" id="additional_location">';
                echo '<option value="">Select Location</option>'; // Default option
            
                foreach ($location_tables as $table_name) {
                    $location_name = get_transient('location_name_' . str_replace($table_prefix, '', $table_name)) ?: "Location " . str_replace($table_prefix, '', $table_name);
                    // Get the number (index) and location name
                    $location_number = str_replace($table_prefix, '', $table_name);
                    echo '<option value="' . $table_name . '">' . $location_number . ' - ' . $location_name . '</option>';
                }
            
                echo '</select>';
            }
            ?>
            
            <script>
                // Embed location data in JavaScript
                const locationData = <?php echo json_encode($location_data); ?>;
            </script>
        </div>

        <div id="generateCopyContainer">
            <input type="hidden" name="hCard" id="hCardInput">
            <button type="submit" class="save-data-btn" name="submit_schema_form">Save Data</button>
            <button type="button" class="copy-clipboard-btn" onclick="copySchemaToClipboard()">Copy to Clipboard</button>
            <button type="submit" name="generate_schema" class="search-schema-btn">Check Site's Existing H-Card</button>
        </div>

        <label for="businessType">Select Local Business Type:</label>
        <select id="businessType" aria-label="Select Business Type" name="businessType">
            <option value="ProfessionalService" <?php selected($business_type, 'ProfessionalService'); ?>>Professional Service</option>
            <option value="Dentist" <?php selected($business_type, 'Dentist'); ?>>Dentist</option>
            <option value="Optician" <?php selected($business_type, 'Optician'); ?>>Optician</option>
            <option value="Store" <?php selected($business_type, 'Store'); ?>>Store</option>
            <option value="Restaurant" <?php selected($business_type, 'Restaurant'); ?>>Restaurant</option>
        </select>
        
        <label for="name">Name:</label>
        <input type="text" name="name" value="<?php echo esc_attr($name); ?>" />
    
        <label for="url">URL:</label>
        <input type="url" name="url" value="<?php echo esc_attr($url); ?>" />
    
        <label for="logo">Logo URL:</label>
        <input type="text" name="logo" value="<?php echo esc_attr($logo); ?>" />
    
        <label for="image">Image URL:</label>
        <input type="text" name="image" value="<?php echo esc_attr($image); ?>" />
    
        <label for="description">Description:</label>
        <textarea name="description" id="description" oninput="autoResize(this)"><?php echo esc_textarea($description); ?></textarea>
    
        <label for="street_address">Street Address:</label>
        <input type="text" name="street_address" value="<?php echo esc_attr($street_address); ?>" />
        
        <label for="address_locality">Address Locality (City):</label>
        <input type="text" name="address_locality" value="<?php echo esc_attr($address_locality); ?>" />
        
        <label for="address_region">Address Region (State):</label>
        <input type="text" name="address_region" value="<?php echo esc_attr($address_region); ?>" />
        
        <label for="postal_code">Postal Code (ZIP):</label>
        <input type="text" name="postal_code" value="<?php echo esc_attr($postal_code); ?>" />
        
        <label for="address_country">Address Country:</label>
        <input type="text" name="address_country" value="<?php echo esc_attr($address_country); ?>" />
    
        <label for="latitude">Latitude:</label>
        <input type="text" name="latitude" value="<?php echo esc_attr($latitude); ?>" />
    
        <label for="longitude">Longitude:</label>
        <input type="text" name="longitude" value="<?php echo esc_attr($longitude); ?>" />
    
        <label for="has_map">Has Map URL:</label>
        <input type="text" name="has_map" value="<?php echo esc_attr($has_map); ?>" />
    
        <label for="telephone">Telephone:</label>
        <input type="text" name="telephone" value="<?php echo esc_attr($telephone); ?>" />
    
        <h2>Opening Hours</h2>
        <div>
            <label><input type="checkbox" name="monday" id="monday" onclick="toggleFields('monday')" <?php echo !empty($monday_open) ? 'checked' : ''; ?>> <strong>Monday</strong></label>
            <div id="monday-fields" style="display:none;">
                <label>Open:</label>
                <input type="text" id="monday-open" name="monday-open" list="times" value="<?php echo esc_attr($monday_open); ?>" onfocus="showDropdown(this)">
                <label>Close:</label>
                <input type="text" name="monday-close" id="monday-close" list="times" value="<?php echo esc_attr($monday_close); ?>" onfocus="showDropdown(this)">
                <label><input type="checkbox" id="monday-additional" onclick="toggleAdditionalHours('monday')" <?php echo !empty($monday_open2) ? 'checked' : ''; ?> /> Additional Hours</label>
                <div id="monday-additional-fields" style="display:none;">
                    <label>Open 2:</label>
                    <input type="text" id="monday-open2" name="monday-open2" list="times" value="<?php echo esc_attr($monday_open2); ?>" onfocus="showDropdown(this)">
                    <label>Close 2:</label>
                    <input type="text" id="monday-close2" name="monday-close2" list="times" value="<?php echo esc_attr($monday_close2); ?>" onfocus="showDropdown(this)">
                </div>
            </div>
        </div>
        <div>
            <label><input type="checkbox" name="tuesday" id="tuesday" onclick="toggleFields('tuesday')" <?php echo !empty($tuesday_open) ? 'checked' : ''; ?>> <strong>Tuesday</strong></label>
            <div id="tuesday-fields" style="display:none;">
                <label>Open:</label>
                <input type="text" id="tuesday-open" name="tuesday-open" list="times" value="<?php echo esc_attr($tuesday_open); ?>" onfocus="showDropdown(this)">
                <label>Close:</label>
                <input type="text" name="tuesday-close" id="tuesday-close" list="times" value="<?php echo esc_attr($tuesday_close); ?>" onfocus="showDropdown(this)">
                <label><input type="checkbox" id="tuesday-additional" onclick="toggleAdditionalHours('tuesday')" <?php echo !empty($tuesday_open2) ? 'checked' : ''; ?> /> Additional Hours</label>
                <div id="tuesday-additional-fields" style="display:none;">
                    <label>Open 2:</label>
                    <input type="text" id="tuesday-open2" name="tuesday-open2" list="times" value="<?php echo esc_attr($tuesday_open2); ?>" onfocus="showDropdown(this)">
                    <label>Close 2:</label>
                    <input type="text" id="tuesday-close2" name="tuesday-close2" list="times" value="<?php echo esc_attr($tuesday_close2); ?>" onfocus="showDropdown(this)">
                </div>
            </div>
        </div>
        <div>
            <label><input type="checkbox" name="wednesday" id="wednesday" onclick="toggleFields('wednesday')" <?php echo !empty($wednesday_open) ? 'checked' : ''; ?>> <strong>Wednesday</strong></label>
            <div id="wednesday-fields" style="display:none;">
                <label>Open:</label>
                <input type="text" id="wednesday-open" name="wednesday-open" list="times" value="<?php echo esc_attr($wednesday_open); ?>" onfocus="showDropdown(this)">
                <label>Close:</label>
                <input type="text" name="wednesday-close" id="wednesday-close" list="times" value="<?php echo esc_attr($wednesday_close); ?>" onfocus="showDropdown(this)">
                <label><input type="checkbox" id="wednesday-additional" onclick="toggleAdditionalHours('wednesday')" <?php echo !empty($wednesday_open2) ? 'checked' : ''; ?> /> Additional Hours</label>
                <div id="wednesday-additional-fields" style="display:none;">
                    <label>Open 2:</label>
                    <input type="text" id="wednesday-open2" name="wednesday-open2" list="times" value="<?php echo esc_attr($wednesday_open2); ?>" onfocus="showDropdown(this)">
                    <label>Close 2:</label>
                    <input type="text" id="wednesday-close2" name="wednesday-close2" list="times" value="<?php echo esc_attr($wednesday_close2); ?>" onfocus="showDropdown(this)">
                </div>
            </div>
        </div>
        <div>
            <label><input type="checkbox" name="thursday" id="thursday" onclick="toggleFields('thursday')" <?php echo !empty($thursday_open) ? 'checked' : ''; ?>> <strong>Thursday</strong></label>
            <div id="thursday-fields" style="display:none;">
                <label>Open:</label>
                <input type="text" id="thursday-open" name="thursday-open" list="times" value="<?php echo esc_attr($thursday_open); ?>" onfocus="showDropdown(this)">
                <label>Close:</label>
                <input type="text" name="thursday-close" id="thursday-close" list="times" value="<?php echo esc_attr($thursday_close); ?>" onfocus="showDropdown(this)">
                <label><input type="checkbox" id="thursday-additional" onclick="toggleAdditionalHours('thursday')" <?php echo !empty($thursday_open2) ? 'checked' : ''; ?> /> Additional Hours</label>
                <div id="thursday-additional-fields" style="display:none;">
                    <label>Open 2:</label>
                    <input type="text" id="thursday-open2" name="thursday-open2" list="times" value="<?php echo esc_attr($thursday_open2); ?>" onfocus="showDropdown(this)">
                    <label>Close 2:</label>
                    <input type="text" id="thursday-close2" name="thursday-close2" list="times" value="<?php echo esc_attr($thursday_close2); ?>" onfocus="showDropdown(this)">
                </div>
            </div>
        </div>
        <div>
            <label><input type="checkbox" name="friday" id="friday" onclick="toggleFields('friday')" <?php echo !empty($friday_open) ? 'checked' : ''; ?>> <strong>Friday</strong></label>
            <div id="friday-fields" style="display:none;">
                <label>Open:</label>
                <input type="text" id="friday-open" name="friday-open" list="times" value="<?php echo esc_attr($friday_open); ?>" onfocus="showDropdown(this)">
                <label>Close:</label>
                <input type="text" name="friday-close" id="friday-close" list="times" value="<?php echo esc_attr($friday_close); ?>" onfocus="showDropdown(this)">
                <label><input type="checkbox" id="friday-additional" onclick="toggleAdditionalHours('friday')" <?php echo !empty($friday_open2) ? 'checked' : ''; ?> /> Additional Hours</label>
                <div id="friday-additional-fields" style="display:none;">
                    <label>Open 2:</label>
                    <input type="text" id="friday-open2" name="friday-open2" list="times" value="<?php echo esc_attr($friday_open2); ?>" onfocus="showDropdown(this)">
                    <label>Close 2:</label>
                    <input type="text" id="friday-close2" name="friday-close2" list="times" value="<?php echo esc_attr($friday_close2); ?>" onfocus="showDropdown(this)">
                </div>
            </div>
        </div>
        <div>
            <label><input type="checkbox" name="saturday" id="saturday" onclick="toggleFields('saturday')" <?php echo !empty($saturday_open) ? 'checked' : ''; ?>> <strong>Saturday</strong></label>
            <div id="saturday-fields" style="display:none;">
                <label>Open:</label>
                <input type="text" id="saturday-open" name="saturday-open" list="times" value="<?php echo esc_attr($saturday_open); ?>" onfocus="showDropdown(this)">
                <label>Close:</label>
                <input type="text" name="saturday-close" id="saturday-close" list="times" value="<?php echo esc_attr($saturday_close); ?>" onfocus="showDropdown(this)">
                <label><input type="checkbox" id="saturday-additional" onclick="toggleAdditionalHours('saturday')" <?php echo !empty($saturday_open2) ? 'checked' : ''; ?> /> Additional Hours</label>
                <div id="saturday-additional-fields" style="display:none;">
                    <label>Open 2:</label>
                    <input type="text" id="saturday-open2" name="saturday-open2" list="times" value="<?php echo esc_attr($saturday_open2); ?>" onfocus="showDropdown(this)">
                    <label>Close 2:</label>
                    <input type="text" id="saturday-close2" name="saturday-close2" list="times" value="<?php echo esc_attr($saturday_close2); ?>" onfocus="showDropdown(this)">
                </div>
            </div>
        </div>
        <div>
            <label><input type="checkbox" name="sunday" id="sunday" onclick="toggleFields('sunday')" <?php echo !empty($sunday_open) ? 'checked' : ''; ?>> <strong>Sunday</strong></label>
            <div id="sunday-fields" style="display:none;">
                <label>Open:</label>
                <input type="text" id="sunday-open" name="sunday-open" list="times" value="<?php echo esc_attr($sunday_open); ?>" onfocus="showDropdown(this)">
                <label>Close:</label>
                <input type="text" name="sunday-close" id="sunday-close" list="times" value="<?php echo esc_attr($sunday_close); ?>" onfocus="showDropdown(this)">
                <label><input type="checkbox" id="sunday-additional" onclick="toggleAdditionalHours('sunday')" <?php echo !empty($sunday_open2) ? 'checked' : ''; ?> /> Additional Hours</label>
                <div id="sunday-additional-fields" style="display:none;">
                    <label>Open 2:</label>
                    <input type="text" id="sunday-open2" name="sunday-open2" list="times" value="<?php echo esc_attr($sunday_open2); ?>" onfocus="showDropdown(this)">
                    <label>Close 2:</label>
                    <input type="text" id="sunday-close2" name="sunday-close2" list="times" value="<?php echo esc_attr($sunday_close2); ?>" onfocus="showDropdown(this)">
                </div>
            </div>
        </div>

        <!-- Data list for time selections (half-hour increments) -->
        <datalist id="times">
          <option value="00:00">
          <option value="00:30">
          <option value="01:00">
          <option value="01:30">
          <option value="02:00">
          <option value="02:30">
          <option value="03:00">
          <option value="03:30">
          <option value="04:00">
          <option value="04:30">
          <option value="05:00">
          <option value="05:30">
          <option value="06:00">
          <option value="06:30">
          <option value="07:00">
          <option value="07:30">
          <option value="08:00">
          <option value="08:30">
          <option value="09:00">
          <option value="09:30">
          <option value="10:00">
          <option value="10:30">
          <option value="11:00">
          <option value="11:30">
          <option value="12:00">
          <option value="12:30">
          <option value="13:00">
          <option value="13:30">
          <option value="14:00">
          <option value="14:30">
          <option value="15:00">
          <option value="15:30">
          <option value="16:00">
          <option value="16:30">
          <option value="17:00">
          <option value="17:30">
          <option value="18:00">
          <option value="18:30">
          <option value="19:00">
          <option value="19:30">
          <option value="20:00">
          <option value="20:30">
          <option value="21:00">
          <option value="21:30">
          <option value="22:00">
          <option value="22:30">
          <option value="23:00">
          <option value="23:30">
        </datalist>
    
        <h2>Social Profiles</h2>
        <div id="sameAsContainer">
            <?php 
            // Assuming the 'social_profiles' field contains comma-separated URLs
            $sameAsUrls = !empty($social_profiles_str) ? explode(',', $social_profiles_str) : [];
            
            foreach ($sameAsUrls as $index => $url): ?>
                <div class="sameAsContainer" id="sameAs<?php echo $index + 1; ?>">
                    <label for="sameAsInput<?php echo $index + 1; ?>">sameAs URL <?php echo $index + 1; ?>:</label>
                    <input type="url" id="sameAsInput<?php echo $index + 1; ?>" name="sameAsInput<?php echo $index + 1; ?>" value="<?php echo esc_url($url); ?>" oninput="updateSchema()">
                </div>
            <?php endforeach; ?>
        </div>
        
        <button type="button" class="sameAs-btn" id="addSameAsBtn">Add sameAs</button>
        <button type="button" class="sameAs-btn" id="removeSameAsBtn">Remove sameAs</button>
        <input type="hidden" name="domain" value="<?php echo esc_url(home_url()); ?>">
    </form>
        
    <form id="removeLocationForm" method="POST" style="display:none;">
        <input type="hidden" name="remove_location" id="remove_location">
        <input type="submit" name="submit_remove_location" value="Remove Location">
    </form>

    <!-- Schema Output Section -->
    <div class="schemaDisplay">
        <h2>Your Local Business Schema:</h2>
        <div id="schemaOutput">
            <pre id="schemaJSONLD"></pre>
        </div>
    </div>
</div>

<script>
    document.addEventListener("DOMContentLoaded", function () {
        const dropdown = document.getElementById("additional_location");
    
        if (dropdown) {
            dropdown.addEventListener("change", function () {
                const selectedLocation = this.value; // Get the selected table name
                const fields = locationData[selectedLocation]; // Get the data for the selected location
        
                const businessTypeDropdown = document.getElementById("businessType");
        
                // Clear the location_name field if "Select Location" is chosen
                const locationNameField = document.getElementById("location_name");
                if (selectedLocation === "default" || !fields) {
                    locationNameField.value = ""; // Clear the field
                    
                    // Reset form fields to the last entry values
                    document.querySelector('input[name="name"]').value = lastEntry.name || '';
                    document.querySelector('input[name="url"]').value = lastEntry.url || '';
                    document.querySelector('input[name="logo"]').value = lastEntry.logo || '';
                    document.querySelector('input[name="image"]').value = lastEntry.image || '';
                    document.querySelector('textarea[name="description"]').value = lastEntry.description || '';
                    document.querySelector('input[name="street_address"]').value = lastEntry.street_address || '';
                    document.querySelector('input[name="address_locality"]').value = lastEntry.address_locality || '';
                    document.querySelector('input[name="address_region"]').value = lastEntry.address_region || '';
                    document.querySelector('input[name="postal_code"]').value = lastEntry.postal_code || '';
                    document.querySelector('input[name="address_country"]').value = lastEntry.address_country || '';
                    document.querySelector('input[name="latitude"]').value = lastEntry.latitude || '';
                    document.querySelector('input[name="longitude"]').value = lastEntry.longitude || '';
                    document.querySelector('input[name="has_map"]').value = lastEntry.has_map || '';
                    document.querySelector('input[name="telephone"]').value = lastEntry.telephone || '';
        
                    // Restore the opening hours and social profiles from the wp_business_info table
                    restoreOpeningHours(lastEntry);
                    restoreSocialProfiles(lastEntry);
                    
                    // Restore the business type in the dropdown
                    businessTypeDropdown.value = lastEntry.business_type || 'ProfessionalService'; // Default to 'ProfessionalService' if no business type
                } else {
                    locationNameField.value = fields.name || ""; // Update the field with the selected location name
        
                    // Update other fields with location data
                    document.querySelector('input[name="name"]').value = fields.name || "";
                    document.querySelector('input[name="url"]').value = fields.url || "";
                    document.querySelector('input[name="logo"]').value = fields.logo || "";
                    document.querySelector('input[name="image"]').value = fields.image || "";
                    document.querySelector('textarea[name="description"]').value = fields.description || "";
                    document.querySelector('input[name="street_address"]').value = fields.street_address || "";
                    document.querySelector('input[name="address_locality"]').value = fields.address_locality || "";
                    document.querySelector('input[name="address_region"]').value = fields.address_region || "";
                    document.querySelector('input[name="postal_code"]').value = fields.postal_code || "";
                    document.querySelector('input[name="address_country"]').value = fields.address_country || "";
                    document.querySelector('input[name="latitude"]').value = fields.latitude || "";
                    document.querySelector('input[name="longitude"]').value = fields.longitude || "";
                    document.querySelector('input[name="has_map"]').value = fields.has_map || "";
                    document.querySelector('input[name="telephone"]').value = fields.telephone || "";
        
                    // Update opening hours fields
                    updateOpeningHours(fields);
                    
                    // Update business type dropdown
                    businessTypeDropdown.value = fields.business_type || 'ProfessionalService'; // Default to 'ProfessionalService' if no business type
        
                    // Pull social profiles from the location data
                    const socialProfilesContainer = document.getElementById("sameAsContainer");
                    socialProfilesContainer.innerHTML = ''; // Clear existing social profiles
        
                    const socialProfiles = fields.social_profiles ? fields.social_profiles.split(', ') : [];
                    socialProfiles.forEach((url, index) => {
                        const sameAsDiv = document.createElement("div");
                        sameAsDiv.classList.add("sameAsContainer");
                        sameAsDiv.id = "sameAs" + (index + 1);
        
                        const label = document.createElement("label");
                        label.setAttribute("for", "sameAsInput" + (index + 1));
                        label.textContent = `sameAs URL ${index + 1}:`;
        
                        const input = document.createElement("input");
                        input.type = "url";
                        input.id = "sameAsInput" + (index + 1);
                        input.name = "sameAsInput" + (index + 1);
                        input.value = url;
                        input.setAttribute("oninput", "updateSchema()");
        
                        sameAsDiv.appendChild(label);
                        sameAsDiv.appendChild(input);
                        socialProfilesContainer.appendChild(sameAsDiv);
                    });
                }
            });
        
            // Function to restore the opening hours from lastEntry (default location)
            function restoreOpeningHours(entry) {
                const days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
        
                days.forEach(function(day) {
                    // Restore opening and closing times for primary hours
                    document.getElementById(`${day}-open`).value = entry[`${day}_open`] || '';
                    document.getElementById(`${day}-close`).value = entry[`${day}_close`] || '';
        
                    // Restore secondary opening and closing times (if any)
                    document.getElementById(`${day}-open2`).value = entry[`${day}_open2`] || '';
                    document.getElementById(`${day}-close2`).value = entry[`${day}_close2`] || '';
        
                    // Set checkbox for additional hours
                    const additionalCheckbox = document.getElementById(`${day}-additional`);
                    if (entry[`${day}_open2`] && entry[`${day}_close2`]) {
                        additionalCheckbox.checked = true;
                        toggleAdditionalHours(day); // Show the additional fields
                    } else {
                        additionalCheckbox.checked = false;
                        toggleAdditionalHours(day); // Hide the additional fields
                    }
        
                    // Check if primary hours are available (open and close times for the day)
                    const primaryOpen = entry[`${day}_open`] || '';
                    const primaryClose = entry[`${day}_close`] || '';
        
                    // If primary hours are not set, uncheck the day checkbox
                    const checkbox = document.getElementById(day);
                    if (!primaryOpen || !primaryClose) {
                        checkbox.checked = false;
                        toggleFields(day); // Hide the fields for that day
                    } else {
                        checkbox.checked = true;
                        toggleFields(day); // Show the fields for that day
                    }
        
                    // If the primary checkbox is unchecked, clear the hours for that day
                    if (!checkbox.checked) {
                        clearHours(day);
                    }
                });
            }
    
            // Function to reset the opening hours
            function resetOpeningHours() {
                const days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
                days.forEach(function(day) {
                    // Reset the hours for both primary and secondary
                    document.getElementById(`${day}-open`).value = '';
                    document.getElementById(`${day}-close`).value = '';
                    document.getElementById(`${day}-open2`).value = '';
                    document.getElementById(`${day}-close2`).value = '';
        
                    // Also uncheck the additional hours checkboxes
                    const additionalCheckbox = document.getElementById(`${day}-additional`);
                    additionalCheckbox.checked = false;
                    toggleAdditionalHours(day); // Hide additional fields
                });
            }
            
            // Function to restore the social profiles from lastEntry (default location)
            function restoreSocialProfiles(entry) {
                const socialProfilesContainer = document.getElementById("sameAsContainer");
                socialProfilesContainer.innerHTML = ''; // Clear existing social profiles
        
                const socialProfiles = entry.social_profiles ? entry.social_profiles.split(', ') : [];
                socialProfiles.forEach((url, index) => {
                    const sameAsDiv = document.createElement("div");
                    sameAsDiv.classList.add("sameAsContainer");
                    sameAsDiv.id = "sameAs" + (index + 1);
        
                    const label = document.createElement("label");
                    label.setAttribute("for", "sameAsInput" + (index + 1));
                    label.textContent = `sameAs URL ${index + 1}:`;
        
                    const input = document.createElement("input");
                    input.type = "url";
                    input.id = "sameAsInput" + (index + 1);
                    input.name = "sameAsInput" + (index + 1);
                    input.value = url;
                    input.setAttribute("oninput", "updateSchema()");
        
                    sameAsDiv.appendChild(label);
                    sameAsDiv.appendChild(input);
                    socialProfilesContainer.appendChild(sameAsDiv);
                });
            }
        
            // Function to update opening hours based on the selected location data
            function updateOpeningHours(fields) {
                const days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
            
                days.forEach(function(day) {
                    // Update opening and closing times for primary hours
                    document.getElementById(`${day}-open`).value = fields[`${day}_open`] || '';
                    document.getElementById(`${day}-close`).value = fields[`${day}_close`] || '';
            
                    // Update secondary opening and closing times (if any)
                    document.getElementById(`${day}-open2`).value = fields[`${day}_open2`] || '';
                    document.getElementById(`${day}-close2`).value = fields[`${day}_close2`] || '';
            
                    // Set checkbox for additional hours
                    const additionalCheckbox = document.getElementById(`${day}-additional`);
                    if (fields[`${day}_open2`] && fields[`${day}_close2`]) {
                        additionalCheckbox.checked = true;
                        toggleAdditionalHours(day); // Show the additional fields
                    } else {
                        additionalCheckbox.checked = false;
                        toggleAdditionalHours(day); // Hide the additional fields
                    }
            
                    // Check if primary hours are available (open and close times for the day)
                    const primaryOpen = fields[`${day}_open`] || '';
                    const primaryClose = fields[`${day}_close`] || '';
            
                    // If primary hours are not set, uncheck the day checkbox
                    const checkbox = document.getElementById(day);
                    if (!primaryOpen || !primaryClose) {
                        checkbox.checked = false;
                        toggleFields(day); // Hide the fields for that day
                    } else {
                        checkbox.checked = true;
                        toggleFields(day); // Show the fields for that day
                    }
                    
                    // If the primary checkbox is unchecked, clear the hours for that day
                    if (!checkbox.checked) {
                        clearHours(day);
                    }
                });
            }
        } else {
        // Handle the absence of the dropdown
        console.warn("The 'additional_location' dropdown does not exist on the page, likely because it's a single location.");
        }
    });

    document.addEventListener('DOMContentLoaded', function() {
        const locationDropdown = document.getElementById('additional_location');
        const removeLocationButton = document.querySelector('.remove-location-btn');

        // Function to toggle the visibility of the remove location button
        function toggleRemoveButton() {
            if (locationDropdown.value && locationDropdown.value !== '') {
                removeLocationButton.style.display = 'inline-block'; // Show button if additional location is selected
            } else {
                removeLocationButton.style.display = 'none'; // Hide button if default location is selected
            }
        }
        
        if (locationDropdown) {
        // Add event listener for when the dropdown value changes
        locationDropdown.addEventListener('change', toggleRemoveButton);

        // Run the toggle function once on page load to ensure the button is hidden initially
        toggleRemoveButton();
        
        } else {
            // Handle the absence of the dropdown
            console.warn("The 'additional_location' dropdown does not exist on the page, likely because it's a single location.");
        }
    });

    // Function to confirm location removal
    function confirmRemoveLocation() {
        const location = document.getElementById('additional_location').value;
        if (!location) {
            alert('Please select a location to remove.');
            return;
        }

        const confirmDelete = confirm('Are you sure you want to remove this location? This action cannot be undone.');
        if (confirmDelete) {
            // Set the value of the hidden input field
            document.getElementById('remove_location').value = location;

            // Submit the form to process the deletion
            document.getElementById('removeLocationForm').submit();
        }
    }

    // Add event listener to some fields
    document.getElementById('businessType').addEventListener('change', updateSchema);
    
    document.addEventListener('DOMContentLoaded', function() {
        const descriptionField = document.querySelector('textarea[name="description"]');
        
        // Add input event listener to the description field
        descriptionField.addEventListener('input', updateSchema);
    });
    
    // Function to auto-resize the description textarea
    function autoResize(textarea) {
        textarea.style.height = 'auto'; // Reset the height to auto to recalculate
        textarea.style.height = textarea.scrollHeight + 'px'; // Set the height to match the scroll height
    }
    
    // Initialize autoResize for the description field on page load
    document.addEventListener('DOMContentLoaded', function() {
        const descriptionField = document.getElementById('description');
        autoResize(descriptionField); // Adjust initial size if there's pre-filled content
    });
    
    let currentSchema = {}; // Global variable to hold the current schema
    
    // Function to update schema based on form fields and selected location
    function updateSchema() {
        const businessType = document.getElementById('businessType').value;
        const name = document.querySelector('input[name="name"]').value;
        const url = document.querySelector('input[name="url"]').value;
        const logo = document.querySelector('input[name="logo"]').value;
        const image = document.querySelector('input[name="image"]').value;
        const description = document.querySelector('textarea[name="description"]').value.replace(/\n/g, '<br>');
        const streetAddress = document.querySelector('input[name="street_address"]').value;
        const addressLocality = document.querySelector('input[name="address_locality"]').value;
        const addressRegion = document.querySelector('input[name="address_region"]').value;
        const postalCode = document.querySelector('input[name="postal_code"]').value;
        const addressCountry = document.querySelector('input[name="address_country"]').value;
        const latitude = document.querySelector('input[name="latitude"]').value;
        const longitude = document.querySelector('input[name="longitude"]').value;
        const hasMap = document.querySelector('input[name="has_map"]').value;
        const telephone = document.querySelector('input[name="telephone"]').value;
    
        // Check if the dropdown exists before accessing its value
        const dropdown = document.getElementById('additional_location');
        const selectedLocation = dropdown ? dropdown.value : "default";
    
        // If no location is selected (default state), use the data from wp_business_info (i.e., form fields' current values)
        let locationData = {};
    
        // If a specific location is selected, override with that location's data (this would be pulled from your location data)
        if (selectedLocation !== "default") {
            locationData = locationData[selectedLocation] || {}; // Fetch the data for the selected location
        } else {
            // If default is selected, use the form fields' values to build the schema
            locationData = {
                name: name,
                street_address: streetAddress,
                address_locality: addressLocality,
                address_region: addressRegion,
                postal_code: postalCode,
                address_country: addressCountry,
                latitude: latitude,
                longitude: longitude,
                telephone: telephone,
                url: url,
                logo: logo,
                image: image,
                description: description,
                has_map: hasMap
            };
        }
    
        // Override form field values with location-specific values if any exist
        const locationName = locationData.name || name;
        const locationStreetAddress = locationData.street_address || streetAddress;
        const locationAddressLocality = locationData.address_locality || addressLocality;
        const locationAddressRegion = locationData.address_region || addressRegion;
        const locationPostalCode = locationData.postal_code || postalCode;
        const locationAddressCountry = locationData.address_country || addressCountry;
        const locationLatitude = locationData.latitude || latitude;
        const locationLongitude = locationData.longitude || longitude;
        const locationTelephone = locationData.telephone || telephone;
        const locationUrl = locationData.url || url;
        const locationLogo = locationData.logo || logo;
        const locationImage = locationData.image || image;
        const locationDescription = locationData.description || description;
        const locationHasMap = locationData.has_map || hasMap;
    
        // Process opening hours
        const openingHours = [];
        const dayAbbreviations = {
            'monday': 'Mo',
            'tuesday': 'Tu',
            'wednesday': 'We',
            'thursday': 'Th',
            'friday': 'Fr',
            'saturday': 'Sa',
            'sunday': 'Su'
        };
    
        for (const day of Object.keys(dayAbbreviations)) {
            const checkbox = document.getElementById(day);
            if (checkbox.checked) {
                const openTime = document.getElementById(`${day}-open`).value;
                const closeTime = document.getElementById(`${day}-close`).value;
                let hoursString = `${dayAbbreviations[day]} ${openTime} - ${closeTime}`;
    
                const openTime2Element = document.getElementById(`${day}-open2`);
                const closeTime2Element = document.getElementById(`${day}-close2`);
                const additionalCheckbox = document.getElementById(`${day}-additional`);
    
                // Check if additional hours checkbox is checked before adding additional times
                if (additionalCheckbox && additionalCheckbox.checked) {
                    const openTime2 = openTime2Element ? openTime2Element.value : null;
                    const closeTime2 = closeTime2Element ? closeTime2Element.value : null;
    
                    if (openTime2 && closeTime2) {
                        hoursString += `, ${openTime2} - ${closeTime2}`;
                    }
                }
                openingHours.push(hoursString);
            }
        }
    
        const sameAsUrls = Array.from(document.querySelectorAll('[id^="sameAsInput"]')).map(input => input.value).filter(url => url);
    
        // Build the schema
        const schema = {
            "@context": "https://schema.org",
            "@type": businessType,
            name: locationName,
            url: locationUrl,
            logo: locationLogo,
            image: locationImage,
            description: locationDescription,
            address: {
                "@type": "PostalAddress",
                streetAddress: locationStreetAddress,
                addressLocality: locationAddressLocality,
                addressRegion: locationAddressRegion,
                postalCode: locationPostalCode,
                addressCountry: locationAddressCountry
            },
            geo: {
                "@type": "GeoCoordinates",
                latitude: locationLatitude,
                longitude: locationLongitude
            },
            hasMap: locationHasMap,
            telephone: locationTelephone,
            openingHours: openingHours,
            sameAs: sameAsUrls
        };
    
        // Update hCardInput with the JSON schema
        document.getElementById('hCardInput').value = JSON.stringify(schema, null, 2);
    
        // Add script tags for displaying schema on the page (escaped)
        const schemaWithTags = `&lt;script type='application/ld+json'&gt;\n${JSON.stringify(schema, null, 2)}\n&lt;/script&gt;`;
    
        // Display schema with escaped tags in the HTML
        document.getElementById('schemaJSONLD').innerHTML = schemaWithTags;
    }
    
    const locationDropdown = document.getElementById('additional_location');
    if (locationDropdown) {
    // Add event listener to update schema whenever the location is changed
    document.getElementById('additional_location').addEventListener('change', function() {
        // Delay the schema update by a few milliseconds to ensure the selection is processed
        setTimeout(updateSchema, 100); // 100ms delay to sync dropdown change
    });
    } else {
        console.warn("The 'additional_location' dropdown does not exist on the page, likely because it's a single location.");
    }


    
    function copySchemaToClipboard() {
        // Get the current schema from the schemaJSONLD element (innerHTML)
        let schemaOutput = document.getElementById('schemaJSONLD').innerHTML
            .replace(/&lt;/g, '<')
            .replace(/&gt;/g, '>'); // Decode HTML entities
    
        // Replace <br> tags with newline characters
        schemaOutput = schemaOutput.replace(/<br\s*\/?>/gi, '\n');
    
        // Create a temporary textarea element to facilitate copying
        const textarea = document.createElement('textarea');
        textarea.value = schemaOutput; // Use the schema with the tags
        document.body.appendChild(textarea);
        textarea.select(); // Select the content
        document.execCommand('copy'); // Copy the selected content to the clipboard
        document.body.removeChild(textarea); // Remove the temporary textarea
        
        // Optionally, you can add feedback for the user
        alert('Schema copied to clipboard!');
    }
    
    // Show the dropdown list
    function showDropdown(input) {
        // Clear the input field
        input.value = '';
        // Show the dropdown list
        input.focus();
    }
    
    
    function toggleFields(day) {
        var checkbox = document.getElementById(day);
        var fields = document.getElementById(day + '-fields');
        fields.style.display = checkbox.checked ? 'block' : 'none';
    
        // If the checkbox is checked, check for filled hours and log to the console
        if (checkbox.checked) {
            checkForHours(day);
        }
        
        // If the primary checkbox is unchecked, clear the hours for that day
        if (!checkbox.checked) {
            clearHours(day);
        }
    }
    
    function checkForHours(day) {
        // Get the values of open and close hours
        var open = document.getElementById(`${day}-open`).value; // Get open hours
        var close = document.getElementById(`${day}-close`).value; // Get close hours
        var open2 = document.getElementById(`${day}-open2`).value; // Get additional open hours
        var close2 = document.getElementById(`${day}-close2`).value; // Get additional close hours
    }
    
    function toggleAdditionalHours(day) {
        const additionalFields = document.getElementById(`${day}-additional-fields`);
        const additionalCheckbox = document.getElementById(`${day}-additional`);
    
        // Toggle the display of additional fields
        additionalFields.style.display = additionalCheckbox.checked ? 'block' : 'none';

        // If unchecked, clear the additional hours
        if (!additionalCheckbox.checked) {
            clearAdditionalHours(day);
        }
    }
    
    function clearHours(day) {
        // Clear the additional hour fields in the form
        document.getElementById(`${day}-open`).value = '';
        document.getElementById(`${day}-close`).value = '';
    }

    function clearAdditionalHours(day) {
        // Clear the additional hour fields in the form
        document.getElementById(`${day}-open2`).value = '';
        document.getElementById(`${day}-close2`).value = '';
    }

    // Add an event listener to ensure additional hours are cleared before form submission
    document.addEventListener('DOMContentLoaded', function() {
        const form = document.querySelector('form'); // Assuming you're using a form
    
        form.addEventListener('submit', function(event) {
            // Loop through the additional hours checkboxes to ensure unchecked ones have their values cleared
            const days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
            days.forEach(day => {
                const additionalCheckbox = document.getElementById(`${day}-additional`);
                if (additionalCheckbox && !additionalCheckbox.checked) {
                    clearAdditionalHours(day); // Ensure the additional hours are cleared before submission
                }
            });
        });
    });

    // Call toggleFields on page load to display fields for checked checkboxes
    document.addEventListener("DOMContentLoaded", function() {
        var days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
        days.forEach(function(day) {
            toggleFields(day); // Call the toggle function for each day
            // Add event listener to the checkbox
            document.getElementById(day).addEventListener('change', function() {
                toggleFields(day); // Check if fields should be displayed or not
            });
        });
    });
    
    // Function to check if any additional hours checkboxes are checked
    function checkAdditionalHoursOnLoad() {
        // Get all checkboxes for additional hours
        const additionalCheckboxes = document.querySelectorAll('input[type="checkbox"][id$="-additional"]');
    
        additionalCheckboxes.forEach(checkbox => {
            // Check if the checkbox is checked
            if (checkbox.checked) {
                // Extract the day from the checkbox ID (e.g., "monday-additional" -> "monday")
                const day = checkbox.id.split('-')[0];
                // Call the toggleAdditionalHours function for the respective day
                toggleAdditionalHours(day);
            }
        });
    }
    
    // Add event listener for when the DOM is fully loaded
    document.addEventListener('DOMContentLoaded', (event) => {
        checkAdditionalHoursOnLoad();
    });
</script>

<?php 

session_start();

    // Initialize variables to hold the submitted values
    $businessType = '';
    $name = '';
    $url = '';
    $logo = '';
    $image = '';
    $description = '';
    $street_address = '';
    $address_locality = '';
    $address_region = '';
    $postal_code = '';
    $address_country = '';
    $latitude = '';
    $longitude = '';
    $has_map = '';
    $telephone = '';
    $sameAsUrls = !empty($social_profiles_str) ? explode(',', $social_profiles_str) : [];
    
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // Check if the 'generate_schema' button was clicked
        if (isset($_POST['generate_schema'])) {
            
        // Get the submitted values
        $businessType = sanitize_text_field($_POST['businessType']);
        $name = sanitize_text_field($_POST['name']);
        $url = sanitize_text_field($_POST['url']);
        $logo = sanitize_text_field($_POST['logo']);
        $image = sanitize_text_field($_POST['image']);
        $description = sanitize_textarea_field($_POST['description']);
        $street_address = sanitize_text_field($_POST['street_address']);
        $address_locality = sanitize_text_field($_POST['address_locality']);
        $address_region = sanitize_text_field($_POST['address_region']);
        $postal_code = sanitize_text_field($_POST['postal_code']);
        $address_country = sanitize_text_field($_POST['address_country']);
        $latitude = sanitize_text_field($_POST['latitude']);
        $longitude = sanitize_text_field($_POST['longitude']);
        $has_map = sanitize_text_field($_POST['has_map']);
        $telephone = sanitize_text_field($_POST['telephone']);
    
        // Handle sameAs URLs
        for ($i = 1; $i <= $sameAsCounter; $i++) {
            if (isset($_POST['sameAsInput' . $i])) {
                $sameAsUrls[] = sanitize_text_field($_POST['sameAsInput' . $i]);
            }
        }
        
        // Check if an additional location is selected
        if (isset($_POST['additional_location']) && !empty($_POST['additional_location'])) {
            // The "additional-h-card.sh" script should be executed
            $scriptPath = plugin_dir_path(__FILE__) . 'additional-h-card.sh';
            
            // Get the selected location number
            $selectedLocation = $_POST['additional_location'];
        } else {
            // The default "h-card.sh" script should be executed
            $scriptPath = plugin_dir_path(__FILE__) . 'h-card.sh';
        }

        if (isset($_POST['hCard'])) {
            $schema = $_POST['hCard'];  // This should retain newlines and indents
    
            // Get the domain of the website
            $domain = parse_url(home_url(), PHP_URL_HOST);
            $domain = preg_replace('/^www\./', '', $domain);
        
            // Use escapeshellarg to safely pass the domain and hCard
            $escapedDomain = escapeshellarg($domain);
            $escapedHCard = escapeshellarg($schema);
            $escapedLocation = escapeshellarg($selectedLocation);  // Escape the location number
            
            exec("bash $scriptPath $escapedDomain $escapedHCard $escapedLocation 2>&1", $output, $returnVar);
        
            // Prepare the message based on the output and return status
            if ($returnVar === 0) {
                $message = "<span style='font-weight: 400;'>H-Card Updated Successfully! </span><br>'Perfection is not attainable, but if we chase perfection we can catch excellence.' - Vince Lombardi<br> " . implode("<br>", $output);
                add_settings_error('my_plugin_notice', 'success', $message, 'updated');
            } elseif ($returnVar === 1) {
                $message = "<span style='font-weight: 400;'>Sorry, looks like the H-Card needs to be updated manually.</span> <br>" . implode("<br>", $output);
                add_settings_error('my_plugin_notice', 'warning', $message, 'warning');
            } else {
                $message = "Error trying to update the H-Card! <br>Output: " . implode("<br>", $output);
                add_settings_error('my_plugin_notice', 'error', $message, 'error');
            }
    
            // Display the messages on the page
            settings_errors('my_plugin_notice');
        }
    }
    
    // Check if the 'submit_schema_form' button was clicked to handle saving data
    if (isset($_POST['submit_schema_form'])) {

        global $wpdb;
    
        // Handle location selection
        $additionalLocation = isset($_POST['additional_location']) ? sanitize_text_field($_POST['additional_location']) : '';
        if ($additionalLocation) {
            // If a location is selected, use that table
            $table_name = $additionalLocation;
        } else {
            // If no location is selected, use the default wp_business_info table
            $table_name = $wpdb->prefix . 'business_info';
        }
        
        // Check if the table exists
        $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'");
        
        if ($table_exists) {
            // List of required columns and their definitions
            $columns = [
                'business_type' => "VARCHAR(255)",
                'name' => "VARCHAR(255)",
                'url' => "VARCHAR(255)",
                'logo' => "VARCHAR(255)",
                'image' => "VARCHAR(255)",
                'description' => "TEXT",
                'street_address' => "VARCHAR(255)",
                'address_locality' => "VARCHAR(255)",
                'address_region' => "VARCHAR(255)",
                'postal_code' => "VARCHAR(20)",
                'address_country' => "VARCHAR(100)",
                'latitude' => "DECIMAL(10, 8)",
                'longitude' => "DECIMAL(11, 8)",
                'has_map' => "VARCHAR(255)",
                'telephone' => "VARCHAR(50)",
                'opening_hours' => "TEXT",
                'monday_open' => "VARCHAR(255)",
                'monday_close' => "VARCHAR(255)",
                'tuesday_open' => "VARCHAR(255)",
                'tuesday_close' => "VARCHAR(255)",
                'wednesday_open' => "VARCHAR(255)",
                'wednesday_close' => "VARCHAR(255)",
                'thursday_open' => "VARCHAR(255)",
                'thursday_close' => "VARCHAR(255)",
                'friday_open' => "VARCHAR(255)",
                'friday_close' => "VARCHAR(255)",
                'saturday_open' => "VARCHAR(255)",
                'saturday_close' => "VARCHAR(255)",
                'sunday_open' => "VARCHAR(255)",
                'sunday_close' => "VARCHAR(255)",
                'monday_open2' => "VARCHAR(255)",
                'monday_close2' => "VARCHAR(255)",
                'tuesday_open2' => "VARCHAR(255)",
                'tuesday_close2' => "VARCHAR(255)",
                'wednesday_open2' => "VARCHAR(255)",
                'wednesday_close2' => "VARCHAR(255)",
                'thursday_open2' => "VARCHAR(255)",
                'thursday_close2' => "VARCHAR(255)",
                'friday_open2' => "VARCHAR(255)",
                'friday_close2' => "VARCHAR(255)",
                'saturday_open2' => "VARCHAR(255)",
                'saturday_close2' => "VARCHAR(255)",
                'sunday_open2' => "VARCHAR(255)",
                'sunday_close2' => "VARCHAR(255)",
                'social_profiles' => "TEXT"
            ];
        
            // Loop through each column and add it if it doesn't exist
            foreach ($columns as $column_name => $column_definition) {
                $column_exists = $wpdb->get_results("SHOW COLUMNS FROM `$table_name` LIKE '$column_name'");
        
                if (!$column_exists) {
                    $alter_sql = "ALTER TABLE $table_name ADD COLUMN $column_name $column_definition";
                    $wpdb->query($alter_sql);
        
                    // Check for errors during table alteration
                    if ($wpdb->last_error) {
                        echo '<div class="notice notice-error"><p>Failed to modify table: ' . esc_html($wpdb->last_error) . '</p></div>';
                        break; // Stop if an error occurs
                    }
                }
            }
        } else {
            // SQL to create the table if it doesn't exist
            $table_sql = "CREATE TABLE IF NOT EXISTS $table_name (
                id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
                business_type VARCHAR(255),
                name VARCHAR(255) NOT NULL,
                url VARCHAR(255),
                logo VARCHAR(255),
                image VARCHAR(255),
                description TEXT,
                street_address VARCHAR(255),
                address_locality VARCHAR(255),
                address_region VARCHAR(255),
                postal_code VARCHAR(20),
                address_country VARCHAR(100),
                latitude DECIMAL(10, 8),
                longitude DECIMAL(11, 8),
                has_map VARCHAR(255),
                telephone VARCHAR(50),
                opening_hours TEXT,
                monday_open VARCHAR(50),
                monday_close VARCHAR(50),
                tuesday_open VARCHAR(50),
                tuesday_close VARCHAR(50),
                wednesday_open VARCHAR(50),
                wednesday_close VARCHAR(50),
                thursday_open VARCHAR(50),
                thursday_close VARCHAR(50),
                friday_open VARCHAR(50),
                friday_close VARCHAR(50),
                saturday_open VARCHAR(50),
                saturday_close VARCHAR(50),
                sunday_open VARCHAR(50),
                sunday_close VARCHAR(50),
                monday_open2 VARCHAR(50),
                monday_close2 VARCHAR(50),
                tuesday_open2 VARCHAR(50),
                tuesday_close2 VARCHAR(50),
                wednesday_open2 VARCHAR(50),
                wednesday_close2 VARCHAR(50),
                thursday_open2 VARCHAR(50),
                thursday_close2 VARCHAR(50),
                friday_open2 VARCHAR(50),
                friday_close2 VARCHAR(50),
                saturday_open2 VARCHAR(50),
                saturday_close2 VARCHAR(50),
                sunday_open2 VARCHAR(50),
                sunday_close2 VARCHAR(50),
                social_profiles TEXT,
                PRIMARY KEY (id)
            ) {$wpdb->get_charset_collate()};";
        
            // Create the table
            $wpdb->query($table_sql);
        
            // Check for errors during table creation
            if ($wpdb->last_error) {
                echo '<div class="notice notice-error"><p>Failed to create table: ' . esc_html($wpdb->last_error) . '</p></div>';
            }
        }
    
        $business_type = sanitize_text_field($_POST['businessType']);
        $name = $_POST['name']; // Directly use the value without escaping
        $url = esc_url_raw($_POST['url']);
        $logo = esc_url_raw($_POST['logo']);
        $image = esc_url_raw($_POST['image']);
        $description = $_POST['description']; // Directly use the value without escaping
        $street_address = $_POST['street_address']; // Directly use the value without escaping
        $address_locality = $_POST['address_locality']; // Directly use the value without escaping
        $address_region = sanitize_text_field($_POST['address_region']);
        $postal_code = sanitize_text_field($_POST['postal_code']);
        $address_country = sanitize_text_field($_POST['address_country']);
        $latitude = sanitize_text_field($_POST['latitude']);
        $longitude = sanitize_text_field($_POST['longitude']);
        $has_map = esc_url_raw($_POST['has_map']);
        $telephone = sanitize_text_field($_POST['telephone']);
    
        // Collect opening hours with two sets of times if applicable
        $opening_hours = [];
        
        $monday_open = sanitize_text_field($_POST['monday-open']);
        $monday_close = sanitize_text_field($_POST['monday-close']);
        $tuesday_open = sanitize_text_field($_POST['tuesday-open']);
        $tuesday_close = sanitize_text_field($_POST['tuesday-close']);
        $wednesday_open = sanitize_text_field($_POST['wednesday-open']);
        $wednesday_close = sanitize_text_field($_POST['wednesday-close']);
        $thursday_open = sanitize_text_field($_POST['thursday-open']);
        $thursday_close = sanitize_text_field($_POST['thursday-close']);
        $friday_open = sanitize_text_field($_POST['friday-open']);
        $friday_close = sanitize_text_field($_POST['friday-close']);
        $saturday_open = sanitize_text_field($_POST['saturday-open']);
        $saturday_close = sanitize_text_field($_POST['saturday-close']);
        $sunday_open = sanitize_text_field($_POST['sunday-open']);
        $sunday_close = sanitize_text_field($_POST['sunday-close']);
        $monday_open2 = sanitize_text_field($_POST['monday-open2']);
        $monday_close2 = sanitize_text_field($_POST['monday-close2']);
        $tuesday_open2 = sanitize_text_field($_POST['tuesday-open2']);
        $tuesday_close2 = sanitize_text_field($_POST['tuesday-close2']);
        $wednesday_open2 = sanitize_text_field($_POST['wednesday-open2']);
        $wednesday_close2 = sanitize_text_field($_POST['wednesday-close2']);
        $thursday_open2 = sanitize_text_field($_POST['thursday-open2']);
        $thursday_close2 = sanitize_text_field($_POST['thursday-close2']);
        $friday_open2 = sanitize_text_field($_POST['friday-open2']);
        $friday_close2 = sanitize_text_field($_POST['friday-close2']);
        $saturday_open2 = sanitize_text_field($_POST['saturday-open2']);
        $saturday_close2 = sanitize_text_field($_POST['saturday-close2']);
        $sunday_open2 = sanitize_text_field($_POST['sunday-open2']);
        $sunday_close2 = sanitize_text_field($_POST['sunday-close2']);
        
        $days_of_week = [
            'monday' => 'Mo',
            'tuesday' => 'Tu',
            'wednesday' => 'We',
            'thursday' => 'Th',
            'friday' => 'Fr',
            'saturday' => 'Sa',
            'sunday' => 'Su'
        ];
        
        foreach ($days_of_week as $day => $day_abbr) {
            if (!empty($_POST[$day])) {
                $open_time = sanitize_text_field($_POST["{$day}-open"]);
                $close_time = sanitize_text_field($_POST["{$day}-close"]);
                $open_time2 = sanitize_text_field($_POST["{$day}-open2"]);
                $close_time2 = sanitize_text_field($_POST["{$day}-close2"]);
        
                if (!empty($open_time) && !empty($close_time)) {
                    // First time set
                    $hours = "{$day_abbr} {$open_time} - {$close_time}";
        
                    // Second time set if available
                    if (!empty($open_time2) && !empty($close_time2)) {
                        $hours .= ", {$open_time2} - {$close_time2}";
                    }
        
                    $opening_hours[] = $hours;
                }
            }
        }
    
        // Combine all opening hours into a single string
        $opening_hours_str = implode(', ', $opening_hours);
    
        // Collect social profiles (sameAs URLs)
        $social_profiles = [];
        foreach ($_POST as $key => $value) {
            if (strpos($key, 'sameAsInput') !== false && !empty($value)) {
                $social_profiles[] = esc_url_raw($value);
            }
        }
        $social_profiles_str = implode(', ', $social_profiles);

    // Insert data into the table
    $inserted = $wpdb->insert(
        $table_name,
        [
            'business_type' => $business_type,
            'name' => stripslashes($name),
            'url' => $url,
            'logo' => $logo,
            'image' => $image,
            'description' => stripslashes($description),
            'street_address' => stripslashes($street_address),
            'address_locality' => stripslashes($address_locality),
            'address_region' => $address_region,
            'postal_code' => $postal_code,
            'address_country' => $address_country,
            'latitude' => $latitude,
            'longitude' => $longitude,
            'has_map' => $has_map,
            'telephone' => $telephone,
            'opening_hours' => $opening_hours_str,
            'monday_open' => $monday_open,
            'monday_close' => $monday_close,
            'tuesday_open' => $tuesday_open,
            'tuesday_close' => $tuesday_close,
            'wednesday_open' => $wednesday_open,
            'wednesday_close' => $wednesday_close,
            'thursday_open' => $thursday_open,
            'thursday_close' => $thursday_close,
            'friday_open' => $friday_open,
            'friday_close' => $friday_close,
            'saturday_open' => $saturday_open,
            'saturday_close' => $saturday_close,
            'sunday_open' => $sunday_open,
            'sunday_close' => $sunday_close,
            'monday_open2' => $monday_open2,
            'monday_close2' => $monday_close2,
            'tuesday_open2' => $tuesday_open2,
            'tuesday_close2' => $tuesday_close2,
            'wednesday_open2' => $wednesday_open2,
            'wednesday_close2' => $wednesday_close2,
            'thursday_open2' => $thursday_open2,
            'thursday_close2' => $thursday_close2,
            'friday_open2' => $friday_open2,
            'friday_close2' => $friday_close2,
            'saturday_open2' => $saturday_open2,
            'saturday_close2' => $saturday_close2,
            'sunday_open2' => $sunday_open2,
            'sunday_close2' => $sunday_close2,
            'social_profiles' => $social_profiles_str,
        ]
    );
    
        // Check if data was inserted successfully
        if ($inserted) {
            $_SESSION['success_message'] = 'Data saved successfully! <strong>Refreshing the page and updating the data in 3 seconds...</strong>';
        } else {
            $_SESSION['error_message'] = 'Error saving data: ' . $wpdb->last_error;
        }
        
        // Display messages and trigger JavaScript if a message is set
        if (isset($_SESSION['success_message']) || isset($_SESSION['error_message'])) {
            if (isset($_SESSION['success_message'])) {
                echo '<div class="notice notice-success"><p>' . $_SESSION['success_message'] . '</p></div>';
                unset($_SESSION['success_message']);
                
                // Output JavaScript to refresh page after 3 seconds so the data is updated
                echo "<script>
                    document.addEventListener('DOMContentLoaded', function() {
                        // Set a timeout to reload the page after 3 seconds
                        setTimeout(function() {
                            window.location.reload();
                        }, 3000); // 3000 milliseconds = 3 seconds
                    });
                </script>";

            }
        
            if (isset($_SESSION['error_message'])) {
                echo '<div class="notice notice-error"><p>' . $_SESSION['error_message'] . '</p></div>';
                unset($_SESSION['error_message']);
            }
        }
    }
}
?>

<!-- Schema script that will contain the generated JSON-LD -->
<script type="application/ld+json" id="jsonLdSchema"></script>

<script>
    // Initialize the counter
    let sameAsCounter = <?php echo count($sameAsUrls); ?>; // Set initial count based on existing URLs
    
    // Function to add more social profile (sameAs) inputs
    function addSameAs() {
        sameAsCounter++;
        const container = document.getElementById('sameAsContainer');
        const div = document.createElement('div');
        div.className = 'sameAsContainer';
        div.id = 'sameAs' + sameAsCounter;
    
        const label = document.createElement('label');
        label.setAttribute('for', 'sameAsInput' + sameAsCounter);
        label.innerText = 'sameAs URL ' + sameAsCounter + ':';
        div.appendChild(label);
    
        const input = document.createElement('input');
        input.type = 'url';
        input.placeholder = 'Enter sameAs URL';
        input.id = 'sameAsInput' + sameAsCounter;
        input.name = 'sameAsInput' + sameAsCounter; // Make sure name attribute is set for form submission
        input.value = ''; // Set input value to blank for new fields
        input.oninput = updateSchema; // Add input event listener for the new input
        div.appendChild(input);
    
        container.appendChild(div);
    
        // Call updateSchema() to refresh the schema with the new input
        updateSchema();
    }
    
    // Function to remove last social profile (sameAs) input
    function removeSameAs() {
        if (sameAsCounter > 0) {
            const container = document.getElementById('sameAsContainer');
            const lastSameAs = document.getElementById('sameAs' + sameAsCounter);
            container.removeChild(lastSameAs);
            sameAsCounter--;
            
            // Call updateSchema() to refresh the schema with the new input
            updateSchema();
        }
    }
    
    // Attach event listeners to buttons after defining the functions
    document.getElementById('addSameAsBtn').onclick = addSameAs; // No parameters for new fields
    document.getElementById('removeSameAsBtn').onclick = removeSameAs;
</script>

<script>
    <?php
        // Create table on plugin activation
        function create_business_info_table() {
            global $wpdb;
            
            $table_name = $wpdb->prefix . 'business_info'; // Table name
        
            $charset_collate = $wpdb->get_charset_collate();
        
            $sql = "CREATE TABLE $table_name (
                id mediumint(9) NOT NULL AUTO_INCREMENT,
                business_type varchar(100) NOT NULL,
                name varchar(255) NOT NULL,
                url varchar(255) NOT NULL,
                logo varchar(255),
                image varchar(255),
                description text,
                street_address varchar(255),
                address_locality varchar(100),
                address_region varchar(100),
                postal_code varchar(20),
                address_country varchar(100),
                latitude varchar(50),
                longitude varchar(50),
                has_map varchar(255),
                telephone varchar(50),
                opening_hours text,
                monday_open varchar(50),
                monday_close varchar(50),
                tuesday_open varchar(50),
                tuesday_close varchar(50),
                wednesday_open varchar(50),
                wednesday_close varchar(50),
                thursday_open varchar(50),
                thursday_close varchar(50),
                friday_open varchar(50),
                friday_close varchar(50),
                saturday_open varchar(50),
                saturday_close varchar(50),
                sunday_open varchar(50),
                sunday_close varchar(50),
                monday_open2 varchar(50),
                monday_close2 varchar(50),
                tuesday_open2 varchar(50),
                tuesday_close2 varchar(50),
                wednesday_open2 varchar(50),
                wednesday_close2 varchar(50),
                thursday_open2 varchar(50),
                thursday_close2 varchar(50),
                friday_open2 varchar(50),
                friday_close2 varchar(50),
                saturday_open2 varchar(50),
                saturday_close2 varchar(50),
                sunday_open2 varchar(50),
                sunday_close2 varchar(50),
                social_profiles text,
                PRIMARY KEY  (id)
            ) $charset_collate;";
        
            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
            dbDelta($sql);
        }
        register_activation_hook(__FILE__, 'create_business_info_table');
        ?>

    // Add event listeners to input fields
    document.querySelectorAll('input').forEach(input => {
        input.addEventListener('input', updateSchema);
    });
    
    // Call updateSchema once on page load to set initial values
    document.addEventListener('DOMContentLoaded', updateSchema);
</script>

<?php
// Start the session to store messages
session_start();

// Check if the form is submitted to remove a location
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['remove_location'])) {
    global $wpdb;

    // Get the table to be removed
    $table_to_remove = sanitize_text_field($_POST['remove_location']);
    $table_prefix = $wpdb->prefix . 'business_info';

    // Ensure the table exists
    if ($wpdb->get_var("SHOW TABLES LIKE '{$table_to_remove}'") === $table_to_remove) {
        // Drop the table from the database
        $result = $wpdb->query("DROP TABLE IF EXISTS {$table_to_remove}");

        if ($result !== false) {
            // Success message - store in session
            $_SESSION['location_removal_message'] = [
                'type' => 'success', 
                'message' => "Location table '{$table_to_remove}' has been removed successfully."
            ];
        } else {
            // Error message - store in session
            $_SESSION['location_removal_message'] = [
                'type' => 'error', 
                'message' => "Error occurred while removing the location table '{$table_to_remove}'."
            ];
        }
    } else {
        // Error message if the table does not exist - store in session
        $_SESSION['location_removal_message'] = [
            'type' => 'error', 
            'message' => "Location table '{$table_to_remove}' does not exist."
        ];
    }

    // Redirect to the same page to display the message
    header('Location: ' . $_SERVER['REQUEST_URI']);
    exit;
}

// Display the stored message if it exists using WordPress style
if (isset($_SESSION['location_removal_message'])) {
    $message_type = $_SESSION['location_removal_message']['type'];
    $message = $_SESSION['location_removal_message']['message'];

    // Add the message to WordPress settings errors to display it in the correct style
    add_settings_error('location_removal', 'location_removal_error', $message, $message_type);

    // Clear the session message after displaying it
    unset($_SESSION['location_removal_message']);
}

// Display messages on the page
settings_errors('location_removal');
?>
