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

function column_exists(mysqli $mysqli, string $table, string $column): bool {
    $safeTable = $mysqli->real_escape_string($table);
    $safeColumn = $mysqli->real_escape_string($column);
    $res = $mysqli->query("SHOW COLUMNS FROM `{$safeTable}` LIKE '{$safeColumn}'");
    return $res && $res->num_rows > 0;
}

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) { header('Location: orders.php'); exit; }

$stmt = $mysqli->prepare("
    SELECT o.id, o.usage_date, o.note, o.project_id, p.name AS project_name, p.location, p.project_status
    FROM consumption_orders o
    JOIN projects p ON p.id = o.project_id
    WHERE o.id = ?
");
$stmt->bind_param('i', $id);
$stmt->execute();
$order = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$order) {
    echo '<div class="alert alert-danger m-3">Nalog nije pronađen.</div>';
    require_once 'footer.php'; exit;
}

$dt = DateTime::createFromFormat('Y-m-d', $order['usage_date']);
$date_hr = $dt ? $dt->format('d.m.Y') : $order['usage_date'];
$hasConsumptionItemWarranty = column_exists($mysqli, 'consumption_items', 'has_warranty') && column_exists($mysqli, 'consumption_items', 'warranty_months');
$warrantySelect = $hasConsumptionItemWarranty ? ', ci.has_warranty, ci.warranty_months' : ', 0 AS has_warranty, NULL AS warranty_months';

$items = $mysqli->query("
    SELECT ci.item_id, i.code, i.name, ci.quantity, ci.unit {$warrantySelect}
    FROM consumption_items ci
    JOIN items i ON i.id = ci.item_id
    WHERE ci.order_id = ".(int)$id."
    ORDER BY i.name
");

$mediaRes = $mysqli->query("
    SELECT id, type, path, original_name, mime, created_at
    FROM consumption_order_media
    WHERE order_id = ".(int)$id."
    ORDER BY id DESC
");
$media = [];
if ($mediaRes) { while($r=$mediaRes->fetch_assoc()) { $media[] = $r; } }

?>
<div class="row g-3 mb-3 align-items-center">
    <div class="col">
        <div class="section-title">Pregled naloga</div>
        <div class="text-muted small">Nalog #<?php echo $order['id']; ?></div>
    </div>
    <div class="col-auto d-flex flex-wrap gap-2">
        <a href="orders.php" class="btn btn-outline-secondary btn-soft btn-sm">← Natrag</a>
        <?php if (($order['project_status'] ?? 'open') !== 'closed'): ?>
            <a href="order_edit.php?id=<?php echo $order['id']; ?>" class="btn btn-outline-primary btn-soft btn-sm">Uredi</a>
        <?php endif; ?>
    </div>
</div>

<div class="card card-soft mb-3">
    <div class="card-body card-soft-body">
        <div class="row g-3">
            <div class="col-md-6">
                <div class="text-muted small">Projekt</div>
                <div class="fw-semibold"><?php echo htmlspecialchars($order['project_name']); ?></div>
                <?php if (!empty($order['location'])): ?>
                    <div class="text-muted small"><?php echo htmlspecialchars($order['location']); ?></div>
                <?php endif; ?>
            </div>
            <div class="col-md-3">
                <div class="text-muted small">Datum</div>
                <div class="fw-semibold"><?php echo $date_hr; ?></div>
            </div>
            <div class="col-md-3">
                <div class="text-muted small">Status projekta</div>
                <?php if (($order['project_status'] ?? 'open') === 'closed'): ?>
                    <span class="badge bg-secondary">Dovršen</span>
                <?php else: ?>
                    <span class="badge bg-success">Otvoren</span>
                <?php endif; ?>
            </div>
            <div class="col-12">
                <div class="text-muted small">Napomena</div>
                <div><?php echo htmlspecialchars($order['note'] ?? ''); ?></div>
            </div>
        </div>
    </div>
</div>


<div class="card card-soft mb-3">
    <div class="card-header card-soft-header d-flex justify-content-between align-items-center">
        <span class="fw-semibold">Prilozi</span>
        <span class="pill-counter d-none d-sm-inline"><?php echo !empty($media) ? count($media) : 0; ?> datoteka</span>
    </div>
    <div class="card-body card-soft-body">
        <?php if (empty($media)): ?>
            <div class="text-muted small">Nema priloga.</div>
        <?php else: ?>
            <div class="row g-3">
                <?php foreach($media as $m): ?>
                    <div class="col-12 col-md-6 col-lg-4">
                        <div class="card card-soft h-100">
                            <div class="card-body card-soft-body">
                                <div class="small text-muted mb-2"><?php echo htmlspecialchars($m['original_name'] ?? ''); ?></div>
                                <?php if (($m['type'] ?? '') === 'image'): ?>
                                    <a href="<?php echo htmlspecialchars($m['path']); ?>" target="_blank" rel="noopener">
                                        <img src="<?php echo htmlspecialchars($m['path']); ?>" class="img-fluid rounded" alt="">
                                    </a>
                                <?php else: ?>
                                    <video src="<?php echo htmlspecialchars($m['path']); ?>" class="w-100 rounded" controls preload="metadata"></video>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<div class="card card-soft">
    <div class="card-header card-soft-header d-flex justify-content-between align-items-center">
        <span class="fw-semibold">Stavke</span>
        <span class="pill-counter d-none d-sm-inline"><?php echo (int)$items->num_rows; ?> stavki</span>
    </div>
    <div class="card-body card-soft-body">
        <div class="table-responsive d-none d-md-block">
            <table class="table table-sm align-middle">
                <thead class="small text-muted">
                <tr>
                    <th>Šifra</th>
                    <th>Naziv</th>
                    <th class="text-end">Količina</th>
                    <th>JM</th>
                    <th>Garancija</th>
                </tr>
                </thead>
                <tbody>
                <?php while ($it = $items->fetch_assoc()): ?>
                    <tr>
                        <td class="fw-semibold"><?php echo htmlspecialchars($it['code']); ?></td>
                        <td><?php echo htmlspecialchars($it['name']); ?></td>
                        <td class="text-end"><?php echo rtrim(rtrim(number_format((float)$it['quantity'], 3, ',', '.'), '0'), ','); ?></td>
                        <td><?php echo htmlspecialchars($it['unit']); ?></td>
                        <td><?php echo !empty($it['has_warranty']) ? ('Da' . (!empty($it['warranty_months']) ? ' (' . (int)$it['warranty_months'] . ' mj)' : '')) : 'Ne'; ?></td>
                    </tr>
                <?php endwhile; ?>
                </tbody>
            </table>
        </div>

        <div class="d-md-none">
            <?php
            $items->data_seek(0);
            if ($items->num_rows === 0): ?>
                <div class="text-muted small">Nema stavki.</div>
            <?php endif; ?>
            <?php while ($it = $items->fetch_assoc()): ?>
                <div class="list-card">
                    <div class="list-card-title"><?php echo htmlspecialchars($it['name']); ?></div>
                    <div class="list-card-sub">Šifra: <?php echo htmlspecialchars($it['code']); ?></div>
                    <div class="list-card-meta">
                        Količina: <strong><?php echo rtrim(rtrim(number_format((float)$it['quantity'], 3, ',', '.'), '0'), ','); ?></strong>
                        <?php echo htmlspecialchars($it['unit']); ?>
                    </div>
                    <?php if (!empty($it['has_warranty'])): ?>
                        <div class="list-card-sub">Garancija<?php echo !empty($it['warranty_months']) ? ': ' . (int)$it['warranty_months'] . ' mj' : ''; ?></div>
                    <?php endif; ?>
                </div>
            <?php endwhile; ?>
        </div>
    </div>
</div>

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