<?php
// agreement_for_partner.php
require_once 'db_connect.php';
header('Content-Type: application/json');

$partner_id = isset($_GET['partner_id']) ? intval($_GET['partner_id']) : 0;
if (!$partner_id) {
    echo json_encode(['error' => 'Missing partner_id']);
    exit;
}

// Fetch latest active agreement (if multiple, pick latest created_at)
$stmt = $conn->prepare("SELECT * FROM Partnership_Agreements WHERE partner_id = ? AND status = 'Active' ORDER BY created_at DESC LIMIT 1");
$stmt->bind_param("i", $partner_id);
$stmt->execute();
$res = $stmt->get_result();
if ($res && $res->num_rows > 0) {
    $a = $res->fetch_assoc();
    echo json_encode(['agreement' => $a]);
} else {
    // If no Active agreement, try to return the latest agreement (any status)
    $stmt2 = $conn->prepare("SELECT * FROM Partnership_Agreements WHERE partner_id = ? ORDER BY created_at DESC LIMIT 1");
    $stmt2->bind_param("i", $partner_id);
    $stmt2->execute();
    $res2 = $stmt2->get_result();
    if ($res2 && $res2->num_rows > 0) {
        $a = $res2->fetch_assoc();
        echo json_encode(['agreement' => $a]);
    } else {
        echo json_encode(['agreement' => null]);
    }
}
