<?php
session_start();
header('Content-Type: application/json');

$conn = new mysqli("localhost", "root", "", "blagajna");

if (!isset($_SESSION["poslovnica_id"])) {
    echo json_encode(['error' => 'Niste prijavljeni']);
    exit();
}

$id = $_SESSION["poslovnica_id"];
$res = $conn->query("
  SELECT DATE_FORMAT(datum, '%Y-%m') AS mjesec, 
         SUM(CASE WHEN tip='uplata' THEN iznos ELSE -iznos END) AS saldo 
  FROM transakcije 
  WHERE poslovnica_id = $id 
  GROUP BY mjesec 
  ORDER BY mjesec
");

$labels = [];
$values = [];

while ($row = $res->fetch_assoc()) {
    $labels[] = $row['mjesec'];
    $values[] = floatval($row['saldo']);
}

echo json_encode(['labels' => $labels, 'values' => $values]);
?>
