<?php

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use Firebase\JWT\JWT;

//Login
$app->post('/login', function (Request $request, Response $response) {


    $username = $request->getParam('username');
    $password = $request->getParam('password');

    $consulta = "SELECT id_user,username, id_rol FROM users WHERE username = '$username' and password = '$password'";
    try {

        // Instanciar la base de datos
        $db = new db();

        // Conexión
        $conn = $db->connect();
        $stmt = $conn->prepare($consulta);
        $stmt->execute();
        $result = $stmt->fetchObject();
        $db = null;

        if ($result->id_user) {
            $now = time();
            $future = strtotime('+6 month', $now);
            $secret = JWT_SECRET;
            $payload = [
                "jti" => $result->id_user,
                "iat" => $now,
                "exp" => $future
            ];
            $result->token = JWT::encode($payload, $secret, "HS256");
        }

        $response->getBody()->write(json_encode($result));

        return $response
            ->withHeader('Content-Type', 'application/json')
            ->withStatus(200);
    } catch (PDOException $e) {
        $error = array(
            "message" => $e->getMessage()
        );
        $response->getBody()->write(json_encode($error));
        return $response
            ->withHeader('Content-Type', 'application/json')
            ->withStatus(500);;
    }
});