<?php
include 'config.php';
if($_SESSION['user_role'] != 'SuperAdmin') exit();

// --- HANDLE DELETE ---
if(isset($_GET['delete'])) {
    $pay_id = (int)$_GET['delete'];
    $amount = (float)$_GET['amt'];
    $agency_id = (int)$_GET['aid'];

    if($conn->query("DELETE FROM saas_payments WHERE id = $pay_id")) {
        // Increase the debt again
        $conn->query("UPDATE agencies SET balance_due = balance_due + $amount WHERE id = $agency_id");
        header("Location: agency_ledger.php?id=$agency_id&msg=deleted");
    }
    exit();
}

// --- HANDLE ADD & UPDATE ---
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $agency_id = (int)$_POST['agency_id'];
    $amount    = (float)$_POST['amount'];
    $method    = $_POST['method'];
    $notes     = $_POST['notes'];
    $date      = date('Y-m-d');

    if (isset($_POST['action']) && $_POST['action'] == 'update') {
        // UPDATE LOGIC
        $payment_id = (int)$_POST['payment_id'];
        $old_amount = (float)$_POST['old_amount'];

        $stmt = $conn->prepare("UPDATE saas_payments SET amount_paid=?, payment_method=?, notes=? WHERE id=?");
        $stmt->bind_param("dssi", $amount, $method, $notes, $payment_id);
        
        if($stmt->execute()) {
            // Re-calculate the agency balance: remove old credit and add new credit
            $adjustment = $old_amount - $amount;
            $conn->query("UPDATE agencies SET balance_due = balance_due + $adjustment WHERE id = $agency_id");
            header("Location: agency_ledger.php?id=$agency_id&msg=updated");
        }
    } else {
        // ADD LOGIC
        $stmt = $conn->prepare("INSERT INTO saas_payments (agency_id, amount_paid, payment_date, payment_method, notes) VALUES (?, ?, ?, ?, ?)");
        $stmt->bind_param("idsss", $agency_id, $amount, $date, $method, $notes);
        
        if ($stmt->execute()) {
            $conn->query("UPDATE agencies SET balance_due = balance_due - $amount WHERE id = $agency_id");
            header("Location: saas_revenue.php?msg=success");
        }
    }
}
?>