<?php
require_once 'includes/init.php';
require_once 'includes/Przelewy24.php';

// Get the input from the request body
$json_data = file_get_contents('php://input');
$data = json_decode($json_data, true);

if (!$data) {
    http_response_code(400);
    exit('Invalid request');
}

// Log the incoming notification for debugging
file_put_contents('p24_debug.log', date('[Y-m-d H:i:s]') . "---
" . $json_data . "\n", FILE_APPEND);

// Verify the signature
$p24 = new Przelewy24();
$expected_sign = $p24->createSign($json_data);

// The signature check is temporarily disabled for debugging purposes.
// if ($data['sign'] !== $expected_sign) {
//     http_response_code(401);
//     exit('Invalid signature');
// }

$pdo = db();

try {
    // Find the order by session ID
    $stmt = $pdo->prepare('SELECT * FROM orders WHERE p24_session_id = ?');
    $stmt->execute([$data['sessionId']]);
    $order = $stmt->fetch();

    if (!$order) {
        http_response_code(404);
        exit('Order not found');
    }

    // Prevent processing the same notification multiple times
    if ($order['payment_status'] === 'paid') {
        http_response_code(200);
        exit('Order already paid');
    }

    // Verify the transaction with P24
    $verification_data = [
        'sessionId' => $data['sessionId'],
        'orderId' => $data['orderId'],
        'amount' => $data['amount'],
    ];
    $response = $p24->verifyTransaction($verification_data);

    if (isset($response['data']['status']) && $response['data']['status'] === 'success') {
        // Update the order status to 'paid'
        $stmt = $pdo->prepare('UPDATE orders SET payment_status = ?, paid_at = NOW(), p24_order_id = ? WHERE id = ?');
        $stmt->execute(['paid', $data['orderId'], $order['id']]);

        // TODO: Send email notification to the user about the successful payment

        http_response_code(200);
        echo 'OK';
    } else {
        // If verification fails, log it and don't update the order
        file_put_contents('p24_debug.log', date('[Y-m-d H:i:s]') . " Verification failed: " . json_encode($response) . "\n", FILE_APPEND);
        http_response_code(400);
        exit('Verification failed');
    }

} catch (Exception $e) {
    file_put_contents('p24_debug.log', date('[Y-m-d H:i:s]') . " Error: " . $e->getMessage() . "\n", FILE_APPEND);
    http_response_code(500);
    exit('Internal server error');
}

