<?php

header("Content-Type: application/json");

// DB connection

$host = 'localhost';
$db = 'demoptma_publications';
$user = 'demoptma_publications';
$pass = 'dj$JN)hJerjG';

try {
    $pdo = new PDO(
        "mysql:host=$host;dbname=$db;charset=utf8mb4",
        $user,
        $pass,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        ]
    );
} catch (PDOException $e) {
    echo json_encode(["status" => "db_error"]);
    exit;
}

// Get JSON input
$data = json_decode(file_get_contents("php://input"), true);

$invoiceId = $data['invoice_id'] ?? null;
$paymentIntent = $data['payment_intent'] ?? null;

if (!$invoiceId || !$paymentIntent) {
    echo json_encode(["status" => "invalid_request"]);
    exit;
}

try {

    $stmt = $pdo->prepare("
        UPDATE invoices
        SET payment_status = 'Paid',
            stripe_payment_intent_id = ?
        WHERE id = ?
    ");

    $stmt->execute([$paymentIntent, $invoiceId]);

    echo json_encode([
        "status" => "success"
    ]);

} catch (Exception $e) {

    echo json_encode([
        "status" => "error"
    ]);

}