<?php
session_start();
require_once 'config/database.php';

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'error' => 'Unauthorized access']);
    exit();
}

// Check if this is a POST request with action
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'get_user') {
    $user_id = intval($_POST['user_id']);
    
    if ($user_id <= 0) {
        echo json_encode(['success' => false, 'error' => 'Invalid user ID']);
        exit();
    }
    
    try {
        $database = new Database();
        $conn = $database->getConnection();
        
        // Get user details
        $stmt = $conn->prepare("SELECT 
            id, username, firstname, middlename, lastname, email, phone,
            account_number, account_type, status, balance, currency, nationality,
            date_of_birth, address, profile_photo, imf_code, swift_code,
            cot_code, transaction_pin, imf_enabled, swift_enabled, cot_enabled,
            created_at, updated_at
        FROM users WHERE id = ?");
        
        $stmt->execute([$user_id]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($user) {
            // Format dates for display
            if ($user['date_of_birth']) {
                $user['date_of_birth'] = date('Y-m-d', strtotime($user['date_of_birth']));
            }
            if ($user['created_at']) {
                $user['created_at'] = date('Y-m-d H:i:s', strtotime($user['created_at']));
            }
            if ($user['updated_at']) {
                $user['updated_at'] = date('Y-m-d H:i:s', strtotime($user['updated_at']));
            }
            
            echo json_encode(['success' => true, 'user' => $user]);
        } else {
            echo json_encode(['success' => false, 'error' => 'User not found']);
        }
        
        $database->closeConnection();
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
    }
    
} else {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Invalid request']);
}
?>
