<?php

class Payment {
    private $db;

    public function __construct() {
        $this->db = Database::getInstance();
    }

    /**
     * Get user wallet balance
     */
    public function getBalance($userId) {
        $result = $this->db->fetch(
            'SELECT balance FROM wallets WHERE user_id = ?',
            [$userId]
        );
        return $result ? (float)$result['balance'] : 0.00;
    }

    /**
     * Add credits to user wallet
     */
    public function addCredits($userId, $amount, $description = 'Manual Credit') {
        try {
            // Update wallet
            $this->db->query(
                'UPDATE wallets SET balance = balance + ? WHERE user_id = ?',
                [$amount, $userId]
            );

            // Log transaction
            $this->logTransaction($userId, 'credit', $amount, $description);
            return true;
        } catch (Exception $e) {
            error_log('Add Credits Error: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Deduct credits from user wallet
     */
    public function deductCredits($userId, $amount, $description = 'Search') {
        try {
            $currentBalance = $this->getBalance($userId);

            if ($currentBalance < $amount) {
                return ['status' => false, 'message' => 'Insufficient balance'];
            }

            // Deduct from wallet
            $this->db->query(
                'UPDATE wallets SET balance = balance - ? WHERE user_id = ?',
                [$amount, $userId]
            );

            // Log transaction
            $this->logTransaction($userId, 'debit', $amount, $description);
            return ['status' => true, 'message' => 'Credits deducted successfully'];
        } catch (Exception $e) {
            error_log('Deduct Credits Error: ' . $e->getMessage());
            return ['status' => false, 'message' => 'Error processing transaction'];
        }
    }

    /**
     * Create payment order
     */
    public function createPaymentOrder($userId, $amount, $packageName = 'Custom') {
        try {
            $orderId = 'ORD-' . time() . '-' . rand(1000, 9999);
            
            $data = [
                'user_id' => $userId,
                'amount' => $amount,
                'package_name' => $packageName,
                'order_id' => $orderId,
                'status' => 'pending',
                'created_at' => date('Y-m-d H:i:s')
            ];

            $this->db->insert('payment_orders', $data);
            return $orderId;
        } catch (Exception $e) {
            error_log('Create Payment Order Error: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Confirm payment and add credits
     */
    public function confirmPayment($orderId, $transactionId, $paymentMethod = 'upi') {
        try {
            // First check if already completed to prevent duplicates
            $existingOrder = $this->db->fetch(
                'SELECT * FROM payment_orders WHERE order_id = ? AND status = "completed"',
                [$orderId]
            );

            if ($existingOrder) {
                return ['status' => false, 'message' => 'Payment already approved'];
            }

            // Get order if still awaiting approval
            $order = $this->db->fetch(
                'SELECT * FROM payment_orders WHERE order_id = ? AND status = "awaiting_approval"',
                [$orderId]
            );

            if (!$order) {
                return ['status' => false, 'message' => 'Order not found or already processed'];
            }

            // Update order status to completed
            $this->db->update('payment_orders',
                ['status' => 'completed', 'payment_method' => $paymentMethod],
                'order_id = :order_id',
                ['order_id' => $orderId]
            );

            // Add credits to wallet
            $this->addCredits($order['user_id'], $order['amount'], 'Payment Approved - ' . $orderId);

            return ['status' => true, 'message' => 'Payment confirmed successfully'];
        } catch (Exception $e) {
            error_log('Confirm Payment Error: ' . $e->getMessage());
            return ['status' => false, 'message' => 'Error confirming payment'];
        }
    }

    /**
     * Get transaction history
     */
    public function getTransactionHistory($userId, $limit = 20) {
        return $this->db->fetchAll(
            'SELECT * FROM transactions WHERE user_id = ? ORDER BY created_at DESC LIMIT ?',
            [$userId, $limit]
        );
    }

    /**
     * Log transaction
     */
    private function logTransaction($userId, $type, $amount, $description) {
        $data = [
            'user_id' => $userId,
            'type' => $type,
            'amount' => $amount,
            'description' => $description,
            'balance_after' => $this->getBalance($userId),
            'created_at' => date('Y-m-d H:i:s')
        ];

        $this->db->insert('transactions', $data);
    }

    /**
     * Get payment details (QR, UPI, etc)
     */
    public function getPaymentDetails() {
        return $this->db->fetch('SELECT * FROM payment_details LIMIT 1') ?: [];
    }

    /**
     * Update payment details
     */
    public function updatePaymentDetails($qrCodePath, $upiId, $telegramToken = '', $telegramChatId = '') {
        $details = $this->getPaymentDetails();

        if (empty($details)) {
            $data = [
                'qr_code_path' => $qrCodePath,
                'upi_id' => $upiId,
                'telegram_bot_token' => $telegramToken,
                'telegram_admin_chat_id' => $telegramChatId
            ];
            $this->db->insert('payment_details', $data);
        } else {
            $this->db->query(
                'UPDATE payment_details SET qr_code_path = ?, upi_id = ?, telegram_bot_token = ?, telegram_admin_chat_id = ?',
                [$qrCodePath, $upiId, $telegramToken, $telegramChatId]
            );
        }
        return true;
    }

    /**
     * Submit manual payment with screenshot
     */
    public function submitManualPayment($userId, $orderId, $transactionId, $screenshotPath) {
        try {
            $this->db->query(
                'UPDATE payment_orders SET screenshot_path = ?, transaction_id = ?, status = "awaiting_approval" WHERE order_id = ? AND user_id = ?',
                [$screenshotPath, $transactionId, $orderId, $userId]
            );
            return ['status' => true, 'message' => 'Payment submitted for verification'];
        } catch (Exception $e) {
            error_log('Submit Manual Payment Error: ' . $e->getMessage());
            return ['status' => false, 'message' => 'Error submitting payment'];
        }
    }

    /**
     * Get pending approvals
     */
    public function getPendingApprovals($limit = 20) {
        $limit = intval($limit);
        return $this->db->fetchAll(
            'SELECT po.*, u.name, u.email FROM payment_orders po 
             JOIN users u ON po.user_id = u.id 
             WHERE po.status = "awaiting_approval" 
             ORDER BY po.created_at DESC LIMIT ' . $limit,
            []
        );
    }

    /**
     * Get payment packages
     */
    public function getPaymentPackages() {
        return [
            [
                'id' => 1,
                'name' => 'Basic',
                'credits' => 10,
                'price' => 50,
                'description' => '10 Mobile Searches'
            ],
            [
                'id' => 2,
                'name' => 'Standard',
                'credits' => 30,
                'price' => 130,
                'description' => '30 Mobile Searches or 6 Aadhaar Searches'
            ],
            [
                'id' => 3,
                'name' => 'Premium',
                'credits' => 60,
                'price' => 250,
                'description' => '60 Mobile Searches or 12 Aadhaar Searches'
            ],
            [
                'id' => 4,
                'name' => 'Pro',
                'credits' => 150,
                'price' => 600,
                'description' => '150 Mobile Searches or 30 Aadhaar Searches'
            ]
        ];
    }
}
?>
