<?php
require 'config.php'; // Adjust path if outside root

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



$invoiceId = (int)($data['invoice_id'] ?? 0);
$uuid = $data['uuid'] ?? '';
$hash = $data['hash'] ?? '';
$paypalId = $data['paypal_id'] ?? '';
$amount = (float)($data['amount'] ?? 0.00);

// DB Connection
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($conn->connect_error) die("DB error");

// Validate hash
$stmt = $conn->prepare("SELECT salt FROM invoices WHERE id = ? AND uuid = ?");
$stmt->bind_param("is", $invoiceId, $uuid);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$stmt->close();

if (!$row || !hash_equals(generateInvoiceHash($invoiceId, $row['salt']), $hash)) {
    http_response_code(403);
    exit("Invalid request");
}

// Update invoice
$stmt = $conn->prepare("UPDATE invoices SET status = 'paid', paid_at = NOW(), paypal_transaction_id = ? WHERE id = ?");
$stmt->bind_param("si", $paypalId, $invoiceId);
$stmt->execute();
$stmt->close();

$conn->close();
echo json_encode(['success' => true]);
