<?php
ini_set('display_errors',1);
error_reporting(E_ALL);

require_once __DIR__ . '/../../../includes/auth.php';
requireLogin();

require_once __DIR__ . '/../../../config/database.php';

/* ===============================
   VALIDATE INPUT
================================ */
if(!isset($_GET['payment_id'])){
    die("Missing payment_id");
}

$paymentId = (int)$_GET['payment_id'];

/* ===============================
   LOAD PAYMENT
================================ */
$stmt = $pdo->prepare("
SELECT * FROM invoice_payments
WHERE id = ?
LIMIT 1
");
$stmt->execute([$paymentId]);
$payment = $stmt->fetch(PDO::FETCH_ASSOC);

if(!$payment){
    die("Payment not found");
}

$invoiceId = $payment['invoice_id'];

/* ===============================
   DELETE PAYMENT (SAFE)
================================ */
$pdo->prepare("
DELETE FROM invoice_payments
WHERE id = ?
")->execute([$paymentId]);

/* ===============================
   REDIRECT BACK
================================ */
header("Location: invoice_view.php?id=".$invoiceId."&success=payment_reversed");
exit;