<?php
require_once 'header.php';
require_permission('items');

$item_id = (int)($_GET['id'] ?? 0);
if ($item_id <= 0) {
    echo '<div class="alert alert-danger m-3">Artikl nije odabran.</div>';
    require_once 'footer.php';
    exit;
}

// osnovni podaci
$sqlItem = "SELECT i.id, i.code, i.name, i.unit, g.name AS group_name
            FROM items i
            LEFT JOIN item_groups g ON g.id = i.item_group_id
            WHERE i.id = ?";
$stmt = $mysqli->prepare($sqlItem);
$stmt->bind_param('i', $item_id);
$stmt->execute();
$stmt->bind_result($id, $code, $name, $unit, $group_name);
if (!$stmt->fetch()) {
    $stmt->close();
    echo '<div class="alert alert-danger m-3">Artikl nije pronađen.</div>';
    require_once 'footer.php';
    exit;
}
$stmt->close();

// agregati
$stmtIn = $mysqli->prepare("
    SELECT COALESCE(SUM(ri.quantity),0) AS total_in
    FROM receipt_items ri
    JOIN receipts r ON r.id = ri.receipt_id
    WHERE ri.item_id = ?
");
$stmtIn->bind_param('i', $item_id);
$stmtIn->execute();
$stmtIn->bind_result($total_in);
$stmtIn->fetch();
$stmtIn->close();

$stmtOut = $mysqli->prepare("
    SELECT COALESCE(SUM(ci.quantity),0) AS total_out
    FROM consumption_items ci
    JOIN consumption_orders o ON o.id = ci.order_id
    WHERE ci.item_id = ?
");
$stmtOut->bind_param('i', $item_id);
$stmtOut->execute();
$stmtOut->bind_result($total_out);
$stmtOut->fetch();
$stmtOut->close();

$total_in  = (float)$total_in;
$total_out = (float)$total_out;
$stock     = $total_in - $total_out;

// primke
$sqlReceipts = "
    SELECT 
        r.id AS receipt_id,
        r.receipt_date,
        r.doc_no,
        r.note,
        s.name AS supplier_name,
        ri.quantity,
        ri.unit
    FROM receipt_items ri
    JOIN receipts r   ON r.id = ri.receipt_id
    JOIN suppliers s  ON s.id = r.supplier_id
    WHERE ri.item_id = ?
    ORDER BY r.receipt_date, r.id
";
$stmtR = $mysqli->prepare($sqlReceipts);
$stmtR->bind_param('i', $item_id);
$stmtR->execute();
$resReceipts = $stmtR->get_result();
$receipts = [];
while ($row = $resReceipts->fetch_assoc()) {
    $receipts[] = $row;
}
$stmtR->close();

// nalozi
$sqlOrders = "
    SELECT 
        o.id AS order_id,
        o.usage_date,
        o.note,
        p.name AS project_name,
        ci.quantity,
        ci.unit
    FROM consumption_items ci
    JOIN consumption_orders o ON o.id = ci.order_id
    JOIN projects p           ON p.id = o.project_id
    WHERE ci.item_id = ?
    ORDER BY o.usage_date, o.id
";
$stmtO = $mysqli->prepare($sqlOrders);
$stmtO->bind_param('i', $item_id);
$stmtO->execute();
$resOrders = $stmtO->get_result();
$orders = [];
while ($row = $resOrders->fetch_assoc()) {
    $orders[] = $row;
}
$stmtO->close();
?>
<div class="row g-3 mb-3 align-items-center">
    <div class="col">
        <div class="section-title">Kartica artikla</div>
        <div class="text-muted small">Pregled primki i naloga utroška</div>
    </div>
    <div class="col-auto d-flex flex-wrap gap-2">
        <a href="items.php" class="btn btn-outline-secondary btn-soft btn-sm">← Artikli</a>
        <a href="stock.php" class="btn btn-outline-secondary btn-soft btn-sm">Stanje skladišta</a>
    </div>
</div>

<div class="card card-soft mb-3">
    <div class="card-body card-soft-body">
        <div class="row g-3 align-items-center">
            <div class="col-12 col-md-8">
                <div class="fw-semibold mb-1">
                    <?php echo htmlspecialchars($name); ?>
                </div>
                <div class="text-muted small">
                    Šifra: <strong><?php echo htmlspecialchars($code); ?></strong><br>
                    JM: <?php echo htmlspecialchars($unit); ?><br>
                    Grupa: <?php echo htmlspecialchars($group_name ?: 'Bez grupe'); ?>
                </div>
            </div>
            <div class="col-12 col-md-4 text-md-end">
                <div class="small text-muted">Stanje skladišta</div>
                <div class="fw-bold fs-5">
                    <?php echo number_format($stock, 3, ',', '.'); ?> <?php echo htmlspecialchars($unit); ?>
                </div>
                <div class="small mt-1">
                    Ulaz: <?php echo number_format($total_in, 3, ',', '.'); ?> |
                    Izlaz: <?php echo number_format($total_out, 3, ',', '.'); ?>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row g-3">
    <div class="col-12 col-lg-6">
        <div class="card card-soft">
            <div class="card-header card-soft-header">
                <span class="fw-semibold">Primke (ulaz)</span>
            </div>
            <div class="card-body card-soft-body">
                <?php if (empty($receipts)): ?>
                    <div class="text-muted small">Nema primki za ovaj artikl.</div>
                <?php else: ?>
                    <div class="table-responsive d-none d-md-block">
                        <table class="table table-sm align-middle">
                            <thead class="small text-muted">
                            <tr>
                                <th>Datum</th>
                                <th>Dobavljač</th>
                                <th>Dokument</th>
                                <th class="text-end">Količina</th>
                                <th>JM</th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php foreach ($receipts as $r):
                                $dt = DateTime::createFromFormat('Y-m-d', $r['receipt_date']);
                                $date_hr = $dt ? $dt->format('d.m.Y') : $r['receipt_date'];
                            ?>
                                <tr>
                                    <td><?php echo $date_hr; ?></td>
                                    <td><?php echo htmlspecialchars($r['supplier_name']); ?></td>
                                    <td><?php echo htmlspecialchars($r['doc_no']); ?></td>
                                    <td class="text-end">
                                        <?php echo number_format((float)$r['quantity'], 3, ',', '.'); ?>
                                    </td>
                                    <td><?php echo htmlspecialchars($r['unit']); ?></td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <div class="d-md-none">
                        <?php foreach ($receipts as $r):
                            $dt = DateTime::createFromFormat('Y-m-d', $r['receipt_date']);
                            $date_hr = $dt ? $dt->format('d.m.Y') : $r['receipt_date'];
                        ?>
                            <div class="list-card">
                                <div class="list-card-title">
                                    <?php echo htmlspecialchars($r['supplier_name']); ?>
                                </div>
                                <div class="list-card-sub">
                                    Datum: <strong><?php echo $date_hr; ?></strong>
                                    <?php if (!empty($r['doc_no'])): ?>
                                        • Br: <?php echo htmlspecialchars($r['doc_no']); ?>
                                    <?php endif; ?>
                                </div>
                                <div class="list-card-meta">
                                    Količina: <strong>
                                        <?php echo number_format((float)$r['quantity'], 3, ',', '.'); ?>
                                        <?php echo htmlspecialchars($r['unit']); ?>
                                    </strong>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div class="col-12 col-lg-6">
        <div class="card card-soft">
            <div class="card-header card-soft-header">
                <span class="fw-semibold">Nalozi utroška (izlaz)</span>
            </div>
            <div class="card-body card-soft-body">
                <?php if (empty($orders)): ?>
                    <div class="text-muted small">Nema naloga utroška za ovaj artikl.</div>
                <?php else: ?>
                    <div class="table-responsive d-none d-md-block">
                        <table class="table table-sm align-middle">
                            <thead class="small text-muted">
                            <tr>
                                <th>Datum</th>
                                <th>Projekt</th>
                                <th># Nalog</th>
                                <th class="text-end">Količina</th>
                                <th>JM</th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php foreach ($orders as $o):
                                $dt = DateTime::createFromFormat('Y-m-d', $o['usage_date']);
                                $date_hr = $dt ? $dt->format('d.m.Y') : $o['usage_date'];
                            ?>
                                <tr>
                                    <td><?php echo $date_hr; ?></td>
                                    <td><?php echo htmlspecialchars($o['project_name']); ?></td>
                                    <td><?php echo $o['order_id']; ?></td>
                                    <td class="text-end">
                                        <?php echo number_format((float)$o['quantity'], 3, ',', '.'); ?>
                                    </td>
                                    <td><?php echo htmlspecialchars($o['unit']); ?></td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <div class="d-md-none">
                        <?php foreach ($orders as $o):
                            $dt = DateTime::createFromFormat('Y-m-d', $o['usage_date']);
                            $date_hr = $dt ? $dt->format('d.m.Y') : $o['usage_date'];
                        ?>
                            <div class="list-card">
                                <div class="list-card-title">
                                    <?php echo htmlspecialchars($o['project_name']); ?>
                                </div>
                                <div class="list-card-sub">
                                    Datum: <strong><?php echo $date_hr; ?></strong>
                                    • Nalog #<?php echo $o['order_id']; ?>
                                </div>
                                <div class="list-card-meta">
                                    Količina: <strong>
                                        <?php echo number_format((float)$o['quantity'], 3, ',', '.'); ?>
                                        <?php echo htmlspecialchars($o['unit']); ?>
                                    </strong>
                                </div>
                                <?php if (!empty($o['note'])): ?>
                                    <div class="text-muted small mt-1">
                                        Napomena naloga: <?php echo htmlspecialchars($o['note']); ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php require_once 'footer.php'; ?>
