<?php
/**
 * Wallet Helper Functions
 * File: app/Helpers/WalletHelper.php
 * 
 * Utility functions for wallet operations across the application
 */

class WalletHelper {
    
    /**
     * Format currency amount
     */
    public static function formatMoney($amount, $currency = 'NGN') {
        $amount = floatval($amount);
        
        if ($currency === 'NGN') {
            return '₦' . number_format($amount, 2);
        }
        
        return $currency . ' ' . number_format($amount, 2);
    }
    
    /**
     * Get wallet balance for display
     */
    public static function getDisplayBalance($user_id) {
        $wallet = new Wallet();
        $balance = $wallet->getBalance($user_id);
        return self::formatMoney($balance);
    }
    
    /**
     * Get pending balance for display
     */
    public static function getDisplayPendingBalance($user_id) {
        $wallet = new Wallet();
        $pending = $wallet->getPendingBalance($user_id);
        return self::formatMoney($pending);
    }
    
    /**
     * Check if user has sufficient balance
     */
    public static function hasSufficientBalance($user_id, $required_amount) {
        $wallet = new Wallet();
        $balance = $wallet->getBalance($user_id);
        return $balance >= floatval($required_amount);
    }
    
    /**
     * Get transaction type label
     */
    public static function getTransactionTypeLabel($type) {
        $labels = [
            'rental_payment' => 'Rental Payment',
            'security_deposit' => 'Security Deposit',
            'security_refund' => 'Security Refund',
            'commission' => 'Platform Commission',
            'vendor_earning' => 'Rental Earning',
            'withdrawal' => 'Withdrawal',
            'top_up' => 'Wallet Top-up',
            'dispute_deduction' => 'Dispute Deduction',
            'cancellation_refund' => 'Cancellation Refund',
            'admin_fee' => 'Admin Fee'
        ];
        
        return $labels[$type] ?? ucwords(str_replace('_', ' ', $type));
    }
    
    /**
     * Get transaction category badge class
     */
    public static function getCategoryBadgeClass($category) {
        return $category === 'credit' ? 'badge-success' : 'badge-danger';
    }
    
    /**
     * Get status badge class
     */
    public static function getStatusBadgeClass($status) {
        $classes = [
            'completed' => 'badge-success',
            'pending' => 'badge-warning',
            'failed' => 'badge-danger',
            'reversed' => 'badge-secondary'
        ];
        
        return $classes[$status] ?? 'badge-secondary';
    }
    
    /**
     * Format transaction reference for display
     */
    public static function formatReference($reference) {
        // Show only last 8 characters for cleaner display
        return '...' . substr($reference, -8);
    }
    
    /**
     * Get full transaction reference (for copying)
     */
    public static function getFullReference($reference) {
        return $reference;
    }
    
    /**
     * Calculate vendor earning after commission
     */
    public static function calculateVendorEarning($rental_amount, $commission_percentage) {
        $rental_amount = floatval($rental_amount);
        $commission_percentage = floatval($commission_percentage);
        
        $commission = ($rental_amount * $commission_percentage) / 100;
        $vendor_earning = $rental_amount - $commission;
        
        return [
            'rental_amount' => $rental_amount,
            'commission_percentage' => $commission_percentage,
            'commission_amount' => $commission,
            'vendor_earning' => $vendor_earning
        ];
    }
    
    /**
     * Get wallet statistics for dashboard cards
     */
    public static function getDashboardStats($user_id) {
        $wallet = new Wallet();
        $stats = $wallet->getStats($user_id);
        
        return [
            'balance' => self::formatMoney($stats['balance'] ?? 0),
            'balance_raw' => floatval($stats['balance'] ?? 0),
            'total_earned' => self::formatMoney($stats['total_earned'] ?? 0),
            'total_withdrawn' => self::formatMoney($stats['total_withdrawn'] ?? 0),
            'pending_balance' => self::formatMoney($stats['pending_balance'] ?? 0),
            'total_transactions' => $stats['total_transactions'] ?? 0,
            'earnings_30_days' => self::formatMoney($stats['earnings_30_days'] ?? 0)
        ];
    }
    
    /**
     * Validate bank account number
     */
    public static function validateAccountNumber($account_number) {
        // Nigerian bank account numbers are 10 digits
        return preg_match('/^\d{10}$/', $account_number);
    }
    
    /**
     * Validate withdrawal amount
     */
    public static function validateWithdrawalAmount($user_id, $amount, $min_withdrawal = 1000) {
        $amount = floatval($amount);
        
        if ($amount < $min_withdrawal) {
            return [
                'valid' => false,
                'message' => "Minimum withdrawal amount is ₦" . number_format($min_withdrawal, 2)
            ];
        }
        
        $wallet = new Wallet();
        $balance = $wallet->getBalance($user_id);
        
        if ($amount > $balance) {
            return [
                'valid' => false,
                'message' => "Insufficient balance. Available: " . self::formatMoney($balance)
            ];
        }
        
        return [
            'valid' => true,
            'message' => 'Valid withdrawal amount'
        ];
    }
    
    /**
     * Get Nigerian banks list
     */
    public static function getNigerianBanks() {
        return [
            'Access Bank',
            'Citibank',
            'Ecobank Nigeria',
            'Fidelity Bank Nigeria',
            'First Bank of Nigeria',
            'First City Monument Bank',
            'Globus Bank',
            'Guaranty Trust Bank',
            'Heritage Bank',
            'Keystone Bank',
            'Polaris Bank',
            'Providus Bank',
            'Stanbic IBTC Bank',
            'Standard Chartered Bank',
            'Sterling Bank',
            'Suntrust Bank',
            'Union Bank of Nigeria',
            'United Bank for Africa',
            'Unity Bank',
            'Wema Bank',
            'Zenith Bank'
        ];
    }
    
    /**
     * Log wallet activity
     */
    public static function logActivity($user_id, $action, $details = []) {
        error_log("Wallet Activity - User: {$user_id}, Action: {$action}, Details: " . json_encode($details));
        
        // You can also save to a wallet_activity_log table if needed
    }
}