<?php
// contribution_actions.php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include 'db_connect.php';

if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['action']) && $_GET['action'] == 'delete') {
    // --- DELETE LOGIC ---
    $id = intval($_GET['id']);
    $partner_id = intval($_GET['partner_id']);

    if ($id > 0) {
        $stmt = $conn->prepare("DELETE FROM Financial_Contributions WHERE contribution_id = ?");
        $stmt->bind_param("i", $id);
        
        if ($stmt->execute()) {
            header("Location: individual_partner_details.php?partner_id=$partner_id&msg=deleted");
        } else {
            header("Location: individual_partner_details.php?partner_id=$partner_id&msg=error");
        }
        $stmt->close();
    }
} 
elseif ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] == 'update') {
    // --- UPDATE LOGIC ---
    $id = intval($_POST['contribution_id']);
    $partner_id = intval($_POST['partner_id']);
    $amount = floatval($_POST['amount']);
    $date = $_POST['contribution_date'];
    // Fix: Ensure receipt_number is captured from the POST data
    $ref = isset($_POST['receipt_number']) ? $_POST['receipt_number'] : '';

    if ($id > 0 && !empty($ref)) {
        $sql = "UPDATE Financial_Contributions SET amount = ?, contribution_date = ?, receipt_number = ? WHERE contribution_id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("dssi", $amount, $date, $ref, $id);
        
        if ($stmt->execute()) {
            header("Location: individual_partner_details.php?partner_id=$partner_id&msg=updated");
        } else {
            // Check if error is due to duplicate receipt number
            if ($conn->errno == 1062) {
                header("Location: individual_partner_details.php?partner_id=$partner_id&msg=error&reason=duplicate");
            } else {
                header("Location: individual_partner_details.php?partner_id=$partner_id&msg=error");
            }
        }
        $stmt->close();
    } else {
        header("Location: individual_partner_details.php?partner_id=$partner_id&msg=error&reason=missing_fields");
    }
}
$conn->close();
?>