<?php
/**
 * Wallet Management
 * مدیریت کیف پول
 */

namespace GemAcc;

use PDO;

class Wallet
{
    private PDO $pdo;
    
    public function __construct(PDO $pdo)
    {
        $this->pdo = $pdo;
    }
    
    /**
     * گرفتن موجودی کاربر
     */
    public function getBalance(int $userId): int
    {
        $stmt = $this->pdo->prepare("SELECT balance FROM users WHERE id = ?");
        $stmt->execute([$userId]);
        $balance = $stmt->fetchColumn();
        return $balance !== false ? (int)$balance : 0;
    }
    
    /**
     * افزایش موجودی
     */
    public function addBalance(int $userId, int $amount): bool
    {
        $stmt = $this->pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
        return $stmt->execute([$amount, $userId]);
    }
    
    /**
     * کاهش موجودی
     */
    public function subtractBalance(int $userId, int $amount): bool
    {
        $stmt = $this->pdo->prepare("UPDATE users SET balance = balance - ? WHERE id = ? AND balance >= ?");
        return $stmt->execute([$amount, $userId, $amount]) && $stmt->rowCount() > 0;
    }
    
    /**
     * ایجاد درخواست واریز
     */
    public function createDepositRequest(int $userId, int $amount, ?string $receiptFileId = null, ?string $receiptText = null): int
    {
        $stmt = $this->pdo->prepare("
            INSERT INTO wallet_transactions (user_id, amount, type, status, description, receipt_file_id, receipt_text)
            VALUES (?, ?, 'DEPOSIT', 'PENDING', 'درخواست افزایش موجودی', ?, ?)
        ");
        $stmt->execute([$userId, $amount, $receiptFileId, $receiptText]);
        
        return (int)$this->pdo->lastInsertId();
    }
    
    /**
     * تایید واریز (با بونوس)
     * @return array ['success' => bool, 'bonus' => int]
     */
    public function approveDeposit(int $txId, int $processedBy): array
    {
        $tx = $this->getTransactionById($txId);
        if (!$tx || $tx['status'] !== 'PENDING' || $tx['type'] !== 'DEPOSIT') {
            return ['success' => false, 'bonus' => 0];
        }
        
        $this->pdo->beginTransaction();
        
        try {
            // محاسبه بونوس
            $bonus = $this->calculateDepositBonus($tx['amount']);
            $totalAmount = $tx['amount'] + $bonus;
            
            // بروزرسانی تراکنش
            $stmt = $this->pdo->prepare("
                UPDATE wallet_transactions 
                SET status = 'COMPLETED', processed_by = ?, processed_at = NOW() 
                WHERE id = ?
            ");
            $stmt->execute([$processedBy, $txId]);
            
            // افزایش موجودی (مبلغ اصلی + بونوس)
            $this->addBalance($tx['user_id'], $totalAmount);
            
            // اگر بونوس داشت، ثبت تراکنش جداگانه
            if ($bonus > 0) {
                $stmt = $this->pdo->prepare("
                    INSERT INTO wallet_transactions (user_id, amount, type, status, description)
                    VALUES (?, ?, 'CASHBACK', 'COMPLETED', 'بونوس شارژ کیف پول')
                ");
                $stmt->execute([$tx['user_id'], $bonus]);
            }
            
            $this->pdo->commit();
            return ['success' => true, 'bonus' => $bonus, 'user_id' => $tx['user_id'], 'amount' => $tx['amount']];
            
        } catch (\Exception $e) {
            $this->pdo->rollBack();
            error_log("approveDeposit error: " . $e->getMessage());
            return ['success' => false, 'bonus' => 0];
        }
    }
    
    /**
     * محاسبه بونوس واریز
     */
    public function calculateDepositBonus(int $amount): int
    {
        // گرفتن تنظیمات بونوس
        $stmt = $this->pdo->query("SELECT key_name, value FROM settings WHERE key_name IN ('wallet_bonus_enabled', 'wallet_bonus_min_amount', 'wallet_bonus_percent')");
        $settings = [];
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $settings[$row['key_name']] = $row['value'];
        }
        
        $enabled = ($settings['wallet_bonus_enabled'] ?? '0') === '1';
        $minAmount = (int)($settings['wallet_bonus_min_amount'] ?? 100000);
        $percent = (int)($settings['wallet_bonus_percent'] ?? 10);
        
        if (!$enabled || $amount < $minAmount) {
            return 0;
        }
        
        return (int)floor($amount * $percent / 100);
    }
    
    /**
     * رد واریز
     */
    public function rejectDeposit(int $txId, int $processedBy): bool
    {
        $stmt = $this->pdo->prepare("
            UPDATE wallet_transactions 
            SET status = 'REJECTED', processed_by = ?, processed_at = NOW() 
            WHERE id = ? AND status = 'PENDING' AND type = 'DEPOSIT'
        ");
        return $stmt->execute([$processedBy, $txId]) && $stmt->rowCount() > 0;
    }
    
    /**
     * ثبت خرید
     */
    public function recordPurchase(int $userId, int $amount, string $description = 'خرید اشتراک'): int
    {
        $stmt = $this->pdo->prepare("
            INSERT INTO wallet_transactions (user_id, amount, type, status, description)
            VALUES (?, ?, 'PURCHASE', 'COMPLETED', ?)
        ");
        $stmt->execute([$userId, $amount, $description]);
        
        return (int)$this->pdo->lastInsertId();
    }
    
    /**
     * استرداد وجه
     */
    public function refund(int $userId, int $amount, string $description = 'استرداد وجه'): int
    {
        $this->pdo->beginTransaction();
        
        try {
            $stmt = $this->pdo->prepare("
                INSERT INTO wallet_transactions (user_id, amount, type, status, description)
                VALUES (?, ?, 'REFUND', 'COMPLETED', ?)
            ");
            $stmt->execute([$userId, $amount, $description]);
            $txId = (int)$this->pdo->lastInsertId();
            
            $this->addBalance($userId, $amount);
            
            $this->pdo->commit();
            return $txId;
            
        } catch (\Exception $e) {
            $this->pdo->rollBack();
            error_log("refund error: " . $e->getMessage());
            return 0;
        }
    }
    
    /**
     * پرداخت با کیف پول
     * @return array ['success' => bool, 'message' => string, 'tx_id' => int|null]
     */
    public function pay(int $userId, int $amount, string $description = 'خرید اشتراک'): array
    {
        $balance = $this->getBalance($userId);
        
        if ($balance < $amount) {
            return [
                'success' => false,
                'message' => 'موجودی کیف پول شما کافی نیست. موجودی: ' . number_format($balance) . ' تومان',
                'tx_id'   => null,
            ];
        }
        
        $this->pdo->beginTransaction();
        
        try {
            // کسر موجودی
            if (!$this->subtractBalance($userId, $amount)) {
                throw new \Exception('خطا در کسر موجودی');
            }
            
            // ثبت تراکنش
            $txId = $this->recordPurchase($userId, $amount, $description);
            
            $this->pdo->commit();
            
            return [
                'success' => true,
                'message' => 'پرداخت با موفقیت انجام شد',
                'tx_id'   => $txId,
            ];
            
        } catch (\Exception $e) {
            $this->pdo->rollBack();
            return [
                'success' => false,
                'message' => 'خطا در پرداخت: ' . $e->getMessage(),
                'tx_id'   => null,
            ];
        }
    }
    
    /**
     * گرفتن تراکنش با آیدی
     */
    public function getTransactionById(int $txId): ?array
    {
        $stmt = $this->pdo->prepare("
            SELECT wt.*, u.first_name, u.username
            FROM wallet_transactions wt
            LEFT JOIN users u ON wt.user_id = u.id
            WHERE wt.id = ?
        ");
        $stmt->execute([$txId]);
        return $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
    }
    
    /**
     * تاریخچه تراکنش‌های کاربر
     */
    public function getUserHistory(int $userId, int $limit = 20): array
    {
        $stmt = $this->pdo->prepare("
            SELECT * FROM wallet_transactions 
            WHERE user_id = ? 
            ORDER BY created_at DESC 
            LIMIT ?
        ");
        $stmt->bindValue(1, $userId, PDO::PARAM_INT);
        $stmt->bindValue(2, $limit, PDO::PARAM_INT);
        $stmt->execute();
        
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    
    /**
     * درخواست‌های واریز در انتظار (برای ادمین)
     */
    public function getPendingDeposits(int $limit = 50): array
    {
        $stmt = $this->pdo->prepare("
            SELECT wt.*, u.first_name, u.username
            FROM wallet_transactions wt
            LEFT JOIN users u ON wt.user_id = u.id
            WHERE wt.type = 'DEPOSIT' AND wt.status = 'PENDING'
            ORDER BY wt.created_at ASC
            LIMIT ?
        ");
        $stmt->bindValue(1, $limit, PDO::PARAM_INT);
        $stmt->execute();
        
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    
    /**
     * اعمال کش‌بک خرید
     * @return int مبلغ کش‌بک
     */
    public function applyCashback(int $userId, int $purchaseAmount): int
    {
        // گرفتن تنظیمات کش‌بک
        $stmt = $this->pdo->query("SELECT key_name, value FROM settings WHERE key_name IN ('cashback_enabled', 'cashback_percent')");
        $settings = [];
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $settings[$row['key_name']] = $row['value'];
        }
        
        $enabled = ($settings['cashback_enabled'] ?? '0') === '1';
        $percent = (int)($settings['cashback_percent'] ?? 5);
        
        if (!$enabled || $percent <= 0) {
            return 0;
        }
        
        $cashbackAmount = (int)floor($purchaseAmount * $percent / 100);
        
        if ($cashbackAmount > 0) {
            $this->pdo->beginTransaction();
            
            try {
                // ثبت تراکنش کش‌بک
                $stmt = $this->pdo->prepare("
                    INSERT INTO wallet_transactions (user_id, amount, type, status, description)
                    VALUES (?, ?, 'CASHBACK', 'COMPLETED', 'کش‌بک خرید')
                ");
                $stmt->execute([$userId, $cashbackAmount]);
                
                // افزایش موجودی
                $this->addBalance($userId, $cashbackAmount);
                
                // بروزرسانی آمار کش‌بک کاربر
                $stmt = $this->pdo->prepare("UPDATE users SET total_cashback = total_cashback + ? WHERE id = ?");
                $stmt->execute([$cashbackAmount, $userId]);
                
                $this->pdo->commit();
                return $cashbackAmount;
                
            } catch (\Exception $e) {
                $this->pdo->rollBack();
                error_log("applyCashback error: " . $e->getMessage());
                return 0;
            }
        }
        
        return 0;
    }
    
    /**
     * لیبل نوع تراکنش
     */
    public static function getTypeLabel(string $type): string
    {
        $labels = [
            'DEPOSIT'  => '💰 واریز',
            'PURCHASE' => '🛒 خرید',
            'REFUND'   => '↩️ استرداد',
            'ADMIN'    => '👑 ادمین',
            'CASHBACK' => '🎁 کش‌بک',
        ];
        
        return $labels[$type] ?? $type;
    }
    
    /**
     * لیبل وضعیت تراکنش
     */
    public static function getStatusLabel(string $status): string
    {
        $labels = [
            'PENDING'   => '⏳ در انتظار',
            'COMPLETED' => '✅ تکمیل شده',
            'REJECTED'  => '❌ رد شده',
            'CANCELLED' => '🚫 لغو شده',
        ];
        
        return $labels[$status] ?? $status;
    }
}

