<?php
/**
 * Get User Detail API
 * Endpoint: /admin/adminapi/get_user_detail.php
 */
require_once(__DIR__ . '/includes/db.php');
require_once(__DIR__ . '/includes/auth.php');

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

// Require valid auth token
requireAuth();

try {
    $userId = isset($_GET['id']) ? intval($_GET['id']) : 0;

    if ($userId <= 0) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'Invalid user ID']);
        exit;
    }

    // Get user details - all columns
    $sql = "SELECT * FROM users WHERE id = ?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$userId]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        http_response_code(404);
        echo json_encode(['success' => false, 'error' => 'User not found']);
        exit;
    }

    // Get previous user ID
    $prevSql = "SELECT id FROM users WHERE id < ? ORDER BY id DESC LIMIT 1";
    $prevStmt = $pdo->prepare($prevSql);
    $prevStmt->execute([$userId]);
    $prevResult = $prevStmt->fetch(PDO::FETCH_ASSOC);
    $prevId = $prevResult ? (int)$prevResult['id'] : null;

    // Get next user ID
    $nextSql = "SELECT id FROM users WHERE id > ? ORDER BY id ASC LIMIT 1";
    $nextStmt = $pdo->prepare($nextSql);
    $nextStmt->execute([$userId]);
    $nextResult = $nextStmt->fetch(PDO::FETCH_ASSOC);
    $nextId = $nextResult ? (int)$nextResult['id'] : null;

    echo json_encode([
        'success' => true,
        'status' => true,
        'user' => $user,
        'navigation' => [
            'prev_id' => $prevId,
            'next_id' => $nextId
        ]
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
