<?php
/**
 * Binance P2P Helper Functions
 */

// Check if user is logged in (admin)
function is_logged_in() {
    if (!isset($GLOBALS['adminAuth'])) {
        require_once __DIR__ . '/admin-auth.php';
        $GLOBALS['adminAuth'] = new AdminAuth($GLOBALS['pdo']);
    }
    return $GLOBALS['adminAuth']->isLoggedIn();
}

// Encrypt data
function encrypt_data($data, $key) {
    $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
    $encrypted = openssl_encrypt($data, 'aes-256-cbc', $key, 0, $iv);
    return base64_encode($encrypted . '::' . $iv);
}

// Decrypt data
function decrypt_data($data, $key) {
    list($encrypted_data, $iv) = explode('::', base64_decode($data), 2);
    return openssl_decrypt($encrypted_data, 'aes-256-cbc', $key, 0, $iv);
}

// Redirect if not logged in
function require_login() {
    if (!isset($GLOBALS['adminAuth'])) {
        require_once __DIR__ . '/admin-auth.php';
        $GLOBALS['adminAuth'] = new AdminAuth($GLOBALS['pdo']);
    }
    $GLOBALS['adminAuth']->requireLogin();
}

// Format currency amount
function format_currency($amount, $currency = 'USD') {
    $currency_symbols = [
        'USD' => '$',
        'EUR' => '€',
        'GBP' => '£',
        'MXN' => 'MX$',
        'USDC' => 'USDC ',
        'USDT' => 'USDT '
    ];
    
    $symbol = $currency_symbols[strtoupper($currency)] ?? strtoupper($currency) . ' ';
    return $symbol . number_format(floatval($amount), 2);
}

// Format date for display (using Nairobi timezone)
function format_date($date_string, $format = 'M j, Y g:i A') {
    if (empty($date_string) || $date_string === '0000-00-00 00:00:00') return 'N/A';
    
    try {
        // MySQL datetime strings don't include timezone info
        // We assume they are stored in UTC (since we set MySQL timezone to UTC)
        // Create DateTime object explicitly as UTC
        $date = DateTime::createFromFormat('Y-m-d H:i:s', $date_string, new DateTimeZone('UTC'));
        
        // If createFromFormat fails, try alternative parsing
        if (!$date) {
            // Try with microseconds if present
            $date = DateTime::createFromFormat('Y-m-d H:i:s.u', $date_string, new DateTimeZone('UTC'));
        }
        
        if (!$date) {
            // Last resort: use strtotime (less reliable)
            $timestamp = strtotime($date_string . ' UTC');
            if ($timestamp === false) {
                throw new Exception("Unable to parse date: $date_string");
            }
            $date = new DateTime('@' . $timestamp, new DateTimeZone('UTC'));
        }
        
        // Convert to Nairobi timezone
        $date->setTimezone(new DateTimeZone('Africa/Nairobi'));
        
        return $date->format($format);
    } catch (Exception $e) {
        // Fallback: just return the date string if conversion fails
        error_log("Error formatting date '$date_string': " . $e->getMessage());
        return $date_string;
    }
}

// Get status badge class
function get_status_badge_class($status) {
    $status_classes = [
        'pending' => 'warning',
        'waiting_payment' => 'info',
        'paid' => 'primary',
        'released' => 'success',
        'completed' => 'success',
        'canceled' => 'secondary',
        'cancelled' => 'secondary',
        'appeal' => 'danger',
        'processing' => 'info',
        'failed' => 'danger',
        'trading' => 'warning',
        'buyer_payed' => 'info',
        'buyer_paid' => 'info'
    ];
    
    return $status_classes[strtolower($status)] ?? 'secondary';
}

// Sanitize output
function sanitize($data) {
    return htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
}

// Get order status display name
function get_order_status_display($status) {
    $statuses = [
        'pending' => 'Pending',
        'waiting_payment' => 'Waiting Payment',
        'paid' => 'Paid',
        'released' => 'Released',
        'completed' => 'Completed',
        'canceled' => 'Canceled',
        'cancelled' => 'Cancelled',
        'appeal' => 'Appeal',
        'trading' => 'Pending Payment',
        'buyer_payed' => 'To be released',
        'buyer_paid' => 'To be released'
    ];
    
    return $statuses[strtolower($status)] ?? ucfirst($status);
}

// Get payment status display name
function get_payment_status_display($status) {
    $statuses = [
        'pending' => 'Pending',
        'processing' => 'Processing',
        'completed' => 'Completed',
        'failed' => 'Failed'
    ];
    
    return $statuses[strtolower($status)] ?? ucfirst($status);
}

