<?php
// Webhook for payment processing (e.g., from payment gateways like Stripe, PayPal, etc.)
header('Content-Type: application/json');

// Log webhook data for debugging
$webhook_data = file_get_contents('php://input');
$headers = getallheaders();

error_log("Payment Webhook Received: " . $webhook_data);
error_log("Headers: " . json_encode($headers));

// Basic webhook verification (implement proper verification based on your payment gateway)
$signature = isset($headers['X-Signature']) ? $headers['X-Signature'] : '';
$timestamp = isset($headers['X-Timestamp']) ? $headers['X-Timestamp'] : '';

// Verify webhook signature (implement your own verification logic)
if (!$signature || !$timestamp) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Invalid webhook signature']);
    exit();
}

// Parse webhook data
$data = json_decode($webhook_data, true);
if (!$data) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid JSON data']);
    exit();
}

// Process based on webhook type
$event_type = isset($data['type']) ? $data['type'] : '';
$transaction_id = isset($data['transaction_id']) ? $data['transaction_id'] : '';
$status = isset($data['status']) ? $data['status'] : '';
$amount = isset($data['amount']) ? (float)$data['amount'] : 0;

if (empty($event_type) || empty($transaction_id)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing required webhook data']);
    exit();
}

require_once '../includes/functions.php';
$functions = new Functions();

try {
    // Find transaction by reference or external ID
    $stmt = $functions->db->prepare("SELECT * FROM transactions WHERE reference = ? OR id = ?");
    $stmt->execute([$transaction_id, $transaction_id]);
    $transaction = $stmt->fetch();

    if (!$transaction) {
        error_log("Transaction not found: " . $transaction_id);
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'Transaction not found']);
        exit();
    }

    // Process based on event type
    switch ($event_type) {
        case 'payment.succeeded':
        case 'payment.completed':
            if ($transaction['status'] === 'pending') {
                // Update transaction status
                $update_stmt = $functions->db->prepare("
                    UPDATE transactions SET
                        status = 'completed',
                        payment_proof = ?,
                        transaction_hash = ?,
                        updated_at = NOW()
                    WHERE id = ?
                ");
                $update_stmt->execute([
                    isset($data['payment_proof']) ? $data['payment_proof'] : '',
                    isset($data['transaction_hash']) ? $data['transaction_hash'] : '',
                    $transaction['id']
                ]);

                // If it's a deposit, add to user balance
                if ($transaction['type'] === 'deposit') {
                    $functions->updateUserBalance($transaction['user_id'], $transaction['amount']);
                }

                // Log activity
                $functions->logActivity(
                    $transaction['user_id'],
                    'payment_completed',
                    'Payment completed for transaction #' . $transaction['id']
                );

                error_log("Payment completed for transaction: " . $transaction_id);
            }
            break;

        case 'payment.failed':
        case 'payment.cancelled':
            if ($transaction['status'] === 'pending') {
                // Update transaction status
                $update_stmt = $functions->db->prepare("
                    UPDATE transactions SET
                        status = 'cancelled',
                        admin_note = ?,
                        updated_at = NOW()
                    WHERE id = ?
                ");
                $update_stmt->execute([
                    isset($data['failure_reason']) ? $data['failure_reason'] : 'Payment failed',
                    $transaction['id']
                ]);

                // Log activity
                $functions->logActivity(
                    $transaction['user_id'],
                    'payment_failed',
                    'Payment failed for transaction #' . $transaction['id']
                );

                error_log("Payment failed for transaction: " . $transaction_id);
            }
            break;

        default:
            error_log("Unknown webhook event type: " . $event_type);
            break;
    }

    // Respond to webhook
    echo json_encode(['success' => true, 'message' => 'Webhook processed successfully']);

} catch (Exception $e) {
    error_log("Webhook processing error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Internal server error']);
}
?>
