<?php
// get_user_info.php

header("Content-Type: application/json; charset=UTF-8");

require 'security.php';
require 'logger.php';
require 'db.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method Not Allowed']);
    log_activity("Method Not Allowed on get_user_info.php from IP: " . $_SERVER['REMOTE_ADDR']);
    exit;
}

// Mendapatkan token dari header Authorization
$headers = apache_request_headers();
if (isset($headers['Authorization'])) {
    $authorizationHeader = $headers['Authorization'];
    // Mengambil token dari string "Bearer <token>"
    $token = str_replace("Bearer ", "", $authorizationHeader);
} else {
    http_response_code(401);
    echo json_encode(['error' => 'Authorization header missing']);
    log_activity("Authorization header missing in get_user_info.php");
    exit;
}

try {
    // 1) Cari user_id berdasarkan token
    $stmt = $pdo->prepare("SELECT user_id FROM tokens WHERE token = ? AND expires_at >= NOW()");
    $stmt->execute([$token]);
    $tokenData = $stmt->fetch();

    if (!$tokenData) {
        http_response_code(401);
        echo json_encode(['error' => 'Invalid or expired token']);
        log_activity("Invalid or expired token in get_user_info.php");
        exit;
    }

    $userId = $tokenData['user_id'];

    // 2) Ambil data user dari tabel users
    $stmt = $pdo->prepare("SELECT id,name, email, phone, namabank, cabang, norek FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    $userData = $stmt->fetch();

    if (!$userData) {
        http_response_code(404);
        echo json_encode(['error' => 'User not found']);
        log_activity("User not found in get_user_info.php");
        exit;
    }

    // 3) Response data user
    http_response_code(200);
    echo json_encode($userData);
    log_activity("User info retrieved for user ID '$userId'.");

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Server error']);
    log_activity("get_user_info.php error: " . $e->getMessage());
    exit;
}

?>