<?php
header("Content-Type: application/json");
include '../../config.php';

// Pata user_id kutoka kwa GET parameters
$user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;

if ($user_id === 0) {
    echo json_encode(["error" => "Invalid parameters"]);
    exit;
}

$sql = "SELECT 
            e.id, 
            e.price, 
            e.description, 
            e.date, 
            e.user_id, 
            e.branch_id,
            CONCAT(u.firstname, ' ', u.lastname) AS user_name,
            b.branch_name
        FROM expenditures e
        LEFT JOIN users u ON e.user_id = u.id
        LEFT JOIN branches b ON e.branch_id = b.branch_id
        WHERE e.user_id = ? OR e.branch_id IN (SELECT branch_id FROM branches WHERE user_id = ?)";

$stmt = $conn->prepare($sql);
$stmt->bind_param("ii", $user_id, $user_id);
$stmt->execute();
$result = $stmt->get_result();

$expenses = [];
while($row = $result->fetch_assoc()){
    $expenses[] = $row;
}

$stmt->close();
$conn->close();

echo json_encode($expenses);
?>
