<?php
/**
 * ================================================================
 * WALLET PROCESSOR V4.0 - COMPLETE PAYMENT SYSTEM
 * ================================================================
 * File: app/Core/WalletProcessor.php
 * 
 * Handles the complete 4-table wallet system:
 * 1. online_payments - Raw gateway transactions
 * 2. order_payment_breakdown - 3 records per payment (customer/vendor/admin)
 * 3. wallet_transactions - Immutable ledger (ALL financial events)
 * 4. wallets - Fast balance lookup with analytics
 * 
 * Key Features:
 * - 2-record transaction logging at payment (rental + security)
 * - Tracks customer total_spent separately
 * - Reverses spending on cancellation
 * - Complete audit trail
 * ================================================================
 */

class WalletProcessor {
    private $db;
    
    public function __construct() {
        $this->db = Database::getInstance();
    }
    
    /**
     * ================================================================
     * PROCESS PAYMENT - Called from payment-callback.php
     * ================================================================
     * Creates:
     * - 3 records in order_payment_breakdown (status = onhold)
     * - 2 records in wallet_transactions (rental + security)
     * - Updates customer wallet (security_onhold + total_spent)
     * ================================================================
     */
    public function processPayment($order_id, $payment_id, $booking) {
        try {
            $this->db->beginTransaction();
            
            $rental_amount = floatval($booking['subtotal']);
            $security_deposit = floatval($booking['security_deposit']);
            $total_amount = floatval($booking['total_amount']);
            
            // Get commission from booking (category-based) or default to 10%
            $commission_rate = isset($booking['commission_percentage']) ? floatval($booking['commission_percentage']) : 10.00;
            $platform_commission = isset($booking['platform_commission']) ? floatval($booking['platform_commission']) : ($rental_amount * ($commission_rate / 100));
            $vendor_earning = $rental_amount - $platform_commission;
            
            // Get user IDs
            $order = $this->db->fetch("
                SELECT o.id, o.order_number,
                       c.id as customer_id, c.user_id as customer_user_id, 
                       v.user_id as vendor_user_id
                FROM orders o
                JOIN customers c ON o.customer_id = c.id
                JOIN vendors v ON o.vendor_id = v.id
                WHERE o.id = ?
            ", [$order_id]);
            
            if (!$order) {
                throw new Exception("Order #{$order_id} not found");
            }
            
            // Get admin user ID
            $admin = $this->db->fetch("SELECT id FROM users WHERE user_type = 'admin' ORDER BY id ASC LIMIT 1");
            $admin_user_id = $admin['id'] ?? 1;
            
            $source = $booking['payment_gateway'] ?? 'paystack';
            
            // ========================================
            // STEP 1: CREATE 3 BREAKDOWN RECORDS
            // ========================================
            
            // Record 1: Customer security deposit
            $this->db->execute("
                INSERT INTO order_payment_breakdown 
                (order_id, payment_id, customer_id, user_id, type, amount, total_amount, status, source)
                VALUES (?, ?, ?, ?, 'security_deposit', ?, ?, 'onhold', ?)
            ", [$order_id, $payment_id, $order['customer_id'], $order['customer_user_id'], 
                $security_deposit, $total_amount, $source]);
            
            $security_breakdown_id = $this->db->lastInsertId();
            
            // Record 2: Vendor rental earning
            $this->db->execute("
                INSERT INTO order_payment_breakdown 
                (order_id, payment_id, customer_id, user_id, type, amount, total_amount, status, source)
                VALUES (?, ?, ?, ?, 'rental', ?, ?, 'onhold', ?)
            ", [$order_id, $payment_id, $order['customer_id'], $order['vendor_user_id'], 
                $vendor_earning, $total_amount, $source]);
            
            $rental_breakdown_id = $this->db->lastInsertId();
            
            // Record 3: Admin commission
            $this->db->execute("
                INSERT INTO order_payment_breakdown 
                (order_id, payment_id, customer_id, user_id, type, amount, total_amount, status, source)
                VALUES (?, ?, ?, ?, 'platform_commission', ?, ?, 'onhold', ?)
            ", [$order_id, $payment_id, $order['customer_id'], $admin_user_id, 
                $platform_commission, $total_amount, $source]);
            
            // ========================================
            // STEP 2: GET/CREATE ALL WALLETS (CUSTOMER, VENDOR, ADMIN)
            // ========================================
            $customer_wallet = $this->getOrCreateWallet($order['customer_user_id'], 'customer');
            $vendor_wallet = $this->getOrCreateWallet($order['vendor_user_id'], 'vendor');
            $admin_wallet = $this->getOrCreateWallet($admin_user_id, 'admin');
            
            // ========================================
            // STEP 3: CREATE 2 WALLET TRANSACTIONS
            // ========================================
            
            // Transaction 1: Item Rental Payment (affects total_spent)
            $reference_rental = 'RENT-' . $order['order_number'] . '-' . time();
            
            $this->db->execute("
                INSERT INTO wallet_transactions 
                (user_id, wallet_id, order_id, breakdown_id, transaction_type, category, 
                 amount, balance_before, balance_after, description, reference, status)
                VALUES (?, ?, ?, ?, 'item_rental', 'debit', ?, 0, 0, ?, ?, 'completed')
            ", [
                $order['customer_user_id'], 
                $customer_wallet['id'], 
                $order_id, 
                $rental_breakdown_id,
                $rental_amount,
                "Rental payment for Order #{$order['order_number']}",
                $reference_rental
            ]);
            
            // Transaction 2: Security Deposit Held (affects security_onhold)
            $sec_before = floatval($customer_wallet['security_onhold']);
            $sec_after = $sec_before + $security_deposit;
            $reference_security = 'SEC-HOLD-' . $order['order_number'] . '-' . time();
            
            $this->db->execute("
                INSERT INTO wallet_transactions 
                (user_id, wallet_id, order_id, breakdown_id, transaction_type, category, 
                 amount, balance_before, balance_after, description, reference, status)
                VALUES (?, ?, ?, ?, 'security_deposit_held', 'debit', ?, ?, ?, ?, ?, 'completed')
            ", [
                $order['customer_user_id'], 
                $customer_wallet['id'], 
                $order_id, 
                $security_breakdown_id,
                $security_deposit,
                $sec_before,
                $sec_after,
                "Security deposit held for Order #{$order['order_number']}",
                $reference_security
            ]);
            
            // ========================================
            // STEP 4: UPDATE CUSTOMER WALLET
            // ========================================
            
            // Check if this is a wallet payment (needs balance deduction)
            $is_wallet_payment = (isset($booking['payment_gateway']) && $booking['payment_gateway'] === 'wallet');
            
            if ($is_wallet_payment) {
                // Wallet payment - deduct from balance AND update security_onhold + total_spent
                $this->db->execute("
                    UPDATE wallets 
                    SET balance = balance - ?,
                        security_onhold = security_onhold + ?,
                        total_spent = total_spent + ?,
                        updated_at = NOW()
                    WHERE id = ?
                ", [$total_amount, $security_deposit, $rental_amount, $customer_wallet['id']]);
                
                error_log("✅ Wallet payment processed - Balance deducted: ₦{$total_amount}");
            } else {
                // Online payment (Paystack) - only update security_onhold + total_spent (balance not affected)
                $this->db->execute("
                    UPDATE wallets 
                    SET security_onhold = security_onhold + ?,
                        total_spent = total_spent + ?,
                        updated_at = NOW()
                    WHERE id = ?
                ", [$security_deposit, $rental_amount, $customer_wallet['id']]);
                
                error_log("✅ Online payment processed - No balance deduction");
            }
            
            $this->db->commit();
            
            error_log("✅ WalletProcessor::processPayment SUCCESS - Order #{$order_id}");
            return true;
            
        } catch (Exception $e) {
            if ($this->db->inTransaction()) {
                $this->db->rollback();
            }
            error_log("❌ WalletProcessor::processPayment ERROR: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * ================================================================
     * PROCESS COMPLETED ORDER - Called from complete-rental.php
     * ================================================================
     * Changes:
     * - order_payment_breakdown status → 'released'
     * - Creates 3 wallet_transactions (refund security, vendor earning, admin commission)
     * - Updates all 3 wallets
     * ================================================================
     */
    public function processCompletedOrder($order_id) {
        try {
            $this->db->beginTransaction();
            
            // Get order details
            $order = $this->db->fetch("
                SELECT o.order_number, c.user_id as customer_user_id
                FROM orders o
                JOIN customers c ON o.customer_id = c.id
                WHERE o.id = ?
            ", [$order_id]);
            
            if (!$order) {
                throw new Exception("Order #{$order_id} not found");
            }
            
            // Get breakdown records
            $breakdowns = $this->db->fetchAll("
                SELECT * FROM order_payment_breakdown 
                WHERE order_id = ? AND status = 'onhold'
                ORDER BY type
            ", [$order_id]);
            
            if (empty($breakdowns)) {
                throw new Exception("No onhold breakdown found for order #{$order_id}");
            }
            
            // ========================================
            // STEP 1: UPDATE BREAKDOWN STATUS
            // ========================================
            $this->db->execute("
                UPDATE order_payment_breakdown 
                SET status = 'released', updated_at = NOW()
                WHERE order_id = ? AND status = 'onhold'
            ", [$order_id]);
            
            // ========================================
            // STEP 2: PROCESS EACH BREAKDOWN RECORD
            // ========================================
            foreach ($breakdowns as $breakdown) {
                $user_id = $breakdown['user_id'];
                $type = $breakdown['type'];
                $amount = floatval($breakdown['amount']);
                
                $wallet = $this->getOrCreateWallet($user_id, null);
                
                if ($type === 'security_deposit') {
                    // ========================================
                    // CUSTOMER: Security Refund
                    // ========================================
                    $sec_before = floatval($wallet['security_onhold']);
                    $bal_before = floatval($wallet['balance']);
                    
                    // Update wallet
                    $this->db->execute("
                        UPDATE wallets 
                        SET security_onhold = security_onhold - ?,
                            balance = balance + ?,
                            updated_at = NOW()
                        WHERE id = ?
                    ", [$amount, $amount, $wallet['id']]);
                    
                    // Create transaction record
                    $reference = 'SEC-REFUND-' . $order['order_number'] . '-' . time();
                    
                    $this->db->execute("
                        INSERT INTO wallet_transactions 
                        (user_id, wallet_id, order_id, breakdown_id, transaction_type, category, 
                         amount, balance_before, balance_after, description, reference, status)
                        VALUES (?, ?, ?, ?, 'security_deposit_refund', 'credit', ?, ?, ?, ?, ?, 'completed')
                    ", [
                        $user_id, 
                        $wallet['id'], 
                        $order_id, 
                        $breakdown['id'],
                        $amount,
                        $bal_before,
                        $bal_before + $amount,
                        "Security deposit refund - Order #{$order['order_number']} completed",
                        $reference
                    ]);
                    
                } elseif ($type === 'rental') {
                    // ========================================
                    // VENDOR: Rental Earning
                    // ========================================
                    $bal_before = floatval($wallet['balance']);
                    
                    // Update wallet
                    $this->db->execute("
                        UPDATE wallets 
                        SET balance = balance + ?,
                            total_earned = total_earned + ?,
                            updated_at = NOW()
                        WHERE id = ?
                    ", [$amount, $amount, $wallet['id']]);
                    
                    // Create transaction record
                    $reference = 'VEND-EARN-' . $order['order_number'] . '-' . time();
                    
                    $this->db->execute("
                        INSERT INTO wallet_transactions 
                        (user_id, wallet_id, order_id, breakdown_id, transaction_type, category, 
                         amount, balance_before, balance_after, description, reference, status)
                        VALUES (?, ?, ?, ?, 'rental_earning', 'credit', ?, ?, ?, ?, ?, 'completed')
                    ", [
                        $user_id, 
                        $wallet['id'], 
                        $order_id, 
                        $breakdown['id'],
                        $amount,
                        $bal_before,
                        $bal_before + $amount,
                        "Rental earning - Order #{$order['order_number']} completed",
                        $reference
                    ]);
                    
                } elseif ($type === 'platform_commission') {
                    // ========================================
                    // ADMIN: Platform Commission
                    // ========================================
                    $bal_before = floatval($wallet['balance']);
                    
                    // Update wallet
                    $this->db->execute("
                        UPDATE wallets 
                        SET balance = balance + ?,
                            total_earned = total_earned + ?,
                            updated_at = NOW()
                        WHERE id = ?
                    ", [$amount, $amount, $wallet['id']]);
                    
                    // Create transaction record
                    $reference = 'COMM-EARN-' . $order['order_number'] . '-' . time();
                    
                    $this->db->execute("
                        INSERT INTO wallet_transactions 
                        (user_id, wallet_id, order_id, breakdown_id, transaction_type, category, 
                         amount, balance_before, balance_after, description, reference, status)
                        VALUES (?, ?, ?, ?, 'platform_commission', 'credit', ?, ?, ?, ?, ?, 'completed')
                    ", [
                        $user_id, 
                        $wallet['id'], 
                        $order_id, 
                        $breakdown['id'],
                        $amount,
                        $bal_before,
                        $bal_before + $amount,
                        "Platform commission - Order #{$order['order_number']}",
                        $reference
                    ]);
                }
            }
            
            $this->db->commit();
            
            error_log("✅ WalletProcessor::processCompletedOrder SUCCESS - Order #{$order_id}");
            return true;
            
        } catch (Exception $e) {
            if ($this->db->inTransaction()) {
                $this->db->rollback();
            }
            error_log("❌ WalletProcessor::processCompletedOrder ERROR: " . $e->getMessage());
            throw $e;
        }
    }
    
    /**
     * ================================================================
     * PROCESS CANCELLATION - Called from cancel-order.php
     * ================================================================
     * Changes:
     * - order_payment_breakdown status → 'cancelled'
     * - Creates 2 wallet_transactions (rental refund + security refund)
     * - Updates customer wallet (REVERSES spending!)
     * ================================================================
     */
    public function processCancellation($order_id) {
        try {
            $this->db->beginTransaction();
            
            // Get order details
            $order = $this->db->fetch("
                SELECT o.order_number, o.subtotal, o.security_deposit, o.total_amount,
                       c.user_id as customer_user_id
                FROM orders o
                JOIN customers c ON o.customer_id = c.id
                WHERE o.id = ?
            ", [$order_id]);
            
            if (!$order) {
                throw new Exception("Order #{$order_id} not found");
            }
            
            // Get breakdown records
            $breakdowns = $this->db->fetchAll("
                SELECT * FROM order_payment_breakdown 
                WHERE order_id = ? AND status = 'onhold'
            ", [$order_id]);
            
            if (empty($breakdowns)) {
                throw new Exception("No onhold breakdown found for order #{$order_id}");
            }
            
            $rental_amount = floatval($order['subtotal']);
            $security_amount = floatval($order['security_deposit']);
            $total_amount = floatval($order['total_amount']);
            
            // ========================================
            // STEP 1: UPDATE BREAKDOWN STATUS
            // ========================================
            $this->db->execute("
                UPDATE order_payment_breakdown 
                SET status = 'cancelled', updated_at = NOW()
                WHERE order_id = ?
            ", [$order_id]);
            
            // ========================================
            // STEP 2: GET CUSTOMER WALLET
            // ========================================
            $wallet = $this->getOrCreateWallet($order['customer_user_id'], 'customer');
            $bal_before = floatval($wallet['balance']);
            
            // ========================================
            // STEP 3: CREATE 2 REFUND TRANSACTIONS
            // ========================================
            
            // Find breakdown IDs
            $rental_breakdown = null;
            $security_breakdown = null;
            foreach ($breakdowns as $bd) {
                if ($bd['type'] === 'rental') $rental_breakdown = $bd;
                if ($bd['type'] === 'security_deposit') $security_breakdown = $bd;
            }
            
            // Transaction 1: Rental Refund - CHANGED TO 'cancellation_refund'
            $reference_rental = 'RENT-REFUND-' . $order['order_number'] . '-' . time();
            
            $this->db->execute("
                INSERT INTO wallet_transactions 
                (user_id, wallet_id, order_id, breakdown_id, transaction_type, category, 
                 amount, balance_before, balance_after, description, reference, status)
                VALUES (?, ?, ?, ?, 'rental_cancellation_refund', 'credit', ?, ?, ?, ?, ?, 'completed')
            ", [
                $order['customer_user_id'], 
                $wallet['id'], 
                $order_id, 
                $rental_breakdown['id'] ?? null,
                $rental_amount,
                $bal_before,
                $bal_before + $rental_amount,
                "Rental refund - Order #{$order['order_number']} cancelled",
                $reference_rental
            ]);
            
            // Transaction 2: Security Deposit Refund - STAYS THE SAME
            $reference_security = 'SEC-CANCEL-' . $order['order_number'] . '-' . time();
            
            $this->db->execute("
                INSERT INTO wallet_transactions 
                (user_id, wallet_id, order_id, breakdown_id, transaction_type, category, 
                 amount, balance_before, balance_after, description, reference, status)
                VALUES (?, ?, ?, ?, 'security_deposit_cancellation_refund', 'credit', ?, ?, ?, ?, ?, 'completed')
            ", [
                $order['customer_user_id'], 
                $wallet['id'], 
                $order_id, 
                $security_breakdown['id'] ?? null,
                $security_amount,
                $bal_before + $rental_amount,
                $bal_before + $total_amount,
                "Security deposit refund - Order #{$order['order_number']} cancelled",
                $reference_security
            ]);
            
            // ========================================
            // STEP 4: UPDATE CUSTOMER WALLET
            // ========================================
            $this->db->execute("
                UPDATE wallets 
                SET security_onhold = security_onhold - ?,
                    total_spent = total_spent - ?,
                    balance = balance + ?,
                    updated_at = NOW()
                WHERE id = ?
            ", [$security_amount, $rental_amount, $total_amount, $wallet['id']]);
            
            $this->db->commit();
            
            error_log("✅ WalletProcessor::processCancellation SUCCESS - Order #{$order_id}");
            return true;
            
        } catch (Exception $e) {
            if ($this->db->inTransaction()) {
                $this->db->rollback();
            }
            error_log("❌ WalletProcessor::processCancellation ERROR: " . $e->getMessage());
            throw $e;
        }
    }
    


    /**
     * ================================================================
     * PROCESS CANCELLATION WITH PENALTY - Customer Cancellations
     * ================================================================
     * Creates:
     * - 2 refund transactions for customer (rental - penalty + security)
     * - 1 penalty transaction for vendor
     * - 1 penalty commission transaction for admin
     * - Updates breakdown status to 'cancelled'
     * - Updates customer wallet (balance + spending reversal - penalty)
     * - Updates vendor wallet (penalty share)
     * - Updates admin wallet (penalty commission)
     * ================================================================
     */
    public function processCancellationWithPenalty($order_id, $penalty_data) {
        try {
            $this->db->beginTransaction();
            
            // Get order details
            $order = $this->db->fetch("
                SELECT o.order_number, o.subtotal, o.security_deposit, o.total_amount,
                       c.user_id as customer_user_id,
                       v.user_id as vendor_user_id
                FROM orders o
                JOIN customers c ON o.customer_id = c.id
                JOIN vendors v ON o.vendor_id = v.id
                WHERE o.id = ?
            ", [$order_id]);
            
            if (!$order) {
                throw new Exception("Order #{$order_id} not found");
            }
            
            // Get breakdown records
            $breakdowns = $this->db->fetchAll("
                SELECT * FROM order_payment_breakdown 
                WHERE order_id = ? AND status = 'onhold'
            ", [$order_id]);
            
            if (empty($breakdowns)) {
                throw new Exception("No onhold breakdown found for order #{$order_id}");
            }
            
            // Extract penalty data
            $penalty_amount = floatval($penalty_data['penalty_amount']);
            $vendor_penalty_share = floatval($penalty_data['vendor_share']);
            $admin_penalty_share = floatval($penalty_data['admin_share']);
            $refund_amount = floatval($penalty_data['refund_amount']);
            
            $rental_amount = floatval($order['subtotal']);
            $security_amount = floatval($order['security_deposit']);
            $rental_refund = $rental_amount - $penalty_amount;
            
            // Get admin user ID
            $admin = $this->db->fetch("SELECT id FROM users WHERE user_type = 'admin' ORDER BY id ASC LIMIT 1");
            $admin_user_id = $admin['id'] ?? 1;
            
            // ========================================
            // STEP 1: UPDATE BREAKDOWN STATUS
            // ========================================
            $this->db->execute("
                UPDATE order_payment_breakdown 
                SET status = 'cancelled', updated_at = NOW()
                WHERE order_id = ?
            ", [$order_id]);
            
            // ========================================
            // STEP 2: CUSTOMER REFUND (2 TRANSACTIONS)
            // ========================================
            
            // Get customer wallet
            $customer_wallet = $this->getOrCreateWallet($order['customer_user_id'], 'customer');
            $customer_bal_before = floatval($customer_wallet['balance']);
            
            // Find breakdown IDs
            $rental_breakdown = null;
            $security_breakdown = null;
            foreach ($breakdowns as $bd) {
                if ($bd['type'] === 'rental') $rental_breakdown = $bd;
                if ($bd['type'] === 'security_deposit') $security_breakdown = $bd;
            }
            
            // Transaction 1: Rental Refund (MINUS PENALTY)
            $reference_rental = 'RENT-REFUND-PENALTY-' . $order['order_number'] . '-' . time();
            
            $this->db->execute("
                INSERT INTO wallet_transactions 
                (user_id, wallet_id, order_id, breakdown_id, transaction_type, category, 
                 amount, balance_before, balance_after, description, reference, status)
                VALUES (?, ?, ?, ?, 'rental_cancellation_refund', 'credit', ?, ?, ?, ?, ?, 'completed')
            ", [
                $order['customer_user_id'], 
                $customer_wallet['id'], 
                $order_id, 
                $rental_breakdown['id'] ?? null,
                $rental_refund,
                $customer_bal_before,
                $customer_bal_before + $rental_refund,
                "Rental refund (after ₦" . number_format($penalty_amount, 2) . " penalty) - Order #{$order['order_number']}",
                $reference_rental
            ]);
            
            // Store the rental breakdown_id for use in penalty transactions
            $rental_breakdown_id = $rental_breakdown['id'] ?? null;
            
            // Transaction 2: Security Deposit Refund (FULL)
            $reference_security = 'SEC-CANCEL-' . $order['order_number'] . '-' . time();
            
            $this->db->execute("
                INSERT INTO wallet_transactions 
                (user_id, wallet_id, order_id, breakdown_id, transaction_type, category, 
                 amount, balance_before, balance_after, description, reference, status)
                VALUES (?, ?, ?, ?, 'security_deposit_cancellation_refund', 'credit', ?, ?, ?, ?, ?, 'completed')
            ", [
                $order['customer_user_id'], 
                $customer_wallet['id'], 
                $order_id, 
                $security_breakdown['id'] ?? null,
                $security_amount,
                $customer_bal_before + $rental_refund,
                $customer_bal_before + $refund_amount,
                "Security deposit refund - Order #{$order['order_number']} cancelled",
                $reference_security
            ]);
            
            // Update customer wallet
            $this->db->execute("
                UPDATE wallets 
                SET security_onhold = security_onhold - ?,
                    total_spent = total_spent - ?,
                    balance = balance + ?,
                    updated_at = NOW()
                WHERE id = ?
            ", [$security_amount, $rental_amount, $refund_amount, $customer_wallet['id']]);
            
            // ========================================
            // STEP 3: VENDOR PENALTY SHARE
            // ========================================
            
            if ($vendor_penalty_share > 0) {
                $vendor_wallet = $this->getOrCreateWallet($order['vendor_user_id'], 'vendor');
                $vendor_bal_before = floatval($vendor_wallet['balance']);
                
                $reference_vendor = 'VENDOR-PENALTY-' . $order['order_number'] . '-' . time();
                
                $this->db->execute("
                    INSERT INTO wallet_transactions 
                    (user_id, wallet_id, order_id, breakdown_id, transaction_type, category, 
                     amount, balance_before, balance_after, description, reference, status)
                    VALUES (?, ?, ?, ?, 'vendor_cancellation_penalty_received', 'credit', ?, ?, ?, ?, ?, 'completed')
                ", [
                    $order['vendor_user_id'], 
                    $vendor_wallet['id'], 
                    $order_id,
                    $rental_breakdown_id, // Same breakdown_id as rental refund
                    $vendor_penalty_share,
                    $vendor_bal_before,
                    $vendor_bal_before + $vendor_penalty_share,
                    "Cancellation penalty (vendor share) - Order #{$order['order_number']}",
                    $reference_vendor
                ]);
                
                // Update vendor wallet
                $this->db->execute("
                    UPDATE wallets 
                    SET balance = balance + ?,
                        total_earned = total_earned + ?,
                        updated_at = NOW()
                    WHERE id = ?
                ", [$vendor_penalty_share, $vendor_penalty_share, $vendor_wallet['id']]);
            }
            
            // ========================================
            // STEP 4: ADMIN PENALTY COMMISSION
            // ========================================
            
            if ($admin_penalty_share > 0) {
                $admin_wallet = $this->getOrCreateWallet($admin_user_id, 'admin');
                $admin_bal_before = floatval($admin_wallet['balance']);
                
                $reference_admin = 'ADMIN-PENALTY-' . $order['order_number'] . '-' . time();
                
                $this->db->execute("
                    INSERT INTO wallet_transactions 
                    (user_id, wallet_id, order_id, breakdown_id, transaction_type, category, 
                     amount, balance_before, balance_after, description, reference, status)
                    VALUES (?, ?, ?, ?, 'admin_cancellation_penalty_received', 'credit', ?, ?, ?, ?, ?, 'completed')
                ", [
                    $admin_user_id, 
                    $admin_wallet['id'], 
                    $order_id,
                    $rental_breakdown_id, // Same breakdown_id as rental refund
                    $admin_penalty_share,
                    $admin_bal_before,
                    $admin_bal_before + $admin_penalty_share,
                    "Cancellation penalty commission - Order #{$order['order_number']}",
                    $reference_admin
                ]);
                
                // Update admin wallet
                $this->db->execute("
                    UPDATE wallets 
                    SET balance = balance + ?,
                        total_earned = total_earned + ?,
                        updated_at = NOW()
                    WHERE id = ?
                ", [$admin_penalty_share, $admin_penalty_share, $admin_wallet['id']]);
            }
            
            $this->db->commit();
            
            error_log("✅ WalletProcessor::processCancellationWithPenalty SUCCESS - Order #{$order_id} | Penalty: ₦{$penalty_amount}");
            return true;
            
        } catch (Exception $e) {
            if ($this->db->inTransaction()) {
                $this->db->rollback();
            }
            error_log("❌ WalletProcessor::processCancellationWithPenalty ERROR: " . $e->getMessage());
            throw $e;
        }
    }



    /**
     * ================================================================
     * PROCESS WITHDRAWAL - For vendors/admins withdrawing to bank
     * ================================================================
     */
    public function processWithdrawal($user_id, $amount, $bank_details = []) {
        try {
            $this->db->beginTransaction();
            
            $wallet = $this->getOrCreateWallet($user_id, null);
            
            // Check sufficient balance
            if (floatval($wallet['balance']) < $amount) {
                throw new Exception("Insufficient balance");
            }
            
            $bal_before = floatval($wallet['balance']);
            $bal_after = $bal_before - $amount;
            
            // Update wallet
            $this->db->execute("
                UPDATE wallets 
                SET balance = balance - ?,
                    total_withdrawn = total_withdrawn + ?,
                    updated_at = NOW()
                WHERE id = ?
            ", [$amount, $amount, $wallet['id']]);
            
            // Create transaction record
            $reference = 'WITHDRAW-' . $user_id . '-' . time();
            
            $metadata = json_encode([
                'bank_details' => $bank_details,
                'processed_at' => date('Y-m-d H:i:s')
            ]);
            
            $this->db->execute("
                INSERT INTO wallet_transactions 
                (user_id, wallet_id, transaction_type, category, 
                 amount, balance_before, balance_after, description, reference, metadata, status)
                VALUES (?, ?, 'withdrawal', 'debit', ?, ?, ?, ?, ?, ?, 'completed')
            ", [
                $user_id, 
                $wallet['id'],
                $amount,
                $bal_before,
                $bal_after,
                "Withdrawal to bank account",
                $reference,
                $metadata
            ]);
            
            $this->db->commit();
            
            error_log("✅ WalletProcessor::processWithdrawal SUCCESS - User #{$user_id}");
            return [
                'success' => true,
                'reference' => $reference,
                'new_balance' => $bal_after
            ];
            
        } catch (Exception $e) {
            if ($this->db->inTransaction()) {
                $this->db->rollback();
            }
            error_log("❌ WalletProcessor::processWithdrawal ERROR: " . $e->getMessage());
            return [
                'success' => false,
                'error' => $e->getMessage()
            ];
        }
    }
    
    /**
     * ================================================================
     * GET OR CREATE WALLET
     * ================================================================
     */
    private function getOrCreateWallet($user_id, $user_type = null) {
        $wallet = $this->db->fetch("SELECT * FROM wallets WHERE user_id = ?", [$user_id]);
        
        if (!$wallet) {
            // Get user type if not provided
            if (!$user_type) {
                $user = $this->db->fetch("SELECT user_type FROM users WHERE id = ?", [$user_id]);
                $user_type = $user['user_type'] ?? 'customer';
            }
            
            // Create wallet
            $this->db->execute("
                INSERT INTO wallets (user_id, user_type) VALUES (?, ?)
            ", [$user_id, $user_type]);
            
            $wallet = $this->db->fetch("SELECT * FROM wallets WHERE user_id = ?", [$user_id]);
        }
        
        return $wallet;
    }
}