<?php
require "config.php";
require "../vendor/autoload.php";

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

header('Content-Type: application/json');
//echo json_encode(["status" => "error", "message" => "Invalid credentials"]);

$data = json_decode(file_get_contents("php://input"));



if (!isset($data->email) || !isset($data->password)) {
    echo json_encode(["status" => "error", "message" => "Missing email or password"]);
    exit;
}

$email = $data->email;
$password = $data->password;

try {
    $stmt = $conn->prepare("SELECT id, password FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user || !password_verify($password, $user['password'])) {
        echo json_encode(["status" => "error", "message" => "Invalid credentials"]);
        exit;
    }

    // Generate JWT Token
    $payload = [
        "iss" => "your_domain.com", // Issuer
        "iat" => time(), // Issued at
        "exp" => time() + (7 * 24 * 60 * 60), // Expires in 7 days
        "sub" => $user['id'] // Subject (user ID)
    ];

    $jwt = JWT::encode($payload, JWT_SECRET_KEY, "HS256");

    echo json_encode(["status" => "success", "token" => $jwt]);
} catch (Exception $e) {
    echo json_encode(["status" => "error", "message" => $e->getMessage()]);
}
?>
