<?php
    // required headers
    header("Access-Control-Allow-Origin: *");
    header("Content-Type: application/json; charset=UTF-8");
    header("Access-Control-Allow-Methods: POST");
    header("Access-Control-Max-Age: 3600");
    header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
    
    // files needed to connect to database
    include_once '../config/database.php';
    include_once '../objects/identite.php';
    
    // get database connection
    $database = new Database();
    $db = $database->getConnection();
    
    // instantiate user object
    $identite = new Identite($db);
   
    // get posted data
    $data = json_decode(file_get_contents("php://input"));
    
    // set product property values
    $identite->login = $data->login;
    $login_exists = $identite->loginExists();
    
    // check if email exists and if password is correct
    if($login_exists){
        $password = $identite->password;
        if($password==$data->password){
            session_start();
            $_SESSION['login']=$identite->login;
            $_SESSION['id']=$identite->id;
            http_response_code(200);
            echo json_encode(array( 
                "message" => "Successful login."
            ));
         }
         else{
            http_response_code(401);
            // tell the user login failed
            echo json_encode(array("message" => "Mot de passe incorrect"));
         }
        }
    
    
    // login failed
    else{
        // set response code
        http_response_code(401);
        // tell the user login failed
        echo json_encode(array("message" => "login inexistant."));
        
    }
    ?>
