<?php

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

function view_race_list_initialisation()
{
    global $wpdb;

    echo "
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            document.getElementById('bulk-action-selector-top').disabled = true;
            document.getElementById('doaction').disabled = true;
            document.getElementById('bulk-action-selector-bottom').disabled = true;
            document.getElementById('doaction2').disabled = true;
        });
        
    </script>

    <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>
";



    //Delete element action
    if (isset($_GET["action"]) && $_GET["action"] = "delete" && isset($_GET["IDRace"]) && intval($_GET["IDRace"]) > 0) {
        $race = new Race();
        $race->setIDRace(intval($_GET["IDRace"]));
        $race->delete();
    }

    //Download model
    if (isset($_POST["downloadModel"]) && intval($_POST["downloadModel"]) == 1) {
        exportModelRace();
    }

    //Import model
    if (isset($_POST["importModel"]) && intval($_POST["importModel"]) == 1) {
        $file = $_FILES['modelFileUpload'];
        importModelRace($file);
    }

    $table = new CASS_View_Race_List();
    ?>
    <div class="wrap">
        <h2>Liste des courses</h2>
        <?php
        if (current_user_can('CASS_ADMIN')) {
            echo "

    <div class='form-container'>        
    <form action='#' method ='post'>
        <input type='hidden' id='downloadModel' name='downloadModel' value='1'>
            <button
                type='submit'
                class='button-secondary'
                id='refresh-cache'>Générer le modèle d'importation
            </button>
        </form>

        <form method='post' enctype='multipart/form-data'>
            <input type='hidden' id='importModel' name='importModel' value='1'>
            <input type='file' name='modelFileUpload' id='modelFileUpload'>
            <input type='submit' name='submit' value='Importer les courses'>
        </form>
    </div>
    ";

            $table->search_box('Rechercher par Adjoint', 'IDWPUser_Deputy');
            $table->search_box('Rechercher par CdC', 'IDWPUser_RL');

        }

        ?>
        <div class='form-container'>
            <form action='<?php echo admin_url() . "admin.php?page=cass-admin-race-edit"; ?>' method='POST'>
                <input type="hidden" id="action" name="action" value="create">
                <button type="submit" class="button-secondary" id="refresh-cache">Ajouter
                </button>
            </form>
            <form action='#' method='POST'>

                <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();

                    $rows = Season::selectAll();
                    $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>

                <button type="submit" class="button-secondary" id="refresh-cache">Filtrer
                </button>
            </form>
        </div>




        <?php
        // Prepare table
        $table->prepare_items();
        // Display table
        echo "<form id='cass-admin-race-list' method='post'>";
        echo '<input type="hidden" name="IDSeason" value="' . esc_attr($_POST['IDSeason'] ?? '') . '">';
        $table->display();
        echo "</form>";


}

class CASS_View_Race_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'),
            'IDWPUser_Deputy' => __('Adjoint', 'cass-race-deputy-content'),
            'start' => __('Début', 'cass-race-start-content'),
            'end' => __('Fin', 'cass-race-end-content'),
            'subscriptionEnable' => __('Ins. activée', 'cass-race-subscription-enable-content'),
            'subscriptionStart' => __('Ins. début', 'cass-race-start-content'),
            'subscriptionEnd' => __('Ins. fin', 'cass-race-end-content'),
            'subscriptionCount' => __('Nbre inscrit', 'cass-race-count-subscribed-content'),
            'IDLevel' => __('Niveau', 'cass-race-level-content'),
            'IDGroup' => __('Groupe', 'cass-race-group-content'),
            'IDType' => __('Type', 'cass-race-type-content'),
            'comment' => __('Commentaire', 'cass-race-comment-content'),
        );
        return $columns;
    }



    public function get_bulk_actions()
    {
        if (current_user_can('CASS_ADMIN')) {
            return array(
                'delete' => __('Supprimer', 'your-textdomain'),
                'open' => __('Ouvrir', 'your-textdomain'),

            );
        } else {
            return null;
        }

    }


    function prepare_items()
    {
        echo "HHAH  :" + $_POST["IDSeason"];


        //Result of bulk action
        $action = $this->current_action();

        $search_CdC = isset($_POST['IDWPUser_RL-search-input']) ? $_POST['IDWPUser_RL-search-input'] : '';
        $search_Deputy = isset($_POST['IDWPUser_Deputy-search-input']) ? $_POST['IDWPUser_Deputy-search-input'] : '';

        $selected_ids = isset($_POST[$this->_args['singular']]) ? $_POST[$this->_args['singular']] : array();

        // Faire quelque chose avec les IDs
        foreach ($selected_ids as $id) {
            // Traitement pour chaque ID
            echo "ID sélectionné : " . $id . "<br>";
        }

        switch ($action) {
            case 'delete':
                //List of ID

                break;
            case 'open':
                $this->handle_bulk_open();
                break;
        }

        $this->table_data = $this->get_table_data($search_CdC, $search_Deputy);

        $columns = $this->get_columns();
        $hidden = array('ID');
        $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($search_CdC, $search_Deputy)
    {
        global $wpdb;

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

        // Obtenez l'ID de la saison en cours
        $currentSeasonID = intval($season->getCurrentSeason());

        $results = null;

        // Récupération de l'ID de la saison
        $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") {
            // Sélectionner toutes les courses
            $results = $wpdb->get_results(
                "SELECT * FROM {$table}",
                ARRAY_A
            );
        } else if (intval($IDSeason) != 0) {
            // Sélectionner les courses pour une saison spécifique
            $results = $wpdb->get_results(
                $wpdb->prepare("SELECT * FROM {$table} WHERE IDSeason = %d", intval($IDSeason)),
                ARRAY_A
            );
        } else {
            // Si aucune condition, retourner toutes les courses par défaut
            $results = $wpdb->get_results(
                "SELECT * FROM {$table}",
                ARRAY_A
            );
        }




        //Filter on CdC or Deputy
        $filtered_data = array();

        // Charger tous les utilisateurs avec le rôle 'CASS_MEMBER'
        $args = array(
            'role' => 'CASS_MEMBER',
            'orderby' => 'user_nicename',
            'order' => 'ASC'
        );
        $users = get_users($args);

        for ($i = 0; $i < count($results); $i++) {
            $result = $results[$i];

            $ItemCdCName = "";
            $ItemDeputyName = "";

            foreach ($users as $user) {
                if ($result['IDWPUser_RL'] == $user->id) {
                    $ItemCdCName = $user->last_name . " " . $user->first_name;
                }
                if ($result['IDWPUser_Deputy'] == $user->id) {
                    $ItemDeputyName = $user->last_name . " " . $user->first_name;
                }
            }

            if ($search_CdC != "" && $search_Deputy != "") {
                if (strpos($ItemCdCName, $search_CdC) !== false && strpos($ItemDeputyName, $search_Deputy) !== false) {
                    $filtered_data[] = $result;
                }
            } else if ($search_CdC != "") {
                if (strpos($ItemCdCName, $search_CdC) !== false) {
                    $filtered_data[] = $result;
                }
            } else if ($search_Deputy != "") {
                if (strpos($ItemDeputyName, $search_Deputy) !== false) {
                    $filtered_data[] = $result;
                }
            } else {
                $filtered_data[] = $result;
            }
        }

        return $filtered_data;
    }

    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->last_name . " " . $user->first_name;
                    }
                }
                return $retuned;
            case 'IDWPUser_Deputy':
                $args = array(
                    'role' => 'CASS_MEMBER',
                    'orderby' => 'user_nicename',
                    'order' => 'ASC'
                );
                $users = get_users($args);
                $retuned = "";
                foreach ($users as $user) {
                    if ($item[$column_name] == $user->id) {
                        $retuned = $user->last_name . " " . $user->first_name;
                    }
                }
                return $retuned;
            case 'start':
                return $item[$column_name];
            case 'end':
                return $item[$column_name];
            case 'subscriptionCount':
                return Race_User::countNumberMemberOfCourseSubsribed(intval($item['IDRace']));
            case 'IDLevel':
                $level = new Level();
                $level->loadFromId($item[$column_name]);
                return ReadGlobal($level->getName());

            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 ReadGlobal($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 ReadGlobal($type->name);
                    }

                }

            case 'comment':
                return ReadGlobal($item[$column_name]);

            case 'subscriptionEnable':
                return $item[$column_name] == 1 ? "Oui" : "Non";
            default:
                return $item[$column_name];
        }
    }

    public function column_cb($item)
    {
        return sprintf(
            '<input type="checkbox" name="%1$s[]" value="%2$s" />',
            $this->_args['singular'],
            $item['ID']
        );
    }


    public function get_sortable_columns()
    {

        $sortable_columns = array(
            'name' => array('name', false),
            'state' => array('state', false),
            'start' => array('start', false),
            'end' => array('end', false),
            'subscriptionEnable' => array('subscriptionEnable', false),
            'subscriptionStart' => array('subscriptionStart', false),
            'subscriptionEnd' => array('subscriptionEnd', false),
            'IDLevel' => array('IDLevel', false),
            'IDGroup' => array('IDGroup', false),
            'IDType' => array('IDType', false),
            'IDWPUser_RL' => array('IDWPUser_RL', false),
            'IDWPUser_Deputy' => array('IDWPUser_Deputy', false),
            'subscriptionCount' => array('subscriptionCount', 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(IDRace) {
                    let confirmAction = confirm("Voulez supprimer la course sélectionnée ?");
                    if (confirmAction) {
                        var url = window.location.href;
                        url += "&action=delete&IDRace=" + IDRace;
                        location.href = url;
                    }
                }
            </script>

            <?php

            $actions = array(
                //Race
                'edit' => sprintf('<a href="' . admin_url() . "admin.php?page=cass-admin-race-edit&action=edit&IDRace=" . $item['IDRace'] . '">Edit</a>', $_REQUEST['page'], 'edit', $item['IDRace']),
                'delete' => sprintf('<a onclick="DeleteRaceConfirmAction(' . $item['IDRace'] . ')" href="#">' . __('Delete', 'cass-admin-race-edit') . '</a>', $_REQUEST['page'], 'delete', $item['IDRace']),
                'editmaterial' => sprintf('<a href="' . admin_url() . "admin.php?page=cass-admin-race-editmaterial&action=edit&IDRace=" . $item['IDRace'] . '">Matériaux</a>', $_REQUEST['page'], 'edit', $item['IDRace']),
                '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));
    }


    function search_box($text, $input_id)
    {
        $input_id = $input_id . '-search-input';

        echo '<form method="post">';
        echo '<p class="search-box">';
        echo '<input type="hidden" name="IDSeason" value="' . esc_attr($_POST['IDSeason'] ?? '') . '">';
        echo '<label class="screen-reader-text" for="' . esc_attr($input_id) . '">' . $text . ':</label>';
        echo '<input type="search" id="' . esc_attr($input_id) . '" name="' . esc_attr($input_id) . '" value="' . esc_attr($_REQUEST[$input_id] ?? '') . '" />';
        echo '<button type="submit" class="button">' . esc_attr($text) . '</button>';
        echo '</p>';
        echo '</form>';
    }
}





