<?php
session_start();
if (!isset($_SESSION["poslovnica_id"])) {
    header("Location: login.php");
    exit();
}
$conn = new mysqli("localhost", "carsfory_locis", "8QYP2!S?ONk1HQ5_", "carsfory_locis");
$id = $_SESSION["poslovnica_id"];

$where = "WHERE poslovnica_id = $id";
if (!empty($_GET['tip'])) $where .= " AND tip = '" . $_GET['tip'] . "'";
if (!empty($_GET['mjesec'])) $where .= " AND DATE_FORMAT(datum, '%Y-%m') = '" . $_GET['mjesec'] . "'";
$transakcije = $conn->query("SELECT * FROM transakcije $where ORDER BY datum DESC");

// Izračunaj stanje
$stanje = 0;
$rez = $conn->query("SELECT tip, iznos FROM transakcije WHERE poslovnica_id = $id");
while ($row = $rez->fetch_assoc()) {
    $stanje += $row['tip'] === 'uplata' ? $row['iznos'] : -$row['iznos'];
}
?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Dashboard - <?= htmlspecialchars($_SESSION['naziv']) ?></title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body class="bg-light">
<div class="container mt-5">
  <h2 class="mb-3">Blagajna - <?= htmlspecialchars($_SESSION['naziv']) ?></h2>
  <h4>Stanje blagajne: <span class="<?= $stanje < 0 ? 'text-danger fw-bold' : 'text-success' ?>"><?= number_format($stanje, 2) ?> EUR</span></h4>

  <form method="GET" class="row g-2 mb-3">
    <div class="col-md-3">
      <select name="tip" class="form-select">
        <option value="">Sve</option>
        <option value="uplata" <?= ($_GET['tip'] ?? '') === 'uplata' ? 'selected' : '' ?>>Uplate</option>
        <option value="isplata" <?= ($_GET['tip'] ?? '') === 'isplata' ? 'selected' : '' ?>>Isplate</option>
      </select>
    </div>
    <div class="col-md-3">
      <input type="month" name="mjesec" class="form-control" value="<?= htmlspecialchars($_GET['mjesec'] ?? '') ?>">
    </div>
    <div class="col-md-3">
      <button class="btn btn-outline-primary">Filtriraj</button>
      <a href="export_csv.php" class="btn btn-outline-success">CSV</a>
    </div>
  </form>

  <form method="POST" class="row g-3 mb-4">
    <div class="col-md-3">
      <select name="tip" class="form-select">
        <option value="uplata">Uplata</option>
        <option value="isplata">Isplata</option>
      </select>
    </div>
    <div class="col-md-4"><input name="opis" placeholder="Opis" class="form-control" required></div>
    <div class="col-md-3"><input name="iznos" type="number" step="0.01" placeholder="Iznos" class="form-control" required></div>
    <div class="col-md-2"><button class="btn btn-primary">Dodaj</button></div>
  </form>

  <?php
  if ($_SERVER["REQUEST_METHOD"] == "POST") {
      $stmt = $conn->prepare("INSERT INTO transakcije (poslovnica_id, tip, opis, iznos) VALUES (?, ?, ?, ?)");
      $stmt->bind_param("isss", $id, $_POST['tip'], $_POST['opis'], $_POST['iznos']);
      $stmt->execute();
      header("Location: dashboard.php");
  }
  ?>

  <h5>Transakcije</h5>
  <table class="table table-bordered table-striped">
    <thead class="table-light">
      <tr><th>#</th><th>Datum</th><th>Tip</th><th>Opis</th><th>Iznos</th></tr>
    </thead>
    <tbody>
      <?php $rb = 1; while ($row = $transakcije->fetch_assoc()): ?>
      <tr class="<?= $row['tip'] === 'isplata' ? 'table-danger fw-bold' : '' ?>">
        <td><?= $rb++ ?></td>
        <td><?= date('d.m.Y H:i', strtotime($row['datum'])) ?></td>
        <td><?= $row['tip'] ?></td>
        <td><?= htmlspecialchars($row['opis']) ?></td>
        <td><?= number_format($row['iznos'], 2) ?> €</td>
      </tr>
      <?php endwhile; ?>
    </tbody>
  </table>

  <h5 class="mt-4">Graf salda po mjesecima</h5>
  <canvas id="graf" height="100"></canvas>
  <script>
    const ctx = document.getElementById('graf').getContext('2d');
    fetch('graf_data.php')
      .then(res => res.json())
      .then(data => {
        new Chart(ctx, {
          type: 'bar',
          data: {
            labels: data.labels,
            datasets: [{
              label: 'Saldo (EUR)',
              data: data.values,
              backgroundColor: 'rgba(54, 162, 235, 0.5)'
            }]
          }
        });
      });
  </script>

  <a href="logout.php" class="btn btn-secondary mt-4">Odjava</a>
</div>
</body>
</html>
