<?php
header('Content-Type: application/json');
require_once '../config.php';

$input = json_decode(file_get_contents('php://input'), true);

if (!isset($input['package_id']) || !isset($input['machine_id'])) {
    echo json_encode(['success' => false, 'error' => 'Missing parameters']);
    exit;
}

try {
    $pdo = getDB();
    
    // Get user by machine_id
    $stmt = $pdo->prepare("SELECT id, email FROM users WHERE machine_id = ?");
    $stmt->execute([$input['machine_id']]);
    $user = $stmt->fetch();
    
    if (!$user) {
        echo json_encode(['success' => false, 'error' => 'User not found']);
        exit;
    }
    
    // Get package details
    $stmt = $pdo->prepare("SELECT * FROM packages WHERE id = ? AND is_active = 1");
    $stmt->execute([$input['package_id']]);
    $package = $stmt->fetch();
    
    if (!$package) {
        echo json_encode(['success' => false, 'error' => 'Package not found']);
        exit;
    }
    
    // Create Razorpay order
    $amount = $package['price'] * 100; // Convert to paise
    
    // BYPASS: Generate mock order for testing
    $order = [
        'id' => 'order_' . uniqid(),
        'amount' => $amount,
        'currency' => 'INR'
    ];
    
    // Save payment record
    $stmt = $pdo->prepare("INSERT INTO payments (user_id, package_id, razorpay_order_id, amount, currency, status) VALUES (?, ?, ?, ?, 'INR', 'success')");
    $stmt->execute([$user['id'], $package['id'], $order['id'], $package['price']]);
    
    // Generate license key
    $license_key = sprintf('%04X-%04X-%04X-%04X', mt_rand(0, 0xFFFF), mt_rand(0, 0xFFFF), mt_rand(0, 0xFFFF), mt_rand(0, 0xFFFF));
    
    // Calculate expiry
    $expires_at = $package['duration_days'] ? date('Y-m-d H:i:s', strtotime("+{$package['duration_days']} days")) : null;
    
    // Create license
    $stmt = $pdo->prepare("INSERT INTO licenses (license_key, plan_type, max_devices, expires_at, status) VALUES (?, ?, ?, ?, 'active')");
    $stmt->execute([$license_key, $package['plan_type'], $package['max_devices'], $expires_at]);
    
    // Activate license for user
    $stmt = $pdo->prepare("INSERT INTO license_activations (license_key, machine_id, activated_at) VALUES (?, ?, NOW())");
    $stmt->execute([$license_key, $input['machine_id']]);
    
    // Update user license
    $stmt = $pdo->prepare("UPDATE users SET license_key = ?, license_expires_at = ? WHERE id = ?");
    $stmt->execute([$license_key, $expires_at, $user['id']]);
    
    echo json_encode([
        'success' => true,
        'order_id' => $order['id'],
        'amount' => $amount,
        'currency' => 'INR',
        'key_id' => RAZORPAY_KEY_ID,
        'package_name' => $package['name'],
        'user_email' => $user['email'],
        'license_key' => $license_key,
        'message' => 'Payment bypassed - License activated directly'
    ]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
