<?php
include_once 'shikanisha.kts.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['pay_id'])) {
    $payId = $conn->real_escape_string($_POST['pay_id']);

    // Begin transaction
    $conn->begin_transaction();

    // Select the trans_id and amount for the payment
    $selectStmt = $conn->prepare("SELECT trans_id, amount FROM payments WHERE pay_id = ?");
    $selectStmt->bind_param("i", $payId);
    $selectStmt->execute();
    $result = $selectStmt->get_result();
    $paymentData = $result->fetch_assoc();
    $selectStmt->close();

    // Update the transaction_receipts table
    $updateStmt = $conn->prepare("UPDATE transaction_receipts SET amount_received = amount_received - ? WHERE trans_id = ?");
    $updateStmt->bind_param("di", $paymentData['amount'], $paymentData['trans_id']);
    $updateSuccess = $updateStmt->execute();
    $updateStmt->close();

    // Delete the payment
    $deleteStmt = $conn->prepare("DELETE FROM payments WHERE pay_id = ?");
    $deleteStmt->bind_param("i", $payId);
    $deleteSuccess = $deleteStmt->execute();
    $deleteStmt->close();

    // Check if all operations were successful
    if ($updateSuccess && $deleteSuccess) {
        $conn->commit();
        echo json_encode(['success' => true]);
    } else {
        $conn->rollback();
        echo json_encode(['error' => 'Failed to delete payment.']);
    }
} else {
    echo json_encode(['error' => 'Invalid request']);
}
?>
