<?php
include 'config.php';
if(!isset($_SESSION['user_id'])) exit();

$agency_id = $_SESSION['agency_id'];

// --- HANDLE DELETE ---
if (isset($_GET['action']) && $_GET['action'] == 'delete') {
    $id = (int)$_GET['id'];
    $client_id = (int)$_GET['client_id'];
    $conn->query("DELETE FROM payments WHERE id = $id AND agency_id = $agency_id");
    header("Location: view_client_ledger.php?id=$client_id&msg=deleted");
    exit();
}

// --- HANDLE ADD & UPDATE ---
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $client_id = $_POST['client_id'];
    $amount    = $_POST['amount'];
    $type      = $_POST['transaction_type'];
    $date      = $_POST['p_date'];
    $notes     = $_POST['notes'];

    if (isset($_POST['action']) && $_POST['action'] == 'update') {
        // UPDATE EXISTING
        $id = $_POST['id'];
        $stmt = $conn->prepare("UPDATE payments SET amount=?, transaction_type=?, payment_date=?, notes=? WHERE id=? AND agency_id=?");
        $stmt->bind_param("isssii", $amount, $type, $date, $notes, $id, $agency_id);
    } else {
        // ADD NEW
        $stmt = $conn->prepare("INSERT INTO payments (agency_id, client_id, amount, transaction_type, payment_date, notes) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("iissss", $agency_id, $client_id, $amount, $type, $date, $notes);
    }

    if ($stmt->execute()) {
        header("Location: view_client_ledger.php?id=$client_id&msg=success");
    } else {
        echo "Error: " . $conn->error;
    }
}
?>