<?php
/**
 * UserWallet Model
 * File: app/Models/UserWallet.php
 * 
 * Handles multi-wallet operations for new wallet system
 */

class UserWallet {
    private $db;
    
    public function __construct() {
        $this->db = Database::getInstance();
    }
    
    /**
     * Create user wallets (called during registration)
     */
    public function createUserWallets($user_id, $user_type) {
        $wallets = [];
        
        if ($user_type === 'customer') {
            $wallets = ['main_balance', 'security_held', 'security_refundable'];
        } elseif ($user_type === 'vendor') {
            $wallets = ['main_balance', 'pending_earnings'];
        }
        
        $sql = "INSERT INTO user_wallets (user_id, wallet_type, balance) VALUES (?, ?, 0.00)";
        $stmt = $this->db->prepare($sql);
        
        foreach ($wallets as $wallet_type) {
            $stmt->bind_param("is", $user_id, $wallet_type);
            $stmt->execute();
        }
        
        return true;
    }
    
    /**
     * Get wallet by user ID and type
     */
    public function getWallet($user_id, $wallet_type) {
        $sql = "SELECT * FROM user_wallets WHERE user_id = ? AND wallet_type = ? LIMIT 1";
        return $this->db->fetch($sql, [$user_id, $wallet_type]);
    }
    
    /**
     * Get all wallets for a user
     */
    public function getAllWallets($user_id) {
        $sql = "SELECT * FROM user_wallets WHERE user_id = ? ORDER BY wallet_type";
        $result = $this->db->fetchAll($sql, [$user_id]);
        
        $wallets = [];
        foreach ($result as $row) {
            $wallets[$row['wallet_type']] = $row;
        }
        
        return $wallets;
    }
    
    /**
     * Get wallet balance
     */
    public function getBalance($user_id, $wallet_type) {
        $wallet = $this->getWallet($user_id, $wallet_type);
        return $wallet ? (float)$wallet['balance'] : 0.00;
    }
    
    /**
     * Update wallet balance
     */
    public function updateBalance($wallet_id, $new_balance) {
        $sql = "UPDATE user_wallets SET balance = ?, updated_at = NOW() WHERE id = ?";
        return $this->db->execute($sql, [$new_balance, $wallet_id]);
    }
    
    /**
     * Credit wallet (add funds)
     */
    public function credit($user_id, $wallet_type, $amount) {
        $wallet = $this->getWallet($user_id, $wallet_type);
        
        if (!$wallet) {
            throw new Exception("Wallet not found");
        }
        
        $new_balance = $wallet['balance'] + $amount;
        return $this->updateBalance($wallet['id'], $new_balance);
    }
    
    /**
     * Debit wallet (remove funds)
     */
    public function debit($user_id, $wallet_type, $amount) {
        $wallet = $this->getWallet($user_id, $wallet_type);
        
        if (!$wallet) {
            throw new Exception("Wallet not found");
        }
        
        if ($wallet['balance'] < $amount) {
            throw new Exception("Insufficient balance");
        }
        
        $new_balance = $wallet['balance'] - $amount;
        return $this->updateBalance($wallet['id'], $new_balance);
    }
    
    /**
     * Get customer wallet summary
     */
    public function getCustomerSummary($user_id) {
        $wallets = $this->getAllWallets($user_id);
        
        // Calculate total spent from transactions
        $sql = "SELECT COALESCE(SUM(amount), 0) as total_spent 
                FROM transactions 
                WHERE user_id = ? 
                AND transaction_type = 'rental_payment' 
                AND status = 'completed'";
        $result = $this->db->fetch($sql, [$user_id]);
        
        return [
            'main_balance' => $wallets['main_balance']['balance'] ?? 0,
            'security_held' => $wallets['security_held']['balance'] ?? 0,
            'security_refundable' => $wallets['security_refundable']['balance'] ?? 0,
            'total_spent' => $result['total_spent'] ?? 0
        ];
    }
    
    /**
     * Get vendor wallet summary
     */
    public function getVendorSummary($user_id) {
        $wallets = $this->getAllWallets($user_id);
        
        // Calculate total earnings from transactions
        $sql = "SELECT COALESCE(SUM(amount), 0) as total_earnings 
                FROM transactions 
                WHERE user_id = ? 
                AND transaction_type = 'vendor_earning' 
                AND status = 'completed'";
        $result = $this->db->fetch($sql, [$user_id]);
        
        return [
            'main_balance' => $wallets['main_balance']['balance'] ?? 0,
            'pending_earnings' => $wallets['pending_earnings']['balance'] ?? 0,
            'total_earnings' => $result['total_earnings'] ?? 0
        ];
    }
    
    /**
     * Check if user has sufficient balance
     */
    public function hasSufficientBalance($user_id, $wallet_type, $amount) {
        $balance = $this->getBalance($user_id, $wallet_type);
        return $balance >= $amount;
    }
    
    /**
     * Get wallet by ID
     */
    public function find($wallet_id) {
        $sql = "SELECT * FROM user_wallets WHERE id = ? LIMIT 1";
        return $this->db->fetch($sql, [$wallet_id]);
    }
}
