<?php

if (!class_exists('WP_List_Table')) {
    require_once(ABSPATH . 'wp-admin/includes/class-wp-list-table.php');
}

function view_race_user_all_courses_list_initialisation()
{
    global $wpdb;

    echo "
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const links = document.querySelectorAll('th a'); // Sélectionner les liens de tri dans les colonnes
            const seasonField = document.querySelector('#IDSeason'); // Sélectionner le champ de filtre IDSeason

            if (seasonField) {
                const currentIDSeason = seasonField.value; // Récupérer la saison actuellement sélectionnée

                links.forEach(function(link) {
                    const url = new URL(link.href); // Transformer l'URL en objet manipulable
                    url.searchParams.set('IDSeason', currentIDSeason); // Ajouter ou remplacer le paramètre IDSeason
                    link.href = url.toString(); // Appliquer la nouvelle URL au lien
                });
            }
        });
    </script>
    ";

    $table = new CASS_View_Race_User_All_Courses_List();
    ?>
    <div class="wrap">
        <?php
        $user = get_userdata($_GET["element"]);
        echo "<h2>Liste des courses pour le membre : " . $user->user_lastname . " " . $user->user_firstname;

        ?>
        <form action='#' method='POST'>
            <div class="form-element">
                <select name="IDSeason" id="IDSeason">
                    <option value="all" <?php echo isset($_POST['IDSeason']) && $_POST['IDSeason'] === 'all' ? 'selected' : ''; ?>>Toutes les saisons</option>
                    <?php
                    $season = new Season();
                    //Select all type
                    $sql = "SELECT IDSeason, name FROM cass_season ORDER BY name ASC;";
                    $rows = $wpdb->get_results($sql);
                    $selectedValue = isset($_POST['IDSeason']) && $_POST['IDSeason'] !== ''
                        ? $_POST['IDSeason']  // Priorité à POST
                        : (isset($_GET['IDSeason']) && $_GET['IDSeason'] !== ''
                            ? $_GET['IDSeason']  // Sinon, GET
                            : $season->getCurrentSeason() // Sinon, saison actuelle
                        );

                    foreach ($rows as $type) {
                        $selected = ($selectedValue !== null && intval($selectedValue) == intval($type->IDSeason)) ? "selected" : "";

                        echo "<option value=" . $type->IDSeason . " " . $selected . ">" . $type->name . "</option>";
                    }
                    ?>
                </select>
            </div>
            <button type="submit" class="button-secondary" id="refresh-cache">Filtrer
            </button>
        </form>

        <?php

        // Prepare table
        $table->prepare_items();
        // Display table
        $table->display();
        echo '</div></form>';
}

class CASS_View_Race_User_All_Courses_List extends WP_List_Table
{
    private $table_data;

    // Define table columns
    function get_columns()
    {
        $columns = array(
            'cb' => '<input type="checkbox" />',
            'name' => __('Nom', 'cass-race-name-content'),
            'state' => __('Etat', 'cass-race-state-content'),
            'start' => __('Début de la course', 'cass-race-start-content'),
            'IDWPUser_RL' => __('Chef de course', 'cass-race-rl-content'),
            'IDLevel' => __('Niveau de la course', 'cass-race-level-content'),
            'IDType' => __('Type', 'cass-race-type-content'),
        );
        return $columns;
    }


    function prepare_items()
    {
        $this->table_data = $this->get_table_data();


        $columns = $this->get_columns();
        $hidden = array();
        $sortable = $this->get_sortable_columns();
        $this->_column_headers = array($columns, $hidden, $sortable);

        usort($this->table_data, array(&$this, 'usort_reorder'));

        /* pagination */
        $per_page = 20;
        $current_page = $this->get_pagenum();
        $total_items = count($this->table_data);

        $this->table_data = array_slice($this->table_data, (($current_page - 1) * $per_page), $per_page);

        $this->set_pagination_args(
            array(
                'total_items' => $total_items,
                // total number of items
                'per_page' => $per_page,
                // items to show on a page
                'total_pages' => ceil($total_items / $per_page) // use ceil to round up
            )
        );

        $this->items = $this->table_data;
    }

    // Get table data
    private function get_table_data()
    {
        global $wpdb;

        $table = 'cass_race';
        $season = new Season();

        // Récupération de l'utilisateur en cours
        $user = get_userdata($_GET["element"]);
        $currentUser = $user->id;

        // Obtenez l'ID de la saison actuelle
        $currentSeasonID = intval($season->getCurrentSeason()); // Saison actuelle par défaut

        // Priorité à $_POST
        if (isset($_POST['IDSeason']) && $_POST['IDSeason'] !== '') {
            $IDSeason = $_POST['IDSeason'];
        }
        // Ensuite vérifier $_GET
        else if (isset($_GET['IDSeason']) && $_GET['IDSeason'] !== '') {
            $IDSeason = $_GET['IDSeason'];
        }
        // Sinon, utiliser la saison actuelle comme fallback
        else {
            $IDSeason = $currentSeasonID;
        }

        // S'assurer que IDSeason est dans $_POST pour une utilisation ultérieure
        $_POST['IDSeason'] = $IDSeason;

        // Construire la requête en fonction de IDSeason
        if ($IDSeason === "all") {
            // Afficher toutes les courses auxquelles l'utilisateur est inscrit
            $results = $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT * FROM {$table} INNER JOIN cass_race_user ON cass_race.IDRace = cass_race_user.IDRace WHERE IDWPUser = %d",
                    $currentUser
                ),
                ARRAY_A
            );

            return $results;
        } else if (intval($IDSeason) != 0) {
            // Afficher toutes les courses auxquelles l'utilisateur est inscrit pour une saison spécifique
            $results = $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT * FROM {$table} INNER JOIN cass_race_user ON cass_race.IDRace = cass_race_user.IDRace WHERE IDWPUser = %d AND IDSeason = %d",
                    $currentUser,
                    intval($IDSeason)
                ),
                ARRAY_A
            );

            return $results;
        } else {
            // Afficher toutes les courses auxquelles l'utilisateur est inscrit dans la saison actuelle
            $results = $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT * FROM {$table} INNER JOIN cass_race_user ON cass_race.IDRace = cass_race_user.IDRace WHERE IDWPUser = %d AND IDSeason = %d",
                    $currentUser,
                    $currentSeasonID
                ),
                ARRAY_A
            );

            return $results;
        }

    }

    function column_default($item, $column_name)
    {
        switch ($column_name) {
            case 'state':
                switch ($item[$column_name]) {
                    case 1:
                        return "Inscrit";
                        break;
                    case 2:
                        return "Validé";
                        break;
                    case 3:
                        return "Désinscrit";
                        break;
                    case 4:
                        return "Excusé";
                        break;
                }
            case 'IDWPUser_RL':
                $args = array(
                    'role' => 'CASS_RL',
                    'orderby' => 'user_nicename',
                    'order' => 'ASC'
                );
                $users = get_users($args);
                $retuned = "";
                foreach ($users as $user) {
                    if ($item[$column_name] == $user->id) {
                        $retuned = $user->display_name;
                    }
                }
                return $retuned;
            case 'IDLevel':
                $level = new Level();
                $level->loadFromId($item[$column_name]);
                return ReadGlobal($level->getName());
            case 'IDType':
                global $wpdb;
                //Type
                //Select all type
                $sql = "SELECT IDType,name FROM cass_type ORDER BY name ASC;";
                $rows = $wpdb->get_results($sql);
                foreach ($rows as $type) {
                    $selected = "";

                    if (intval($item[$column_name]) == intval($type->IDType)) {
                        return ReadGlobal($type->name);
                    }



                }
            default:
                return $item[$column_name];
        }
    }

    function column_cb($item)
    {
        return sprintf(
            '<input type="checkbox" name="element[]" value="%s" />',
            $item['IDType']
        );
    }
    protected function get_sortable_columns()
    {
        $sortable_columns = array(
            'name' => array('name', false),
            'state' => array('state', false),
            'start' => array('start', false),
            'level' => array('level', false),
            'IDType' => array('IDType', false),
            'IDWPUser_RL' => array('IDWPUser_RL', false),
        );
        return $sortable_columns;
    }

    // Sorting function
    function usort_reorder($a, $b)
    {
        // If no sort, default to user_login
        $orderby = (!empty($_GET['orderby'])) ? $_GET['orderby'] : 'user_login';

        // If no order, default to asc
        $order = (!empty($_GET['order'])) ? $_GET['order'] : 'asc';

        // Determine sort order
        $result = strcmp($a[$orderby], $b[$orderby]);

        // Send final sort direction to usort
        return ($order === 'asc') ? $result : -$result;
    }

    // Adding action links to column
    function column_name($item)
    {
        ?>
            <script>
                // The function below will start the confirmation dialog
                function DeleteRaceConfirmAction(IDType) {
                    let confirmAction = confirm("Voulez supprimer la course <?php echo $item['name'] ?>  ?");
                    if (confirmAction) {
                        var url = window.location.href;
                        url += "&action=delete&element=" + IDType;
                        location.href = url;
                    }
                }
            </script>

            <?php

            $actions = array(
                //Race
                'editrace_user' => sprintf('<a href="' . admin_url() . "admin.php?page=cass-admin-race-user-list&action=edit&IDRace=" . $item['IDRace'] . '">Participants</a>', $_REQUEST['page'], 'edit', $item['IDRace']),

            );

            return sprintf('%1$s %2$s', ReadGlobal($item['name']), $this->row_actions($actions));
    }

}