<?php
// dashboard.php (samo zadnjih 20 unosa + soft delete/vrati)
session_start();
if (!isset($_SESSION["poslovnica_id"])) {
    header("Location: login.php");
    exit();
}

// ini_set('display_errors',1); error_reporting(E_ALL);

$conn = new mysqli("localhost", "carsfory_locis", "8QYP2!S?ONk1HQ5_", "carsfory_locis");
if ($conn->connect_error) { exit("DB greška."); }
$conn->set_charset('utf8mb4');

$id    = (int)$_SESSION["poslovnica_id"];
$naziv = $_SESSION["naziv"] ?? '';
if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(16));

$tip_whitelist = ['uplata','isplata'];

/* Mapa poslovnica */
$poslovnice_ids = ['Split'=>0,'Pula'=>0];
$res_ids = $conn->query("SELECT id, naziv FROM poslovnice WHERE naziv IN ('Split','Pula')");
while ($row = $res_ids->fetch_assoc()) { $poslovnice_ids[$row['naziv']] = (int)$row['id']; }

/* helper PRG (bez page parametra) */
function redirect_with_filters($msg=''){
    $keep=[]; foreach(['pos','tip','mjesec'] as $k){ if(isset($_GET[$k]) && $_GET[$k]!=='') $keep[$k]=$_GET[$k]; }
    if ($msg!=='') $keep['msg']=$msg;
    header('Location: ?'.http_build_query($keep)); exit;
}

/* Split dodatni pregled */
$fnStanje=function($conn,$pid){
    $s=0.0; $r=$conn->query("SELECT tip, iznos FROM transakcije WHERE poslovnica_id=$pid AND deleted_at IS NULL");
    while($x=$r->fetch_assoc()){ $s += ($x['tip']==='uplata') ? (float)$x['iznos'] : -(float)$x['iznos']; }
    return $s;
};
$stanje_split=$fnStanje($conn,$poslovnice_ids['Split']);
$stanje_pula=$fnStanje($conn,$poslovnice_ids['Pula']);
$stanje_zbrojno=$stanje_split+$stanje_pula;

$dodatni_pregled=[];
if ($naziv==='Split'){
    foreach(['Pula'] as $pos_naziv){
        $pid=$poslovnice_ids[$pos_naziv];
        $lokal=$fnStanje($conn,$pid);
        $trans=$conn->query("SELECT * FROM transakcije WHERE poslovnica_id=$pid AND deleted_at IS NULL ORDER BY datum DESC LIMIT 10");
        $dodatni_pregled[$pos_naziv]=['stanje'=>$lokal,'transakcije'=>$trans];
    }
}

/* Odabir poslovnice */
$pregled_id=$id;
$dodatne_poslovnice=[];
if ($naziv==='Split'){
    $doz=$conn->query("SELECT id, naziv FROM poslovnice WHERE naziv IN ('Pula')");
    while($row=$doz->fetch_assoc()){ $dodatne_poslovnice[(int)$row['id']]=$row['naziv']; }
    if (isset($_GET['pos']) && $_GET['pos']!=='' && isset($dodatne_poslovnice[(int)$_GET['pos']])) $pregled_id=(int)$_GET['pos'];
}

/* Filteri */
$tip_filter = $_GET['tip'] ?? '';
$mjesec_filter = $_GET['mjesec'] ?? '';
$msg = $_GET['msg'] ?? '';

$whereParts = ["poslovnica_id = $pregled_id","deleted_at IS NULL"];
if ($tip_filter && in_array($tip_filter,$tip_whitelist,true)) $whereParts[] = "tip = '".$conn->real_escape_string($tip_filter)."'";
if ($mjesec_filter && preg_match('/^\d{4}\-\d{2}$/',$mjesec_filter)) $whereParts[] = "DATE_FORMAT(datum, '%Y-%m') = '".$conn->real_escape_string($mjesec_filter)."'";
$where = "WHERE ".implode(' AND ',$whereParts);

/* EDIT prefill (samo vlastita poslovnica) */
$edit_id = isset($_GET['edit_id']) ? (int)$_GET['edit_id'] : 0;
$edit_row=['tip'=>'uplata','opis'=>'','iznos'=>''];
if ($edit_id>0){
    $stmt=$conn->prepare("SELECT * FROM transakcije WHERE id=? AND poslovnica_id=?");
    $stmt->bind_param("ii",$edit_id,$id); $stmt->execute();
    $res=$stmt->get_result();
    if ($res && $res->num_rows===1) $edit_row=$res->fetch_assoc(); else $edit_id=0;
    $stmt->close();
}

/* POST akcije */
if ($_SERVER["REQUEST_METHOD"]==="POST"){
    if (!isset($_POST['csrf']) || !hash_equals($_SESSION['csrf'],$_POST['csrf'])) exit("Nevažeći CSRF token.");
    if ($pregled_id !== $id) redirect_with_filters("Uređivanje/brisanje dopušteno je samo za vlastitu poslovnicu.");

    $akcija=$_POST['akcija'] ?? 'save';

    if ($akcija==='delete'){
        $del_id=(int)($_POST['id'] ?? 0);
        if ($del_id>0){
            $stmt=$conn->prepare("UPDATE transakcije SET deleted_at=NOW() WHERE id=? AND poslovnica_id=? AND deleted_at IS NULL");
            $stmt->bind_param("ii",$del_id,$id); $ok=$stmt->execute(); $stmt->close();
            redirect_with_filters($ok?"Stavka obrisana (soft).":"Greška pri brisanju.");
        }
        redirect_with_filters("Neispravan ID.");
    }
    if ($akcija==='restore'){
        $res_id=(int)($_POST['id'] ?? 0);
        if ($res_id>0){
            $stmt=$conn->prepare("UPDATE transakcije SET deleted_at=NULL WHERE id=? AND poslovnica_id=? AND deleted_at IS NOT NULL");
            $stmt->bind_param("ii",$res_id,$id); $ok=$stmt->execute(); $stmt->close();
            redirect_with_filters($ok?"Stavka vraćena.":"Greška pri vraćanju.");
        }
        redirect_with_filters("Neispravan ID.");
    }

    // save insert/update
    $tid=(int)($_POST['id'] ?? 0);
    $tip=$_POST['tip'] ?? 'uplata'; if (!in_array($tip,$tip_whitelist,true)) $tip='uplata';
    $opis=trim($_POST['opis'] ?? '');
    $iznos=(float)($_POST['iznos'] ?? 0);

    if ($tid>0){
        $stmt=$conn->prepare("UPDATE transakcije SET tip=?, opis=?, iznos=? WHERE id=? AND poslovnica_id=?");
        $stmt->bind_param("ssdii",$tip,$opis,$iznos,$tid,$id);
        $ok=$stmt->execute(); $stmt->close();
        redirect_with_filters($ok?"Stavka ažurirana.":"Greška pri spremanju.");
    } else {
        $stmt=$conn->prepare("INSERT INTO transakcije (poslovnica_id, tip, opis, iznos) VALUES (?, ?, ?, ?)");
        $stmt->bind_param("issd",$id,$tip,$opis,$iznos);
        $ok=$stmt->execute(); $stmt->close();
        redirect_with_filters($ok?"Stavka dodana.":"Greška pri spremanju.");
    }
}

/* LISTA: uvijek samo zadnjih 20 zapisa (po filterima) */
$transakcije = $conn->query("SELECT * FROM transakcije $where ORDER BY datum DESC, id DESC LIMIT 20");

/* Stanje za pregled_id (samo aktivne) */
$stanje = 0.0;
$rez = $conn->query("SELECT tip, iznos FROM transakcije WHERE poslovnica_id=$pregled_id AND deleted_at IS NULL");
while($row=$rez->fetch_assoc()){ $stanje += ($row['tip']==='uplata')?(float)$row['iznos']:-(float)$row['iznos']; }

/* graf url */
$graf_url='graf_data.php';
if ($naziv==='Split' && isset($_GET['pos']) && $_GET['pos']!=='') $graf_url.='?pos='.(int)$_GET['pos'];
?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Dashboard - <?= htmlspecialchars($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>
  <style>
    body{background:#f4f7fb!important;color:#0f172a;font-family:Inter,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}
    .page-shell{max-width:1450px;margin:0 auto;padding:24px 14px 42px}
    .top-actions .btn{border-radius:11px;font-weight:700;padding:.58rem .9rem}
    .cash-table-card{background:#fff;border:1px solid #dfe6ef;border-radius:15px;overflow:hidden;box-shadow:0 5px 18px rgba(15,23,42,.04)}
    .cash-table-scroll{overflow-x:auto}
    .cash-table{width:100%;margin:0;border-collapse:separate;border-spacing:0;font-size:13px}
    .cash-table thead th{background:#f3f6fa;color:#4b5d75;font-size:11px;font-weight:800;text-transform:uppercase;letter-spacing:.025em;padding:11px 13px;border:0;border-bottom:1px solid #dfe6ef;white-space:nowrap}
    .cash-table tbody td{padding:11px 13px;border:0;border-bottom:1px solid #e5eaf1;vertical-align:middle;background:#fff}
    .cash-table tbody tr:last-child td{border-bottom:0}
    .cash-table tbody tr:hover td{background:#f8fbff}
    .cash-table tbody tr.cash-out td{background:#fff4f4}
    .cash-table tbody tr.cash-out:hover td{background:#ffecec}
    .cash-table tbody tr.cash-out td:nth-child(3),.cash-table tbody tr.cash-out td:nth-child(4),.cash-table tbody tr.cash-out .amount{font-weight:700}
    .cash-table .amount{text-align:right;font-weight:800;white-space:nowrap}
    .cash-table .cash-out .amount{color:#dc3545}
    .cash-table .actions{white-space:nowrap}
    .cash-table .actions form{display:inline-block;margin:0 0 0 5px}
    .cash-table .btn-sm{border-radius:8px;font-size:12px;font-weight:700}
    .section-title{font-size:16px;font-weight:800;margin:24px 0 10px}
    .topbar{background:#fff;border:1px solid #dfe6ef;border-radius:18px;padding:14px 18px;box-shadow:0 8px 24px rgba(15,23,42,.06);margin-bottom:24px}
    .brand-wrap{display:flex;align-items:center;gap:12px}
    .brand-badge{width:42px;height:42px;border-radius:13px;background:linear-gradient(135deg,#2f80ed,#1559d6);color:#fff;display:flex;align-items:center;justify-content:center;font-weight:900;box-shadow:0 8px 18px rgba(37,99,235,.22)}
    .brand-title{font-size:18px;font-weight:900;line-height:1.15}.brand-subtitle{font-size:12px;color:#64748b;margin-top:3px}
    .dashboard-card{background:#fff;border:1px solid #dfe6ef;border-radius:18px;box-shadow:0 8px 24px rgba(15,23,42,.05);padding:20px;margin-bottom:18px}
    .balance-card{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:16px;background:linear-gradient(135deg,#ffffff,#f8fbff);border:1px solid #dbe7f5;border-radius:18px;padding:20px 22px;margin-bottom:18px}
    .balance-label{font-size:13px;color:#64748b;font-weight:700;text-transform:uppercase;letter-spacing:.04em}.balance-value{font-size:30px;font-weight:900;line-height:1.15;margin-top:4px}
    .form-label-mini{font-size:12px;font-weight:800;color:#334155;margin-bottom:6px}.form-control,.form-select{border-radius:11px;border-color:#cfd9e7;min-height:42px}.form-control:focus,.form-select:focus{border-color:#2f80ed;box-shadow:0 0 0 .2rem rgba(47,128,237,.12)}
    .btn{border-radius:10px;font-weight:750}.entry-title{font-size:15px;font-weight:900;margin-bottom:14px}.muted-note{font-size:12px;color:#64748b}
    .type-badge{display:inline-flex;align-items:center;border-radius:999px;padding:4px 9px;font-size:11px;font-weight:800;background:#eaf2ff;color:#1767d2}.type-badge.out{background:#ffe8e8;color:#d62f3f}
    @media(max-width:768px){.page-shell{padding-top:14px}.top-actions{justify-content:flex-start!important}.cash-table{min-width:760px}.topbar{padding:12px}.balance-value{font-size:24px}}
  </style>
</head>
<body>
<div class="page-shell">
  <div class="topbar d-flex flex-wrap align-items-center justify-content-between gap-3">
    <div class="brand-wrap">
      <div class="brand-badge">AV</div>
      <div>
        <div class="brand-title">Blagajna</div>
        <div class="brand-subtitle">Poslovnica: <?= htmlspecialchars($naziv) ?> · pregled i evidencija transakcija</div>
      </div>
    </div>
    <div class="d-flex flex-wrap justify-content-end gap-2 top-actions">
      <?php if (in_array($id, [1,2,3,4,5,6], true)): ?>
        <a href="najmovi.php?poslovnica_id=<?= $id ?>" class="btn btn-primary">Najmovi</a>
      <?php endif; ?>
      <?php if ($id === 5): ?>
        <a href="afterhour.php" class="btn btn-outline-secondary">Afterhour</a>
        <a href="walkin.php" class="btn btn-outline-secondary">Walk In</a>
      <?php endif; ?>
      <a href="logout.php" class="btn btn-outline-danger">Odjava</a>
    </div>
  </div>

<?php if ($naziv === 'Split'): ?>
<div class="bg-white p-3 mb-4 rounded shadow-sm">
  <h5>Stanje po poslovnicama</h5>
  <div class="d-flex flex-wrap gap-3">
    <div><strong>Split:</strong> <span class="<?= $stanje_split < 0 ? 'text-danger' : 'text-success' ?>"><?= number_format((float)$stanje_split, 2) ?> €</span></div>
    <div><strong>Pula:</strong> <span class="<?= $stanje_pula < 0 ? 'text-danger' : 'text-success' ?>"><?= number_format((float)$stanje_pula, 2) ?> €</span></div>
    <div><strong>Ukupno:</strong> <span class="<?= $stanje_zbrojno < 0 ? 'text-danger fw-bold' : 'text-success fw-bold' ?>"><?= number_format((float)$stanje_zbrojno, 2) ?> €</span></div>
  </div>
</div>
<?php endif; ?>

<?php if ($msg): ?><div class="alert alert-info"><?= htmlspecialchars($msg) ?></div><?php endif; ?>

<div class="balance-card">
  <div>
    <div class="balance-label">Trenutno stanje blagajne</div>
    <div class="balance-value <?= $stanje < 0 ? 'text-danger' : 'text-success' ?>"><?= number_format((float)$stanje, 2, ',', '.') ?> EUR</div>
  </div>
  <div class="muted-note">Prikazani saldo obuhvaća aktivne uplate i isplate odabrane poslovnice.</div>
</div>

<?php if (!empty($dodatne_poslovnice)): ?>
<form method="GET" class="mb-4">
  <label for="pos" class="form-label">Odaberi poslovnicu za pregled:</label>
  <select name="pos" id="pos" class="form-select" onchange="this.form.submit()" style="max-width: 300px;">
    <option value="">Split (moja)</option>
    <?php foreach ($dodatne_poslovnice as $pos_id => $pos_naziv): ?>
      <option value="<?= $pos_id ?>" <?= ($pregled_id == $pos_id) ? 'selected' : '' ?>><?= $pos_naziv ?></option>
    <?php endforeach; ?>
  </select>
</form>
<?php endif; ?>

<!-- Filteri -->
<div class="dashboard-card">
  <div class="entry-title">Filter transakcija</div>
<form method="GET" class="row g-3 align-items-end mb-0">
  <?php if (!empty($dodatne_poslovnice)): ?>
    <input type="hidden" name="pos" value="<?= htmlspecialchars($_GET['pos'] ?? '') ?>">
  <?php endif; ?>
  <div class="col-md-3">
    <select name="tip" class="form-select">
      <option value="">Sve</option>
      <option value="uplata"  <?= ($tip_filter==='uplata')?'selected':'' ?>>Uplate</option>
      <option value="isplata" <?= ($tip_filter==='isplata')?'selected':'' ?>>Isplate</option>
    </select>
  </div>
  <div class="col-md-3"><input type="month" name="mjesec" class="form-control" value="<?= htmlspecialchars($mjesec_filter) ?>"></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>
</div>

<!-- Dodaj/uredi: samo vlastita -->
<?php if ($pregled_id === $id): ?>
<div class="dashboard-card">
  <div class="entry-title"><?= $edit_id>0 ? 'Uredi transakciju' : 'Nova transakcija' ?></div>
<form method="POST" class="row g-3 mb-0">
  <input type="hidden" name="csrf" value="<?= htmlspecialchars($_SESSION['csrf']) ?>">
  <input type="hidden" name="akcija" value="save">
  <input type="hidden" name="id" value="<?= $edit_id>0?(int)$edit_id:'' ?>">

  <div class="col-md-3">
    <select name="tip" class="form-select">
      <?php foreach($tip_whitelist as $t): ?>
        <option value="<?= $t ?>" <?= ($edit_id>0 && $edit_row['tip']===$t)?'selected':'' ?>><?= ucfirst($t) ?></option>
      <?php endforeach; ?>
    </select>
  </div>
  <div class="col-md-5"><input name="opis" placeholder="Opis" class="form-control" required value="<?= $edit_id>0?htmlspecialchars($edit_row['opis']):'' ?>"></div>
  <div class="col-md-2"><input name="iznos" type="number" step="0.01" placeholder="Iznos" class="form-control" required value="<?= $edit_id>0?htmlspecialchars((string)$edit_row['iznos']):'' ?>"></div>
  <div class="col-md-2 d-flex gap-2">
    <button class="btn btn-primary"><?= $edit_id>0?'Spremi izmjene':'Dodaj' ?></button>
    <?php if ($edit_id>0): ?>
      <a class="btn btn-outline-secondary" href="?<?= http_build_query(array_filter(['pos'=>$_GET['pos']??null,'tip'=>$tip_filter,'mjesec'=>$mjesec_filter])) ?>">Odustani</a>
    <?php endif; ?>
  </div>
</form>
</div>
<?php else: ?>
  <div class="alert alert-warning">Za druge poslovnice dopušten je samo pregled (bez izmjena).</div>
<?php endif; ?>

<h5 class="section-title">Transakcije (zadnjih 20)</h5>
<div class="cash-table-card">
<div class="cash-table-scroll">
<table class="cash-table">
  <thead>
    <tr>
      <th>#</th><th>Datum</th><th>Tip</th><th>Opis</th><th>Iznos</th>
      <?php if ($pregled_id === $id): ?><th style="width:210px;">Akcije</th><?php endif; ?>
    </tr>
  </thead>
  <tbody>
    <?php $rb=1; while($row=$transakcije->fetch_assoc()): ?>
    <tr class="<?= $row['tip']==='isplata' ? 'cash-out' : '' ?>">
      <td><?= $rb++ ?></td>
      <td><?= date('d.m.Y H:i', strtotime($row['datum'])) ?></td>
      <td><span class="type-badge <?= $row['tip']==='isplata' ? 'out' : '' ?>"><?= htmlspecialchars(ucfirst($row['tip'])) ?></span></td>
      <td><?= htmlspecialchars($row['opis']) ?></td>
      <td class="amount"><?= number_format((float)$row['iznos'], 2, ',', '.') ?> €</td>
      <?php if ($pregled_id === $id): ?>
      <td class="actions">
        <?php $qs=array_filter(['pos'=>$_GET['pos']??null,'tip'=>$tip_filter,'mjesec'=>$mjesec_filter,'edit_id'=>(int)$row['id']]); ?>
        <a class="btn btn-sm btn-outline-primary" href="?<?= http_build_query($qs) ?>">Uredi</a>

        <form method="POST" onsubmit="return confirm('Izbrisati ovu stavku?');">
          <input type="hidden" name="csrf" value="<?= htmlspecialchars($_SESSION['csrf']) ?>">
          <input type="hidden" name="akcija" value="delete">
          <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
          <button class="btn btn-sm btn-outline-danger">Izbriši</button>
        </form>

        <?php if (!empty($row['deleted_at'])): ?>
        <form method="POST">
          <input type="hidden" name="csrf" value="<?= htmlspecialchars($_SESSION['csrf']) ?>">
          <input type="hidden" name="akcija" value="restore">
          <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
          <button class="btn btn-sm btn-outline-success">Vrati</button>
        </form>
        <?php endif; ?>
      </td>
      <?php endif; ?>
    </tr>
    <?php endwhile; ?>
  </tbody>
</table>
</div>
</div>

<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_url ?>')
    .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>
</div>
</body>
</html>