<?php
require_once __DIR__ . '/../models/Coins.php';
require_once __DIR__ . '/../models/User.php';
require_once __DIR__ . '/../models/SiteSettings.php';

class CoinsController {
    private $coins;
    private $user;
    private $siteSettings;

    public function __construct() {
        $this->coins = new Coins();
        $this->user = new User();
        $this->siteSettings = new SiteSettings();
    }

    /**
     * Award coins for game play
     */
    public function awardCoins() {
        // Disable error display to prevent HTML in JSON response
        ini_set('display_errors', 0);
        error_reporting(0);
        
        // Clean any previous output
        if (ob_get_level()) {
            ob_clean();
        }
        
        header('Content-Type: application/json');

        try {
            if (!isset($_SESSION['user_id'])) {
                echo json_encode(['success' => false, 'message' => 'User not logged in']);
                return;
            }

            // Check if points system is enabled
            $settings = $this->siteSettings->getAllSettings();
            if (($settings['enable_points_system'] ?? '0') !== '1') {
                echo json_encode(['success' => false, 'message' => 'Points system is disabled']);
                return;
            }

            $input = json_decode(file_get_contents('php://input'), true);
            $gameId = $input['game_id'] ?? null;
            $playTimeSeconds = $input['play_time'] ?? 0;

            if (!$gameId || $playTimeSeconds < 60) { // Minimum 1 minute to earn coins
                echo json_encode(['success' => false, 'message' => 'Invalid parameters or insufficient play time']);
                return;
            }

            $playTimeMinutes = floor($playTimeSeconds / 60);
            $pointsPerMinute = intval($settings['points_per_minute'] ?? 10);
            
            $coinsEarned = $this->coins->awardCoins($_SESSION['user_id'], $gameId, $playTimeMinutes, $pointsPerMinute);

            if ($coinsEarned !== false) {
                $balance = $this->coins->getUserBalance($_SESSION['user_id']);
                echo json_encode([
                    'success' => true, 
                    'coins_earned' => $coinsEarned,
                    'new_balance' => $balance['balance'],
                    'message' => "You earned $coinsEarned coins!"
                ]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to award coins']);
            }
        } catch (Exception $e) {
            error_log("Award coins error: " . $e->getMessage());
            echo json_encode(['success' => false, 'message' => 'An error occurred while awarding coins']);
        }
    }

    /**
     * Get user's coin balance
     */
    public function getBalance() {
        // Disable error display to prevent HTML in JSON response
        ini_set('display_errors', 0);
        error_reporting(0);
        
        // Clean any previous output
        if (ob_get_level()) {
            ob_clean();
        }
        
        header('Content-Type: application/json');

        try {
            if (!isset($_SESSION['user_id'])) {
                echo json_encode(['success' => false, 'message' => 'User not logged in']);
                return;
            }

            $balance = $this->coins->getUserBalance($_SESSION['user_id']);
            echo json_encode(['success' => true, 'balance' => $balance]);
        } catch (Exception $e) {
            error_log("Get balance error: " . $e->getMessage());
            echo json_encode(['success' => false, 'message' => 'An error occurred while retrieving balance']);
        }
    }

    /**
     * Create withdrawal request
     */
    public function createWithdrawal() {
        // Disable error display to prevent HTML in JSON response
        ini_set('display_errors', 0);
        error_reporting(0);
        
        // Clean any previous output
        if (ob_get_level()) {
            ob_clean();
        }
        
        header('Content-Type: application/json');

        try {
            if (!isset($_SESSION['user_id'])) {
                echo json_encode(['success' => false, 'message' => 'User not logged in']);
                return;
            }

            // Check if points system is enabled
            $settings = $this->siteSettings->getAllSettings();
            if (($settings['enable_points_system'] ?? '0') !== '1') {
                echo json_encode(['success' => false, 'message' => 'Points system is disabled']);
                return;
            }

            $input = json_decode(file_get_contents('php://input'), true);
            
            if (!$input) {
                echo json_encode(['success' => false, 'message' => 'Invalid request data']);
                return;
            }
            
            $amount = intval($input['amount'] ?? 0);
            $paymentMethod = trim($input['payment_method'] ?? '');
            $paymentDetails = trim($input['payment_details'] ?? '');

            $minimumWithdrawal = intval($settings['minimum_withdrawal'] ?? 1000);

            if ($amount < $minimumWithdrawal) {
                echo json_encode(['success' => false, 'message' => "Minimum withdrawal is $minimumWithdrawal points"]);
                return;
            }

            if (empty($paymentMethod) || empty($paymentDetails)) {
                echo json_encode(['success' => false, 'message' => 'Payment method and details are required']);
                return;
            }

            $result = $this->coins->createWithdrawalRequest($_SESSION['user_id'], $amount, $paymentMethod, $paymentDetails);
            echo json_encode($result);
            
        } catch (Exception $e) {
            error_log("Withdrawal request error: " . $e->getMessage());
            echo json_encode(['success' => false, 'message' => 'An error occurred while processing your request']);
        }
    }

    /**
     * Get user's withdrawal requests
     */
    public function getUserWithdrawals() {
        // Disable error display to prevent HTML in JSON response
        ini_set('display_errors', 0);
        error_reporting(0);
        
        // Clean any previous output
        if (ob_get_level()) {
            ob_clean();
        }
        
        header('Content-Type: application/json');

        try {
            if (!isset($_SESSION['user_id'])) {
                echo json_encode(['success' => false, 'message' => 'User not logged in']);
                return;
            }

            $withdrawals = $this->coins->getUserWithdrawalRequests($_SESSION['user_id']);
            echo json_encode(['success' => true, 'withdrawals' => $withdrawals]);
        } catch (Exception $e) {
            error_log("Get user withdrawals error: " . $e->getMessage());
            echo json_encode(['success' => false, 'message' => 'An error occurred while retrieving withdrawals']);
        }
    }

    /**
     * Get user's transaction history
     */
    public function getTransactionHistory() {
        // Disable error display to prevent HTML in JSON response
        ini_set('display_errors', 0);
        error_reporting(0);
        
        // Clean any previous output
        if (ob_get_level()) {
            ob_clean();
        }
        
        header('Content-Type: application/json');

        try {
            if (!isset($_SESSION['user_id'])) {
                echo json_encode(['success' => false, 'message' => 'User not logged in']);
                return;
            }

            $transactions = $this->coins->getUserTransactions($_SESSION['user_id']);
            echo json_encode(['success' => true, 'transactions' => $transactions]);
        } catch (Exception $e) {
            error_log("Get transaction history error: " . $e->getMessage());
            echo json_encode(['success' => false, 'message' => 'An error occurred while retrieving transaction history']);
        }
    }

    /**
     * Get withdrawal settings
     */
    public function getWithdrawalSettings() {
        // Disable error display to prevent HTML in JSON response
        ini_set('display_errors', 0);
        error_reporting(0);
        
        // Clean any previous output
        if (ob_get_level()) {
            ob_clean();
        }
        
        header('Content-Type: application/json');

        try {
            if (!isset($_SESSION['user_id'])) {
                echo json_encode(['success' => false, 'message' => 'User not logged in']);
                return;
            }

            // Check if points system is enabled
            $settings = $this->siteSettings->getAllSettings();
            if (($settings['enable_points_system'] ?? '0') !== '1') {
                echo json_encode(['success' => false, 'message' => 'Points system is disabled']);
                return;
            }

            $withdrawalMethods = explode(',', $settings['withdrawal_methods'] ?? 'PayPal,Bank Transfer,Cryptocurrency');
            $withdrawalMethods = array_map('trim', $withdrawalMethods); // Remove any extra spaces

            echo json_encode([
                'success' => true,
                'settings' => [
                    'minimum_withdrawal' => intval($settings['minimum_withdrawal'] ?? 1000),
                    'withdrawal_rate' => intval($settings['withdrawal_rate'] ?? 100),
                    'withdrawal_methods' => $withdrawalMethods
                ]
            ]);
        } catch (Exception $e) {
            error_log("Get withdrawal settings error: " . $e->getMessage());
            echo json_encode(['success' => false, 'message' => 'An error occurred while retrieving withdrawal settings']);
        }
    }
}