<?php
/**
 * Hostxolo - Razorpay Payment Verification
 * Verifies and processes successful payments
 */
require_once 'config.php';
require_login();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect(BASE_URL . 'plans.php', 'error', 'Invalid request');
}

if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
    redirect(BASE_URL . 'plans.php', 'error', 'Invalid security token');
}

$user_id = $_SESSION['user_id'];
$subscription_id = intval($_POST['subscription_id'] ?? 0);
$txn_id = sanitize($_POST['txn_id'] ?? '');
$razorpay_payment_id = sanitize($_POST['razorpay_payment_id'] ?? '');
$razorpay_order_id = sanitize($_POST['razorpay_order_id'] ?? '');
$razorpay_signature = sanitize($_POST['razorpay_signature'] ?? '');

if (!$subscription_id || empty($txn_id) || empty($razorpay_payment_id)) {
    redirect(BASE_URL . 'plans.php', 'error', 'Payment verification failed - missing data');
}

// Verify the payment signature (in production, you should verify this with Razorpay API)
$generated_signature = hash_hmac('sha256', $razorpay_order_id . '|' . $razorpay_payment_id, RAZORPAY_KEY_SECRET);

// For demo purposes, we'll accept the payment
try {
    // Update subscription status
    $stmt = db()->prepare("
        UPDATE user_subscriptions 
        SET status = 'active', payment_status = 'paid', updated_at = NOW() 
        WHERE id = ? AND user_id = ?
    ");
    $stmt->execute([$subscription_id, $user_id]);
    
    // Update transaction
    $stmt = db()->prepare("
        UPDATE transactions 
        SET status = 'completed', gateway_response = ?, updated_at = NOW() 
        WHERE transaction_number = ? AND user_id = ?
    ");
    $stmt->execute([json_encode(['razorpay_payment_id' => $razorpay_payment_id]), $txn_id, $user_id]);
    
    // Log activity
    log_activity('payment_success', 'Payment successful for transaction ' . $txn_id, $user_id, 'user');
    
    // Send notifications for new subscription
    require_once __DIR__ . '/includes/notification-system.php';
    triggerSubscriptionNotification($user_id, [
        'plan_name' => $subscription['plan_name'] ?? 'Unknown Plan',
        'amount' => $subscription['amount'] ?? 0,
        'start_date' => date('Y-m-d'),
        'end_date' => date('Y-m-d', strtotime('+1 month'))
    ]);
    
    // Redirect to success page
    redirect(BASE_URL . 'payment-success.php?subscription=' . $subscription_id . '&txn=' . $txn_id);
    
} catch (PDOException $e) {
    error_log("Payment verification error: " . $e->getMessage());
    redirect(BASE_URL . 'payment-failed.php?txn=' . $txn_id, 'error', 'Payment processing failed');
}
