<?php
/**
 * Google Play Purchase Verification API
 * Verifies in-app purchase tokens and credits user wallet
 */
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

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

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

// Only POST allowed
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonError('Method not allowed', 405);
}

// Check login
if (!isset($_SESSION['user_id'])) {
    jsonError('Not authenticated', 401);
}

$userId = $_SESSION['user_id'];

// Get request data
$data = json_decode(file_get_contents('php://input'), true);
$purchaseToken = $data['purchaseToken'] ?? '';
$productId = $data['productId'] ?? '';
$orderId = $data['orderId'] ?? '';

// Product ID to amount mapping
$productAmounts = [
    'deposit_100'    => 100,
    'deposit_500'    => 500,
    'deposit_1000'   => 1000,
    'deposit_2000'   => 2000,
    'deposit_5000'   => 5000,
    'deposit_10000'  => 10000,
    'deposit_25000'  => 25000,
    'deposit_50000'  => 50000,
    'deposit_100000' => 100000,
];

// Validate inputs
if (empty($purchaseToken) || empty($productId)) {
    jsonError('Missing purchase token or product ID');
}

$amount = $productAmounts[$productId] ?? 0;
if ($amount <= 0) {
    jsonError('Invalid product ID');
}

try {
    // Check for duplicate purchase
    $existing = dbFetch(
        "SELECT id FROM deposits WHERE google_order_id = ? AND status = 'completed'",
        [$orderId]
    );

    if ($existing) {
        jsonError('This purchase has already been processed');
    }

    // Server-side verification using Google Play Developer API
    // Note: For full verification, install google/apiclient via Composer
    // and use a Service Account JSON key. Below is the simplified flow:
    $verified = verifyWithGoogleApi($purchaseToken, $productId);

    if (!$verified['valid']) {
        // If Google API not configured, allow manual verification mode
        // In production, ALWAYS verify with Google API
        $manualMode = getSetting('google_play_manual_mode', '1');
        if ($manualMode !== '1') {
            jsonError('Purchase verification failed: ' . ($verified['error'] ?? 'Unknown error'));
        }
    }

    // Begin transaction
    dbBeginTransaction();

    // Credit user wallet
    $walletUpdate = dbQuery(
        "UPDATE user_wallets SET balance = balance + ? WHERE user_id = ?",
        [$amount, $userId]
    );

    if (!$walletUpdate) {
        // Try users table fallback
        dbQuery(
            "UPDATE users SET balance = balance + ? WHERE id = ?",
            [$amount, $userId]
        );
    }

    // Record deposit
    $depositId = dbInsert('deposits', [
        'user_id'               => $userId,
        'amount'                => $amount,
        'method'                => 'google_play',
        'status'                => 'completed',
        'google_order_id'       => $orderId,
        'google_purchase_token' => $purchaseToken,
        'payment_platform'      => 'android',
        'transaction_id'        => generateTransactionId('GPD'),
        'created_at'            => date('Y-m-d H:i:s')
    ]);

    // Log activity
    logActivity('user', $userId, 'google_play_deposit', "Google Play deposit of ₹{$amount} (Order: {$orderId})");

    dbCommit();

    // Create notification
    dbInsert('push_notifications', [
        'user_id' => $userId,
        'title'   => 'Deposit Successful',
        'body'    => "₹" . number_format($amount) . " has been added to your wallet via Google Play.",
        'type'    => 'deposit',
        'data'    => json_encode(['deposit_id' => $depositId, 'amount' => $amount])
    ]);

    jsonSuccess('Deposit successful', [
        'deposit_id' => $depositId,
        'amount'     => $amount,
        'order_id'   => $orderId
    ]);

} catch (Exception $e) {
    dbRollback();
    error_log("Google Play Verify Error: " . $e->getMessage());
    jsonError('An error occurred while processing your deposit');
}

/**
 * Verify purchase with Google Play Developer API
 * Requires google/apiclient package and service account JSON
 */
function verifyWithGoogleApi($purchaseToken, $productId) {
    $packageName = 'com.binarypro.trading';
    $serviceAccountPath = ROOT_PATH . '/config/google-service-account.json';

    // Check if Google API client is available
    if (!file_exists($serviceAccountPath)) {
        return ['valid' => false, 'error' => 'Service account not configured'];
    }

    // Check if Google API library is installed
    $autoloadPath = ROOT_PATH . '/vendor/autoload.php';
    if (!file_exists($autoloadPath)) {
        return ['valid' => false, 'error' => 'Google API client library not installed'];
    }

    require_once $autoloadPath;

    try {
        $client = new Google_Client();
        $client->setAuthConfig($serviceAccountPath);
        $client->setScopes(['https://www.googleapis.com/auth/androidpublisher']);

        $service = new Google_Service_AndroidPublisher($client);
        $purchase = $service->purchases_products->get(
            $packageName,
            $productId,
            $purchaseToken
        );

        return [
            'valid'        => ($purchase->getPurchaseState() == 0),
            'orderId'      => $purchase->getOrderId(),
            'purchaseTime' => $purchase->getPurchaseTimeMillis()
        ];
    } catch (Exception $e) {
        error_log("Google API Error: " . $e->getMessage());
        return ['valid' => false, 'error' => $e->getMessage()];
    }
}
