<?php
session_start();
header('Access-Control-Allow-Origin:*');
header('Content-Type; application/json; charset=utf-8');
header('Access-control-Allow-Method: POST');
header('Access-control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-request-With');
include('db.php');
    $inputdata = json_decode(file_get_contents("php://input"), true);
    $nom = $inputdata['nom'];
    $pre = $inputdata['pre'];
    $email = $inputdata['email'];
    $password = $inputdata['password'];
    $code_parrain = $inputdata['code_parrain'];
   if (empty($code_parrain)) {
    # code...
    $code_parrain="vision million";
   }
    //verifier code parrain
    $parrain_code_perso=0;
    $verifParrain=$db->prepare('SELECT COUNT(id) AS nbr FROM user WHERE code_perso=?');
    $verifParrain->execute(array($code_parrain));
    while ($a = $verifParrain->fetch()) {
        # code...
        $parrain_code_perso=$a['nbr'];
    }
    if ($parrain_code_perso == 1) {
        function getUsernameFromEmail($emailp) {
            // Utilisation de la fonction explode pour diviser l'email en deux parties, séparées par le caractère @
            $parts = explode('@', $emailp);
        
            // Retourner la première partie (avant le @)
            return $parts[0];
        }
        $username = getUsernameFromEmail($email);
        # faire inscription avec ce parrain pour le filleul
        
        $verif=$db->prepare('INSERT INTO user (nom, pre, email, password, code_perso, code_parrain) VALUES(?,?,?,?,?,?)');
        $verif->execute(array($nom, $pre, $email, $password, $username, $code_parrain));
        if ($verif) {
            # code...
            echo(json_encode(['reponse' => 1]));
        }else {
            # code...
            echo(json_encode(['reponse' => 0]));
        }
    }else {
        # code parrain invalide...
        echo(json_encode(['reponse' => 10]));
    }
