<?php
// Liste des encodages possibles
$enclist = array(
    'UTF-8', 'ASCII',
    'ISO-8859-1', 'ISO-8859-15',
    'Windows-1252'
);

// Lecture brute du contenu
$content = file_get_contents($_FILES['file']['tmp_name']);

// Détection de l'encodage
$encodage = mb_detect_encoding($content, ['UTF-8','ISO-8859-1','ISO-8859-15','Windows-1252'], true);
if ($encodage === false || $encodage === 'ASCII') {
    $encodage = 'Windows-1252';
}
if ($encodage !== 'UTF-8') {
    $content = iconv($encodage, 'UTF-8//IGNORE', $content);
}

// Suppression d'une éventuelle BOM UTF-8
$content = preg_replace('/^\xEF\xBB\xBF/', '', $content);

// Création d’un fichier temporaire avec le contenu converti
$tmp_utf8_file = tempnam(sys_get_temp_dir(), 'utf8_');
file_put_contents($tmp_utf8_file, $content);

// Début du traitement
echo '<h1>' . ELEVINSTALL . '</h1>';

$id = 1;
$cdata5 = $cdata6 = $cdata7 = $cdata8 = 0;

if (($handle = fopen($tmp_utf8_file, "r")) !== false) {
    while (($data = fgetcsv($handle, 1000, ";")) !== false) {
        include('database_datainput_check.php');

        // Sécuriser les variables manquantes
        $att_code = isset($att_code) ? $att_code : '';
        $att_ident = isset($att_ident) ? $att_ident : '';
        $att_mdp = isset($att_mdp) ? $att_mdp : '';
        $att_mail = isset($att_mail) ? $att_mail : '';
        $att_resp_nom = isset($att_resp_nom) ? $att_resp_nom : '';
        $att_add1 = isset($att_add1) ? $att_add1 : '';
        $att_add2 = isset($att_add2) ? $att_add2 : '';
        $att_cpostal = isset($att_cpostal) ? $att_cpostal : '';
        $att_ville = isset($att_ville) ? $att_ville : '';

        // Nettoyage des données
        $att0 = mysqli_real_escape_string($bdd, $data[0]);
        $att1 = mysqli_real_escape_string($bdd, $data[1]);
        $att2 = mysqli_real_escape_string($bdd, $data[4]);
        $att3 = mysqli_real_escape_string($bdd, $data[2]);
        $att4 = mysqli_real_escape_string($bdd, $data[3]);

        // Format date de naissance
        $jour = substr($att3, 0, 2);
        $mois = substr($att3, 3, 2);
        $annee = substr($att3, 6, 4);

        // Traitement sexe
        $att4 = strtoupper($att4);
        if ($att4 !== 'F') $att4 = 'M';

        // Gestion identifiants dupliqués
        if (mysqli_num_rows(mysqli_query($bdd, "SELECT * FROM ".$prefix."_user WHERE login = '$att_code'")) > 0 || $att_code == 'reserver') {
            $att_code = '';
        }

        if (mysqli_num_rows(mysqli_query($bdd, "SELECT * FROM ".$prefix."_user WHERE login = '$att_ident'")) > 0 || $att_ident == 'reserver') {
            $att_ident = '';
        }

        // Génération du mot de passe
        if (!isset($att_mail)) $att_mail = "";
        if ($att_mdp == "") {
            $att_mdp = mb_strtolower(substr(strToNoAccent($att1), 0, 1), 'UTF-8') . $jour . $mois . $annee;
        }

        // Salage et hash
        do {
            $sel = bin2hex(random_bytes(16));
        } while ($sel === '0');

        $hashed_password = hash('sha256', $att_mdp . $sel);

        // Insertion
        mysqli_query($bdd, "
            INSERT INTO ".$prefix."_elevesmaj (
                eleves_id, nom, prenom, division, naissance, sexe, code, mdp, sel, mail, id_perso, resp_nom, add1, add2, cpostal, ville, categ
            ) VALUES (
                '".$id."', '".$att0."', '".$att1."', '".$att2."', '".$annee."-".$mois."-".$jour."', 
                '".$att4."', '".$att_code."', '".$hashed_password."', '".$sel."', '".$att_mail."', '".$att_ident."', '$att_resp_nom', '$att_add1', '$att_add2', '$att_cpostal', '$att_ville', '1'
            )
        ");

        $id++;

        if (!empty($data[5])) $cdata5 = 1;
        if (!empty($data[6])) $cdata6 = 1;
        if (!empty($data[7])) $cdata7 = 1;
        if (!empty($data[8])) $cdata8 = 1;
    }
    fclose($handle);
    unlink($tmp_utf8_file);
}
?>