<?php
// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include 'db_connect.php';

if (isset($_GET['id']) && is_numeric($_GET['id'])) {
    $partner_id = $_GET['id'];

    // Start a transaction to ensure both deletions succeed or fail together
    $conn->begin_transaction();

    try {
        // Step 1: Delete related records from the child table (Partnership_Agreements)
        $sql_agreements = "DELETE FROM Partnership_Agreements WHERE partner_id = ?";
        $stmt_agreements = $conn->prepare($sql_agreements);
        $stmt_agreements->bind_param("i", $partner_id);
        $stmt_agreements->execute();
        $stmt_agreements->close();

        // Step 2: Delete the partner from the parent table (Partners)
        $sql_partner = "DELETE FROM Partners WHERE partner_id = ?";
        $stmt_partner = $conn->prepare($sql_partner);
        $stmt_partner->bind_param("i", $partner_id);
        $stmt_partner->execute();
        $rows_affected = $stmt_partner->affected_rows;
        $stmt_partner->close();

        if ($rows_affected > 0) {
            // Commit the transaction if both deletions were successful
            $conn->commit();
            header("Location: index2.php?status=success&message=" . urlencode("Partner and associated agreements deleted successfully."));
        } else {
            // Rollback if the partner was not found
            $conn->rollback();
            header("Location: index2.php?status=error&message=" . urlencode("Error: Partner not found."));
        }

    } catch (mysqli_sql_exception $e) {
        // Rollback on any database error
        $conn->rollback();
        header("Location: index2.php?status=error&message=" . urlencode("Error deleting partner: " . $e->getMessage()));
    }

    $conn->close();
} else {
    header("Location: index2.php?status=error&message=" . urlencode("Invalid partner ID provided."));
}

exit();
?>