/**
 * Switches the published state of a name and returns the human readable value
 * @param (numeric) $name_id
 * @return string|void
 */
function name_directory_switch_name_published_status($name_id)
{
    global $wpdb;
    global $table_directory_name;
    $wpdb->query($wpdb->prepare("UPDATE `{$table_directory_name}` SET `published`=1 XOR `published` WHERE id=%d", intval($name_id)));
    sleep(0.1);
    return name_directory_yesno($wpdb->get_var(sprintf("SELECT `published` FROM `%s` WHERE id=%d", $table_directory_name, intval($name_id))));
}
/**
 * Handle the names in the name directory
 *  - Display all names
 *  - Edit names (ajax and 'oldskool' view)
 *  - Create new names
 */
function name_directory_names()
{
    if (!current_user_can('manage_options')) {
        wp_die(__('You do not have sufficient permissions to access this page.', 'name-directory'));
    }
    global $wpdb;
    global $table_directory;
    global $table_directory_name;
    if (!empty($_GET['delete_name']) && is_numeric($_GET['delete_name'])) {
        $name = $wpdb->get_var(sprintf("SELECT `name` FROM %s WHERE id=%d", $table_directory_name, $_GET['delete_name']));
        $wpdb->delete($table_directory_name, array('id' => $_GET['delete_name']), array('%d'));
        echo "<div class='updated'><p>" . sprintf(__('Name %s deleted', 'name-directory'), "<i>" . $name . "</i>") . "</p></div>";
    } else {
        if (!empty($_POST['name_id'])) {
            $wpdb->update($table_directory_name, array('name' => stripslashes_deep($_POST['name']), 'letter' => name_directory_get_first_char($_POST['name']), 'description' => stripslashes_deep($_POST['description']), 'published' => $_POST['published'], 'submitted_by' => $_POST['submitted_by']), array('id' => intval($_POST['name_id'])));
            if ($_POST['action'] == "name_directory_ajax_names") {
                echo '<p>';
                echo sprintf(__('Name %s updated', 'name-directory'), "<i>" . esc_sql($_POST['name']) . "</i>");
                echo '</p>';
                exit;
            }
            echo "<div class='updated'><p>" . sprintf(__('Name %s updated', 'name-directory'), "<i>" . esc_sql($_POST['name']) . "</i>") . "</p></div>";
            unset($_GET['edit_name']);
        } else {
            if (!empty($_POST['name'])) {
                $name_exists = name_directory_name_exists_in_directory($_POST['name'], $_POST['directory']);
                if ($name_exists && $_POST['action'] == "name_directory_ajax_names") {
                    echo '<p>';
                    echo sprintf(__('Name %s was already on the list, so it was not added', 'name-directory'), '<i>' . esc_sql($_POST['name']) . '</i>');
                    echo '</p>';
                    exit;
                }
                $wpdb->insert($table_directory_name, array('directory' => $_POST['directory'], 'name' => stripslashes_deep($_POST['name']), 'letter' => name_directory_get_first_char($_POST['name']), 'description' => stripslashes_deep($_POST['description']), 'published' => $_POST['published'], 'submitted_by' => $_POST['submitted_by']), array('%d', '%s', '%s', '%s', '%d', '%s'));
                if ($_POST['action'] == "name_directory_ajax_names") {
                    echo '<p>';
                    printf(__('New name %s added', 'name-directory'), '<i>' . esc_sql($_POST['name']) . '</i> ');
                    echo '. <small><i>' . __('Will be visible when the page is refreshed.', 'name-directory') . '</i></small>';
                    echo '</p>';
                    exit;
                }
                echo "<div class='updated'><p><strong>" . sprintf(__('New name %s added', 'name-directory'), "<i>" . esc_sql($_POST['name']) . "</i> ") . "</strong></p></div>";
            } else {
                if ($_SERVER['REQUEST_METHOD'] == 'POST') {
                    if ($_POST['action'] == "name_directory_ajax_names") {
                        echo '<p>' . __('Please fill in at least a name', 'name-directory') . '</p>';
                        exit;
                    }
                    echo "<div class='error'><p><strong>" . __('Please fill in at least a name', 'name-directory') . "</strong></p></div>";
                }
            }
        }
    }
    $directory_id = intval($_GET['dir']);
    $wp_file = admin_url('options-general.php');
    $wp_page = $_GET['page'];
    $wp_sub = $_GET['sub'];
    $overview_url = sprintf("%s?page=%s", $wp_file, $wp_page);
    $wp_url_path = sprintf("%s?page=%s&sub=%s&dir=%d", $wp_file, $wp_page, $wp_sub, $directory_id);
    $wp_import_path = sprintf("%s?page=%s&sub=import&dir=%d", $wp_file, $wp_page, $directory_id);
    $published_status = '0,1';
    $emphasis_class = 's_all';
    if ($_GET['status'] == 'published') {
        $published_status = '1';
        $emphasis_class = 's_published';
    } else {
        if ($_GET['status'] == 'unpublished') {
            $published_status = '0';
            $emphasis_class = 's_unpublished';
        }
    }
    $directory = $wpdb->get_row("SELECT * FROM " . $table_directory . " WHERE `id` = " . $directory_id, ARRAY_A);
    $names = $wpdb->get_results(sprintf("SELECT * FROM %s WHERE `directory` = %d AND `published` IN (%s) ORDER BY `name` ASC", $table_directory_name, $directory_id, $published_status));
    echo '<div class="wrap">';
    echo "<h2>" . sprintf(__('Manage names for %s', 'name-directory'), $directory['name']) . "</h2>";
    ?>

    <p>
        View:
        <a class='s_all' href='<?php 
    echo $wp_url_path;
    ?>
&status=all'><?php 
    _e('all', 'name-directory');
    ?>
</a> |
        <a class='s_published' href='<?php 
    echo $wp_url_path;
    ?>
&status=published'><?php 
    _e('published', 'name-directory');
    ?>
</a> |
        <a class='s_unpublished' href='<?php 
    echo $wp_url_path;
    ?>
&status=unpublished'><?php 
    _e('unpublished', 'name-directory');
    ?>
</a>

        <span style='float: right';>
            <a href='<?php 
    echo $overview_url;
    ?>
'><?php 
    _e('Back to the directory overview', 'name-directory');
    ?>
</a>
        </span>
    </p>

    <table class="wp-list-table widefat name_directory_names fixed" cellpadding="0">
        <thead>
        <tr>
            <th width="18%"><?php 
    echo __('Name', 'name-directory');
    ?>
</th>
            <th width="54%"><?php 
    echo __('Description', 'name-directory');
    ?>
</th>
            <th width="12%"><?php 
    echo __('Submitter', 'name-directory');
    ?>
</th>
            <th width="9%"><?php 
    echo __('Published', 'name-directory');
    ?>
</th>
            <th width="15%"><?php 
    echo __('Manage', 'name-directory');
    ?>
</th>
        </tr>
        </thead>
        <tbody>
        <?php 
    if (empty($names)) {
        echo sprintf("<tr class='empty-directory'><td colspan='5'>%s</td></tr>", __('Currently, there are no names in this directory..', 'name-directory'));
    }
    foreach ($names as $name) {
        echo sprintf("\n                <tr>\n                    <td>%s</td><td>%s</td><td>%s</td><td><span title='%s' class='toggle_published' id='nid_%d' data-nameid='%d'>%s</span></td>\n                    <td><a class='button button-primary button-small' href='" . $wp_url_path . "&edit_name=%d#anchor_add_form'>%s</a>\n                        <a class='button button-small' href='" . $wp_url_path . "&delete_name=%d'>%s</a>\n                    </td>\n                </tr>", $name->name, html_entity_decode(stripslashes($name->description)), $name->submitted_by, __('Toggle published status', 'name-directory'), $name->id, $name->id, name_directory_yesno($name->published), $name->id, __('Edit', 'name-directory'), $name->id, __('Delete', 'name-directory'));
    }
    ?>
        </tbody>
    </table>

    <p>&nbsp;</p>

    <?php 
    if (!empty($_GET['edit_name'])) {
        $name = $wpdb->get_row(sprintf("SELECT * FROM `%s` WHERE `id` = %d", $table_directory_name, $_GET['edit_name']), ARRAY_A);
        $table_heading = __('Edit a name', 'name-directory');
        $save_button_txt = __('Save name', 'name-directory');
    } else {
        $table_heading = __('Add a new name', 'name-directory');
        $save_button_txt = __('Add name', 'name-directory');
        $name = array();
    }
    ?>
    <span style='float: right';>
        <a href='<?php 
    echo $overview_url;
    ?>
'><?php 
    _e('Back to the directory overview', 'name-directory');
    ?>
</a>
    </span>

    <p>&nbsp;</p>

    <div class="updated hidden" id="add_result"></div>

    <a name="anchor_add_form"></a>
    <form name="add_name" id="add_name_ajax" method="post" action="<?php 
    echo $wp_url_path;
    ?>
">
    <table class="wp-list-table widefat" cellpadding="0">
        <thead>
            <tr>
                <th width="18%"><?php 
    echo $table_heading;
    ?>
                    <input type="hidden" name="directory" value="<?php 
    echo $directory_id;
    ?>
">
                    <?php 
    if ($_GET['edit_name']) {
        echo '<input type="hidden" name="name_id" id="edit_name_id" value="' . intval($_GET['edit_name']) . '">';
    }
    ?>
                    <input type="hidden" name="action" value="0" id="add_form_ajax_submit" />
                </th>
                <th align="right">

                    <label id="input_compact" title="<?php 
    echo __('Show the compact form, showing only the name, always published)', 'name-directory');
    ?>
">
                        <input type="radio" name="input_mode" />
                        <?php 
    echo __('Quick add view', 'name-directory');
    ?>
                    </label>
                    <label id="input_extensive" title="<?php 
    echo __('Show the full form, which allows you to enter a description and submitter', 'name-directory');
    ?>
">
                        <input type="radio" name="input_mode" />
                        <?php 
    echo __('Full add view', 'name-directory');
    ?>
                    </label>

                </th>
            </tr>
        </thead>
        <tbody>
            <tr id="add_name">
                <td width="18%"><?php 
    echo __('Name', 'name-directory');
    ?>
</td>
                <td width="82%"><input type="text" name="name" value="<?php 
    echo $name['name'];
    ?>
" size="20" style="width: 100%;"></td>
            </tr>
            <tr id="add_description">
                <td><?php 
    echo __('Description', 'name-directory');
    ?>
</td>
                <td><textarea name="description" rows="5" style="width: 100%;"><?php 
    echo stripslashes($name['description']);
    ?>
</textarea>
                    <small><strong><?php 
    echo __('Please be careful!', 'name-directory');
    ?>
</strong>
                        <?php 
    echo __('HTML markup is allowed and will we printed on your website and in the Wordpress admin.', 'name-directory');
    ?>
</small></td>
            </tr>
            <tr id="add_published">
                <td><?php 
    echo __('Published', 'name-directory');
    ?>
</td>
                <td>
                    <input type="radio" name="published" id="published_yes" value="1" checked="checked">
                    <label for="published_yes"><?php 
    echo __('Yes', 'name-directory');
    ?>
</label>

                    <input type="radio" name="published" id="published_no" value="0"
                        <?php 
    if (isset($name['published']) && empty($name['published'])) {
        echo 'checked="checked"';
    }
    ?>
>
                    <label for="published_no"><?php 
    echo __('No', 'name-directory');
    ?>
</label>
                </td>
            </tr>
            <tr id="add_submitter">
                <td><?php 
    echo __('Submitted by', 'name-directory');
    ?>
</td>
                <td><input type="text" name="submitted_by" value="<?php 
    echo $name['submitted_by'];
    ?>
" size="20" style="width: 100%;"></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <input type="submit" id="add_button" name="Submit" class="button button-primary button-large"
                           value="<?php 
    echo $save_button_txt;
    ?>
" />
                </td>
            </tr>
        </tbody>
    </table>
    </form>

    <?php 
    print_javascript($emphasis_class);
    print_style();
}