<?php

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

function view_race_leader_all_courses_list_initialisation()
{
    global $wpdb;

    $table = new CASS_View_Race_Leader_All_Courses_List();
    ?> 
    <div class="wrap">
        <?php 
            $user = get_userdata($_GET["element"]);
            echo "<h2>Liste des courses (chef) pour le chef de course : ".$user->user_lastname. " ".$user->user_firstname;
    // Prepare table
    $table->prepare_items();
    // Display table
    $table->display();
    echo '</div></form>';
}

class CASS_View_Race_Leader_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'),
            'IDWPUser_RL' => __('Chef de course', 'cass-race-rl-content'),
            'level' => __('Niveau', 'cass-race-level-content'),
            'IDGroup' => __('Groupe', 'cass-race-group-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';

        return $wpdb->get_results(
            "SELECT DISTINCT cass_race_user.IDRace, name, cass_race.state,IDWPUser_RL,cass_race.level, cass_race.IDGroup, cass_race.IDType FROM {$table} INNER JOIN cass_race_user ON cass_race.IDRace = cass_race_user.IDRace WHERE IDWPUser_RL=".$_GET["element"].";",
            ARRAY_A
        );
    }
    function column_default($item, $column_name)
    {
        switch ($column_name) {
                case 'state':
                    switch ($item[$column_name]) {
                        case 1:
                            return "Brouillon";
                            break;
                        case 2:
                            return "Ouverte";
                            break;
                        case 3:
                            return "Confirmée";
                            break;                       
                        case 4:
                            return "Effectuée";
                            break;                          
                        case 5:
                            return "Annulée";
                            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 'level':
            case 'IDGroup':
                GLOBAL $wpdb;
                //Group
                //Select all group
                $sql = "SELECT IDGroup,name FROM cass_group ORDER BY name ASC;";
                $rows = $wpdb->get_results($sql);
                foreach ($rows as $group) {
                    $selected = "";

                    if (intval($item[$column_name]) == intval($group->IDGroup)) {
                        return $group->name;
                    }                
                }
            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 $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),
            'level' => array('level', false),
            'IDGroup' => array('IDGroup', 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', $item['name'], $this->row_actions($actions));
        }
        
}




