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

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

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

try {
    $pdo = getDB();
    
    // Verify signature
    $generated_signature = hash_hmac('sha256', $input['razorpay_order_id'] . '|' . $input['razorpay_payment_id'], RAZORPAY_KEY_SECRET);
    
    if ($generated_signature !== $input['razorpay_signature']) {
        echo json_encode(['success' => false, 'error' => 'Invalid signature']);
        exit;
    }
    
    // Get payment record
    $stmt = $pdo->prepare("SELECT * FROM payments WHERE razorpay_order_id = ?");
    $stmt->execute([$input['razorpay_order_id']]);
    $payment = $stmt->fetch();
    
    if (!$payment) {
        echo json_encode(['success' => false, 'error' => 'Payment not found']);
        exit;
    }
    
    // Update payment status
    $stmt = $pdo->prepare("UPDATE payments SET razorpay_payment_id = ?, razorpay_signature = ?, status = 'success' WHERE id = ?");
    $stmt->execute([$input['razorpay_payment_id'], $input['razorpay_signature'], $payment['id']]);
    
    // Get package details
    $stmt = $pdo->prepare("SELECT * FROM packages WHERE id = ?");
    $stmt->execute([$payment['package_id']]);
    $package = $stmt->fetch();
    
    // 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]);
    
    // Get user machine_id
    $stmt = $pdo->prepare("SELECT machine_id FROM users WHERE id = ?");
    $stmt->execute([$payment['user_id']]);
    $user = $stmt->fetch();
    
    // Activate license for user
    $stmt = $pdo->prepare("INSERT INTO license_activations (license_key, machine_id, activated_at) VALUES (?, ?, NOW())");
    $stmt->execute([$license_key, $user['machine_id']]);
    
    // Update user license
    $stmt = $pdo->prepare("UPDATE users SET license_key = ?, license_expires_at = ? WHERE id = ?");
    $stmt->execute([$license_key, $expires_at, $payment['user_id']]);
    
    echo json_encode([
        'success' => true,
        'license_key' => $license_key,
        'expires_at' => $expires_at,
        'plan_type' => $package['plan_type']
    ]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
