<?php
/**
 * App Configuration API - Returns app settings for mobile clients
 */
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

require_once '../../config/config.php';
require_once '../../config/database.php';
require_once '../../includes/functions.php';

if (session_status() === PHP_SESSION_NONE) session_start();

try {
    $config = [
        'success'       => true,
        'app_name'      => defined('APP_NAME') ? APP_NAME : 'BinaryPro',
        'site_url'      => defined('SITE_URL') ? SITE_URL : '',
        'currency'      => [
            'symbol' => defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : '₹',
            'code'   => defined('CURRENCY_CODE') ? CURRENCY_CODE : 'INR',
        ],
        'trading'       => [
            'min_amount'    => defined('MIN_TRADE_AMOUNT') ? MIN_TRADE_AMOUNT : 10,
            'max_amount'    => defined('MAX_TRADE_AMOUNT') ? MAX_TRADE_AMOUNT : 50000,
            'demo_balance'  => defined('DEMO_BALANCE') ? DEMO_BALANCE : 10000,
        ],
        'deposit'       => [
            'min_amount' => defined('MIN_PAYMENT_AMOUNT') ? MIN_PAYMENT_AMOUNT : 100,
            'max_amount' => defined('MAX_PAYMENT_AMOUNT') ? MAX_PAYMENT_AMOUNT : 100000,
            'methods'    => ['google_play', 'upi'],
        ],
        'referral'      => [
            'commission_percent' => defined('REFERRAL_COMMISSION_PERCENT') ? REFERRAL_COMMISSION_PERCENT : 5,
        ],
        'features'      => [
            'google_play_billing' => true,
            'upi_payment'         => true,
            'biometric_login'     => true,
            'push_notifications'  => true,
            'demo_trading'        => true,
            'kyc_required'        => true,
        ],
        'app_version'   => [
            'latest'       => '1.0.0',
            'min_required' => '1.0.0',
            'update_url'   => 'https://play.google.com/store/apps/details?id=com.binarypro.trading',
        ],
        'maintenance'   => [
            'enabled' => false,
            'message' => '',
        ],
    ];

    // Add user info if logged in
    if (isset($_SESSION['user_id'])) {
        $user = dbFetch("SELECT id, name, email, phone FROM users WHERE id = ?", [$_SESSION['user_id']]);
        if ($user) {
            $config['user'] = [
                'id'    => $user['id'],
                'name'  => $user['name'],
                'email' => $user['email'],
            ];
        }
    }

    echo json_encode($config);

} catch (Exception $e) {
    error_log("App Config Error: " . $e->getMessage());
    jsonError('Failed to load app configuration');
}
