<?php
// get_profile.php: Fetches the authenticated user's profile data

define('TONSUI_LOADED', true);

// Include required files
require_once __DIR__ . '/session_init.php';
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';

// Set response headers
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');
header('Access-Control-Allow-Credentials: true');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');

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

// Function to send JSON response
function sendResponse($success, $message, $data = null, $statusCode = 200) {
    http_response_code($statusCode);
    $response = ['success' => $success, 'message' => $message];
    if ($data !== null) {
        $response['data'] = $data;
    }
    echo json_encode($response);
    exit;
}

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    error_log('Unauthorized access to profile - no session found');
    sendResponse(false, 'Authentication required', null, 401);
}

try {
    // Get user ID from session
    $userId = $_SESSION['user_id'];
    
    // Build SELECT list tolerant of schema diffs (e.g., kycStatus/account_number may be missing)
    $allFields = ['id','username','email','name','status','balance','total_earned','is_admin','created_at','updated_at'];
    $fields = $allFields;
    $hasKycStatus = false;
    $hasAccountNumber = false;
    $hasProfilePicture = false;
    $hasAccountCurrency = false;
    try {
        $ucols = $pdo->query("SHOW COLUMNS FROM users");
        while ($c = $ucols->fetch(PDO::FETCH_ASSOC)) {
            $f = strtolower($c['Field'] ?? '');
            if ($f === 'kycstatus') $hasKycStatus = true;
            if ($f === 'account_number') $hasAccountNumber = true;
            if ($f === 'profile_picture') $hasProfilePicture = true;
            if ($f === 'account_currency') $hasAccountCurrency = true;
        }
    } catch (Exception $e) { /* ignore */ }
    if ($hasKycStatus) {
        $fields = array_merge(['kycStatus'], $fields);
    }
    if ($hasAccountNumber) {
        $fields = array_merge(['account_number'], $fields);
    }
    if ($hasProfilePicture) {
        $fields = array_merge(['profile_picture'], $fields);
    }
    if ($hasAccountCurrency) {
        $fields = array_merge(['account_currency'], $fields);
    }

    $sql = "SELECT " . implode(', ', $fields) . " FROM users WHERE id = ?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$userId]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$user) {
        error_log("User not found in database - ID: $userId");
        sendResponse(false, 'User not found', null, 404);
    }
    
    // Sanitize user data before sending
    unset($user['password']); // Never send password hashes
    
    // Format dates
    if (isset($user['created_at'])) {
        $user['created_at'] = date('c', strtotime($user['created_at']));
    }
    if (isset($user['updated_at'])) {
        $user['updated_at'] = date('c', strtotime($user['updated_at']));
    }
    
    // Backfill KYC status string if missing using kyc_verified (if present)
    try {
        if (!isset($user['kycStatus']) || $user['kycStatus'] === null || $user['kycStatus'] === '') {
            $kvStmt = $pdo->prepare('SELECT kyc_verified FROM users WHERE id = ?');
            $kvStmt->execute([$userId]);
            $kv = $kvStmt->fetch(PDO::FETCH_ASSOC);
            if ($kv && array_key_exists('kyc_verified', $kv)) {
                $user['kycStatus'] = ((int)$kv['kyc_verified'] === 1) ? 'approved' : 'pending';
            }
        }
    } catch (Exception $e) { /* ignore */ }

    // If KYC is globally disabled, report as approved to clients
    if (isset($config['kyc_required']) && $config['kyc_required'] === false) {
        $user['kycStatus'] = 'approved';
    }

    // Fallback: if profile_picture is missing, try pulling from user_profiles.account_photo_path
    if (!isset($user['profile_picture']) || $user['profile_picture'] === null || $user['profile_picture'] === '') {
        try {
            $pfStmt = $pdo->prepare("SELECT account_photo_path FROM user_profiles WHERE user_id = ? ORDER BY id DESC LIMIT 1");
            $pfStmt->execute([$userId]);
            $pf = $pfStmt->fetch(PDO::FETCH_ASSOC);
            if ($pf && !empty($pf['account_photo_path'])) {
                $user['profile_picture'] = $pf['account_photo_path'];
                // Also expose snake_case field expected by some clients
                $user['account_photo_path'] = $pf['account_photo_path'];
            }
        } catch (Exception $e) { /* ignore */ }
    }

    // Provide alias for clients expecting snake_case
    if (isset($user['kycStatus']) && (!isset($user['kyc_status']) || $user['kyc_status'] === null)) {
        $user['kyc_status'] = $user['kycStatus'];
    }
    // Provide camelCase alias for profile picture used by frontend
    if (isset($user['profile_picture']) && (!isset($user['profilePicture']) || $user['profilePicture'] === null)) {
        $user['profilePicture'] = $user['profile_picture'];
    }
    // Ensure account_photo_path mirrors profile_picture if not explicitly set
    if ((!isset($user['account_photo_path']) || $user['account_photo_path'] === null || $user['account_photo_path'] === '') && isset($user['profile_picture']) && $user['profile_picture'] !== '') {
        $user['account_photo_path'] = $user['profile_picture'];
    }

    // Send success response with user data
    sendResponse(true, 'Profile retrieved successfully', [
        'user' => $user
    ]);
    
} catch (PDOException $e) {
    error_log('Database error in get_profile.php: ' . $e->getMessage());
    sendResponse(false, 'An error occurred while fetching profile', null, 500);
} catch (Exception $e) {
    error_log('Error in get_profile.php: ' . $e->getMessage());
    sendResponse(false, 'An unexpected error occurred', null, 500);
}
