<?php
/**
 * get_user_info.php
 * 
 * Returns user information including KYC status and withdrawal PIN availability
 * Used to determine which withdrawal flow to show
 */

header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

// Reflect exact Origin for credentialed requests
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (!empty($origin)) {
    header('Access-Control-Allow-Origin: ' . $origin);
} else {
    $scheme = $_SERVER['REQUEST_SCHEME'] ?? 'https';
    $host = $_SERVER['HTTP_HOST'] ?? '';
    if (!empty($host)) {
        header('Access-Control-Allow-Origin: ' . $scheme . '://' . $host);
    }
}
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

define('TONSUI_LOADED', true);
require_once __DIR__ . '/session_init.php';
requireLogin(true);

require_once 'config.php';
require_once 'db.php';

try {
    $user_id = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 0;
    
    // Get user KYC status and basic info (schema-aware)
    $hasSusp = false; $hasTxSusp = false; $hasDormant = false;
    try { $hasSusp = $pdo->query("SHOW COLUMNS FROM users LIKE 'account_suspended'")->rowCount() > 0; } catch (Exception $e) {}
    try { $hasTxSusp = $pdo->query("SHOW COLUMNS FROM users LIKE 'transfers_suspended'")->rowCount() > 0; } catch (Exception $e) {}
    try { $hasDormant = $pdo->query("SHOW COLUMNS FROM users LIKE 'account_dormant'")->rowCount() > 0; } catch (Exception $e) {}
    $selFlags = ($hasSusp ? ', account_suspended' : '') . ($hasTxSusp ? ', transfers_suspended' : '') . ($hasDormant ? ', account_dormant' : '');

    $hasKycVerified = false; $hasKycStatus = false; $hasIsVerified = false; $hasCreatedAt = false;
    try { $hasKycVerified = $pdo->query("SHOW COLUMNS FROM users LIKE 'kyc_verified'")->rowCount() > 0; } catch (Exception $e) {}
    try { $hasKycStatus = $pdo->query("SHOW COLUMNS FROM users LIKE 'kycStatus'")->rowCount() > 0; } catch (Exception $e) {}
    try { $hasIsVerified = $pdo->query("SHOW COLUMNS FROM users LIKE 'is_verified'")->rowCount() > 0; } catch (Exception $e) {}
    try { $hasCreatedAt = $pdo->query("SHOW COLUMNS FROM users LIKE 'created_at'")->rowCount() > 0; } catch (Exception $e) {}

    if ($hasKycVerified) {
        $kycSelect = 'kyc_verified AS kyc_ok';
    } elseif ($hasKycStatus) {
        $kycSelect = "(CASE WHEN kycStatus='approved' THEN 1 ELSE 0 END) AS kyc_ok";
    } elseif ($hasIsVerified) {
        $kycSelect = 'is_verified AS kyc_ok';
    } else {
        $kycSelect = '1 AS kyc_ok'; // If no column, treat as verified to avoid breaking UI; backend still enforces
    }

    $createdSel = $hasCreatedAt ? ', created_at' : '';
    $sql = "SELECT id, username, email, $kycSelect, balance$createdSel$selFlags FROM users WHERE id = ?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$user_id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$user) {
        throw new Exception('User not found');
    }
    
    // Count active withdrawal PINs
    // Handle both schema variants safely:
    // - Legacy schema: boolean 'used' (0 = active)
    // - New schema: enum 'status' ('active','used','cancelled') with optional 'expiry_date'
    $has_status = false; $has_used = false; $has_expiry = false;
    try {
        $cols = $pdo->query("SHOW COLUMNS FROM withdrawal_pins");
        while ($c = $cols->fetch(PDO::FETCH_ASSOC)) {
            $f = strtolower($c['Field'] ?? '');
            if ($f === 'status') $has_status = true;
            if ($f === 'used') $has_used = true;
            if ($f === 'expiry_date') $has_expiry = true;
        }
    } catch (Exception $e) { /* ignore */ }

    if ($has_status) {
        // Prefer new schema
        $sql = "SELECT COUNT(*) as pin_count FROM withdrawal_pins WHERE user_id = ? AND status = 'active'";
        if ($has_expiry) {
            $sql .= " AND (expiry_date IS NULL OR expiry_date > NOW())";
        }
        $pinStmt = $pdo->prepare($sql);
        $pinStmt->execute([$user_id]);
    } elseif ($has_used) {
        // Fallback to legacy schema
        $pinStmt = $pdo->prepare(
            "SELECT COUNT(*) as pin_count FROM withdrawal_pins WHERE user_id = ? AND (used = 0 OR used IS NULL)"
        );
        $pinStmt->execute([$user_id]);
    } else {
        // Unknown schema, report zero without failing the whole endpoint
        $pinStmt = null;
    }

    $pinData = $pinStmt ? $pinStmt->fetch(PDO::FETCH_ASSOC) : ['pin_count' => 0];
    $pin_count = $pinData['pin_count'] ?? 0;
    
    echo json_encode([
        'success' => true,
        'user' => [
            'id' => $user['id'],
            'username' => $user['username'],
            'email' => $user['email'],
            'kyc_verified' => (int)($user['kyc_ok'] ?? 0),
            'balance' => (float)$user['balance'],
            'has_withdrawal_pins' => $pin_count > 0,
            'active_pin_count' => (int)$pin_count,
            'member_since' => $hasCreatedAt ? $user['created_at'] : null,
            'account_suspended' => $hasSusp ? (int)($user['account_suspended'] ?? 0) : 0,
            'transfers_suspended' => $hasTxSusp ? (int)($user['transfers_suspended'] ?? 0) : 0,
            'account_dormant' => $hasDormant ? (int)($user['account_dormant'] ?? 0) : 0
        ]
    ]);
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
