<?php
session_start();
if(!isset($_SESSION['username'])) {
    header("Location: ../login.php");
    exit();
}

include('../includes/db.php');

$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$gp_id = isset($_GET['gp_id']) ? intval($_GET['gp_id']) : 0;

if($id > 0 && $gp_id > 0) {
    // Get the amount to subtract
    $get_sql = "SELECT amount FROM gp_payable WHERE id = $id";
    $get_result = mysqli_query($conn, $get_sql);
    $row = mysqli_fetch_assoc($get_result);
    $amount = $row['amount'];
    
    if($amount > 0) {
        mysqli_begin_transaction($conn);
        try {
            // Delete the record
            $delete_sql = "DELETE FROM gp_payable WHERE id = $id";
            mysqli_query($conn, $delete_sql);
            
            // Update balance (subtract the amount)
            $update_sql = "UPDATE general_parties SET current_balance = current_balance - $amount WHERE id = $gp_id";
            mysqli_query($conn, $update_sql);
            
            mysqli_commit($conn);
            header("Location: gp_payable.php?gp_id=$gp_id");
            exit();
        } catch (Exception $e) {
            mysqli_rollback($conn);
            header("Location: gp_payable.php?gp_id=$gp_id&error=1");
            exit();
        }
    }
}

header("Location: gp_payable.php?gp_id=$gp_id");
exit();
?>