<?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);
    $email = $inputdata['email'];
    $password = $inputdata['password'];

    //verifier si le email existe avant conexion
    $verif_email=$db->prepare('SELECT COUNT(id) AS exist FROM user WHERE email=?');
    $verif_email->execute(array($email));
    $nbr="";
    while ($verif_emails = $verif_email->fetch()) {
        # code...
        $nbr=$verif_emails['exist'];
    }
    if ($nbr == 1) {
        // verifier si le password correspond
        $sql_user=$db->prepare('SELECT * FROM user WHERE email=?');
     
        $result=$sql_user->execute(array($email));

            $user = $sql_user->fetchObject();
            $var_data = (object) $user;
    
            $lastPassword = $var_data->{'password'};

            if(password_verify($password, $lastPassword)){
                echo(json_encode(['loginData' => $user]));
 
            }else{
                // mot de passe incorrect
                echo(json_encode(['errorlogin' => 1]));
            }
    } else {
        // email inexistant
        echo(json_encode(['errorlogin' => 2]));

    }
    
    

