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

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

header('Content-Type: application/json');

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

// Log incoming request
file_put_contents("login_log.txt", date("Y-m-d H:i:s") . " - Request: " . json_encode($data) . "\n", FILE_APPEND);

if (!isset($data->email) || !isset($data->password)) {
    $errorResponse = ["status" => "error", "message" => "Missing email or password"];
    file_put_contents("login_log.txt", date("Y-m-d H:i:s") . " - Error: Missing email or password\n", FILE_APPEND);
    echo json_encode($errorResponse);
    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'])) {
        $errorResponse = ["status" => "error", "message" => "Invalid credentials"];
        file_put_contents("login_log.txt", date("Y-m-d H:i:s") . " - Error: Invalid credentials\n", FILE_APPEND);
        echo json_encode($errorResponse);
        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");

    $successResponse = ["status" => "success", "token" => $jwt];

    // Log successful login
    file_put_contents("log.txt", date("Y-m-d H:i:s") . " - Login Successful: $email\n", FILE_APPEND);

    echo json_encode($successResponse);
} catch (Exception $e) {
    $errorResponse = ["status" => "error", "message" => $e->getMessage()];
    file_put_contents("login_log.txt", date("Y-m-d H:i:s") . " - Error: " . $e->getMessage() . "\n", FILE_APPEND);
    echo json_encode($errorResponse);
}
?>
