<?php
use Shuchkin\SimpleXLSXGen;
use Shuchkin\SimpleXLSX;

/*
 * RedirectJS - Redirect to a page in navigation
 *
 * @param string $url - The url of the page to redirect
 */
function redirectJS($url)
{
    echo "<script>location.href = '" . $url . "';</script>";
}


/*
 * exportModelRace - Export to XLSX
 *
 */
function exportModelRace()
{
    global $wpdb;

    //cass_race
    $races = [
        ['name', 'IDWPUser_RL', 'IDSeason', 'placeName', 'placeLocality', 'placeLatitude', 'placeLongitude', 'start', 'end', 'subscriptionStart', 'subscriptionEnd', 'IDLevel', 'meetingPlaceName', 'meetingPlaceLatitude', 'meetingPlaceLongitude', 'participantMin', 'participantMax', 'descriptionPublic', 'descriptionMemberSubscribed', 'formType', 'comment', 'IDType', 'IDGroup', 'IDWPUser_Deputy'],
        ['Le lac de Corin', 1, 1, 'Stade de foot', 'Sierre', 40.123, -74.456, '2023-10-31 09:00:00', '2023-10-31 17:00:00', '2023-10-01 00:00:00', '2023-10-10 00:00:00', 1, 'Devant le stade de foot', 40.123, -74.456, 5, 20, 'Public Description', 'Member Description', 1, 'Some Comment', 3, 1, 2]
    ];

    //cass_type
    $results = Type::selectAll();
    $types = [['IDType', 'name', 'description']];
    foreach ($results as $result) {
        $types[] = [$result->IDType, $result->name, $result->description];
    }

    //cass_level
    $results = Level::selectAll();
    $levels = [['IDLevel', 'name', 'level', 'description']];
    foreach ($results as $result) {
        $levels[] = [$result->IDLevel, $result->name, $result->level, $result->description];
    }

    //cass_group
    $results = Group::selectAll();
    $groups = [['IDGroup', 'name', 'description']];
    foreach ($results as $result) {
        $groups[] = [$result->IDGroup, $result->name, $result->description];
    }

    //cass_material
    $results = Material::selectAll();
    $materials = [['IDMaterial', 'name', 'description']];
    foreach ($results as $result) {
        $materials[] = [$result->IDMaterial, $result->name, $result->description];
    }

    //cass_season
    $results = Season::selectAll();
    $seasons = [['IDSeason', 'name', 'description']];
    foreach ($results as $result) {
        $seasons[] = [$result->IDSeason, $result->name, $result->description];
    }

    //RL
    $rl = [['IDWPUser_RL', 'display_name']];
    $args = array(
        'role' => 'CASS_RL',
        'orderby' => 'user_nicename',
        'order' => 'ASC'
    );
    $users = get_users($args);
    foreach ($users as $user) {
        $rl[] = [$user->id, $user->display_name];
    }

    $xlsx = SimpleXLSXGen::fromArray($races, "cass_race")->addSheet($types, "cass_type")->addSheet($groups, "cass_group")->addSheet($materials, "cass_material")->addSheet($seasons, "cass_season")->addSheet($rl, "user_rl")->addSheet($levels, "cass_level");

    //Create the folder of cass in the upload folder
    $directoryCass = 'cass';
    $upload_dir = wp_upload_dir();
    $upload_path = $upload_dir['basedir'];
    $subdirectory_path = $upload_path . '/' . $directoryCass;
    if (!file_exists($subdirectory_path)) {
        wp_mkdir_p($subdirectory_path);
    }

    $modelCSVExportFile = $subdirectory_path . "/" . "exportModelRace.xlsx";

    $xlsx->saveAs($modelCSVExportFile); // or downloadAs('books.xlsx') or $xlsx_content = (string) $xlsx 

    $url_complet = home_url() . '/wp-content/uploads/' . 'cass' . '/' . 'exportModelRace.xlsx';

    echo "<script>window.open('$url_complet', '_blank');</script>";
}

/*
 * importModelRace - Import from XLSX
 *
 */
function importModelRace($file)
{
    if ($file['error'] !== UPLOAD_ERR_OK) {
        echo "  
            <script>
                alert('Erreur lors de l\'importation du fichier.');
            </script>
        ";

    } else {
        $upload_dir = wp_upload_dir();
        ;
        $file_path = $upload_dir['basedir'] . '/cass/exportModelRace.xlsx';


        // Upload du fichier dans le répertoire uploads
        if (move_uploaded_file($file['tmp_name'], $file_path)) {
            echo "  
            <script>
                alert('Fichier importé avec succès.');
            </script>
        ";
        } else {
            echo "  
            <script>
                alert('Erreur lors de l\'importation du fichier.');
            </script>
        ";
        }

        if ($xlsx = SimpleXLSX::parse($file_path)) {
            //Retrieve the header values
            $header_values = $xlsx->rows()[0];

            for ($k = 1; $k < count($xlsx->rows()); $k++) {
                $row = $xlsx->rows()[$k];

                $race = new Race();
                foreach ($header_values as $index => $column_name) {
                    $cell_value = $row[$index];
                    $race->setState(1);

                    switch ($column_name) {
                        case 'name':
                            $race->setName(SantizeGlobal($cell_value));
                            break;
                        case 'IDSeason':
                            $race->setIDSeason(intval($cell_value));
                            break;
                        case 'IDWPUser_RL':
                            $race->setIDWPUser_RL(intval($cell_value));
                            break;
                        case 'placeName':
                            $race->setPlaceName(SantizeGlobal($cell_value));
                            break;
                        case 'placeLocality':
                            $race->setPlaceLocality(SantizeGlobal($cell_value));
                            break;
                        case 'placeLatitude':
                            $race->setPlaceLatitude(floatval($cell_value));
                            break;
                        case 'placeLongitude':
                            $race->setPlaceLongitude(floatval($cell_value));
                            break;
                        case 'start':
                            $race->setStart($cell_value);
                            break;
                        case 'end':
                            $race->setEnd($cell_value);
                            break;
                        case 'IDLevel':
                            $race->setIDLevel(intval($cell_value));
                            break;
                        case 'meetingPlaceName':
                            $race->setMeetingPlaceName(SantizeGlobal($cell_value));
                            break;
                        case 'meetingPlaceLatitude':
                            $race->setMeetingPlaceLatitude(floatval($cell_value));
                            break;
                        case 'meetingPlaceLongitude':
                            $race->setMeetingPlaceLongitude(floatval($cell_value));
                            break;
                        case 'participantMin':
                            $race->setParticipantMin(intval($cell_value));
                            break;
                        case 'participantMax':
                            $race->setParticipantMax(intval($cell_value));
                            break;
                        case 'descriptionPublic':
                            $race->setDescriptionPublic(SantizeGlobal($cell_value));
                            break;
                        case 'descriptionMemberSubscribed':
                            $race->setDescriptionMemberSubscribed(SantizeGlobal($cell_value));
                            break;
                        case 'formType':
                            $race->setFormType(intval($cell_value));
                            break;
                        case 'comment':
                            $race->setComment(SantizeGlobal($cell_value));
                            break;
                        case 'IDType':
                            $race->setIDType(intval($cell_value));
                            break;
                        case 'IDGroup':
                            $race->setIDGroup(intval($cell_value));
                            break;
                        case 'subscriptionStart':
                            $race->setSubscriptionStart($cell_value);
                            break;
                        case 'subscriptionEnd':
                            $race->setSubscriptionEnd($cell_value);
                            break;
                        case 'IDWPUser_Deputy':
                            $race->setIDWPUser_Deputy(intval($cell_value));
                            break;
                    }
                }

                $race->create();
            }
        } else {
            echo SimpleXLSX::parseError();
        }
    }
}

/*
 * SantizeGlobal - Sanitize the data
 *
 * @param string $url - the data to sanitize
 */
function SantizeGlobal($text)
{
    $data = $text;

    //Disable html
    $data = esc_html($data);

    //Disable javascript
    $data = esc_js($data);

    //Disable css
    $data = esc_attr($data);

    //sanitize_text_field
    $data = sanitize_text_field($data);

    $data = str_replace('\n', "\n", $data);

    return $data;
}

function ReadGlobal($text)
{
    $text = stripslashes($text);

   

   //$text = str_replace(["\r", "\n"], ['\\r', '\\n'], $text);

    return $text;
}

function exportParticipantListOfRaceMailOnly($IDRace){
    global $wpdb;

    $mails = [];

    $race = new Race();
    $race->loadFromId($IDRace);

    //Récupération des participants
    $sql = "
        SELECT IDWPUser FROM cass_race_user WHERE IDRace = %d;
    ";

    $sql = $wpdb->prepare($sql, $IDRace);
    $results = $wpdb->get_results($sql);

    foreach ($results as $result) {
        //Get user meta
        $user_meta = get_user_meta($result->IDWPUser);

        $args = array(
            'role' => 'CASS_MEMBER',
            'orderby' => 'user_nicename',
            'order' => 'ASC'
        );
        $users = get_users($args);
        $retuned = "";
        foreach ($users as $user) {
            if ($user->id == $result->IDWPUser) {
                $mails[] = $user->user_email;
            }
        }
    }

    return $mails;
}

function exportParticipantListOfRace($IDRace)
{
    global $wpdb;

    $race = new Race();
    $race->loadFromId($IDRace);

    //En-tetes
    $race_user = [
        ["Etat", "Nom", "Prénom", "Téléphone", "Email", "No Membre", "Niveau", "Commentaire ins."]
    ];

    //Récupération des participants
    $sql = "
        SELECT IDWPUser, state, commentInscription FROM cass_race_user WHERE IDRace = %d;
    ";

    $sql = $wpdb->prepare($sql, $IDRace);
    $results = $wpdb->get_results($sql);



    //For all results
    foreach ($results as $result) {
        //Get user meta
        $user_meta = get_user_meta($result->IDWPUser);

        $cassLevel = get_user_meta($result->IDWPUser, 'cassLevel', true);
        $cassTelephone = get_user_meta($result->IDWPUser, 'cassTelephone', true);
        $cassMemberNo = get_user_meta($result->IDWPUser, 'cassMemberNo', true);

        $args = array(
            'role' => 'CASS_MEMBER',
            'orderby' => 'user_nicename',
            'order' => 'ASC'
        );
        $users = get_users($args);
        $retuned = "";
        foreach ($users as $user) {
            if ($user->id == $result->IDWPUser) {
                $firstName = $user->user_firstname;
                $lastName = $user->user_lastname;
                $email = $user->user_email;
            }
        }

        //Add level
        $level = new Level();

        $level->loadFromId($cassLevel);
        $levelName = $level->getName();

        //State
        $stateName = "";
        switch ($result->state) {
            case 1:
                $stateName = "Inscrit";
                break;
            case 2:
                $stateName = "Validé";
                break;
            case 3:
                $stateName = "Annulé";
                break;
            case 4:
                $stateName = "Excusé";
                break;
        }

        //Add to array
        $newParticipant = [
            "Etat" => $stateName,
            "Nom" => $lastName,
            "Prénom" => $firstName,
            "Téléphone" => $cassTelephone,
            "Email" => $email,
            "No Membre" => $cassMemberNo,
            "Niveau" => $levelName,
            "Commentaire ins." => $result->commentInscription
        ];

        $race_user[] = $newParticipant;
    }


    //Sort
    //Remove the first element
    array_shift($race_user);
    function compareByStateAndLastName($a, $b) {
        // Compare by state
        $stateComparison = strcmp($a[0], $b[0]);
    
        // Since the state is the same, compare by last name
        return ($stateComparison == 0) ? strcmp($a[1], $b[1]) : $stateComparison;
    }
    
    usort($race_user, 'compareByStateAndLastName');
    //Add the first element
    array_unshift($race_user, ["Etat", "Nom", "Prénom", "Téléphone", "Email", "No Membre", "Niveau", "Commentaire ins."]);


    $xlsx = SimpleXLSXGen::fromArray($race_user, "Participants");

    //Create the folder of cass in the upload folder
    $directoryCass = 'cass';
    $upload_dir = wp_upload_dir();
    $upload_path = $upload_dir['basedir'];
    $subdirectory_path = $upload_path . '/' . $directoryCass;
    if (!file_exists($subdirectory_path)) {
        wp_mkdir_p($subdirectory_path);
    }

    $modelCSVExportFile = $subdirectory_path . "/" . "participants.xlsx";

    $xlsx->saveAs($modelCSVExportFile); // or downloadAs('books.xlsx') or $xlsx_content = (string) $xlsx 

    $url_complet = home_url() . '/wp-content/uploads/' . 'cass' . '/' . 'participants.xlsx';

    echo "<script>window.open('$url_complet', '_blank');</script>";
}