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

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

// osnovni podaci o projektu
$stmt = $mysqli->prepare("SELECT name, location, project_status FROM projects WHERE id = ?");
$stmt->bind_param('i', $project_id);
$stmt->execute();
$stmt->bind_result($p_name, $p_location, $p_status);
if (!$stmt->fetch()) {
    $stmt->close();
    echo '<div class="alert alert-danger m-3">Projekt nije pronađen.</div>';
    require_once 'footer.php';
    exit;
}
$stmt->close();

$date_from_display = trim($_GET['date_from'] ?? '');
$date_to_display   = trim($_GET['date_to'] ?? '');
$date_from_sql = '';
$date_to_sql   = '';

if ($date_from_display !== '') {
    $dt = DateTime::createFromFormat('d.m.Y', $date_from_display);
    if ($dt) $date_from_sql = $dt->format('Y-m-d');
}
if ($date_to_display !== '') {
    $dt = DateTime::createFromFormat('d.m.Y', $date_to_display);
    if ($dt) $date_to_sql = $dt->format('Y-m-d');
}

$where = ["o.project_id = " . $project_id];
if ($date_from_sql !== '') {
    $where[] = "o.usage_date >= '" . $mysqli->real_escape_string($date_from_sql) . "'";
}
if ($date_to_sql !== '') {
    $where[] = "o.usage_date <= '" . $mysqli->real_escape_string($date_to_sql) . "'";
}
$where_sql = 'WHERE ' . implode(' AND ', $where);

$sql = "
SELECT 
    o.id AS order_id,
    o.usage_date,
    o.note,
    i.code,
    i.name AS item_name,
    ci.quantity,
    ci.unit
FROM consumption_items ci
JOIN consumption_orders o ON o.id = ci.order_id
JOIN items i ON i.id = ci.item_id
{$where_sql}
ORDER BY o.usage_date, o.id, i.name
";
$res = $mysqli->query($sql);

$query_params = [
    'project_id' => $project_id,
    'date_from'  => $date_from_display,
    'date_to'    => $date_to_display
];
$export_query = http_build_query($query_params);
?>
<div class="row g-3 mb-3 align-items-center">
    <div class="col">
        <div class="section-title">Utrošak po projektu</div>
        <div class="text-muted small">
            Projekt: <strong><?php echo htmlspecialchars($p_name); ?></strong>
            <?php if ($p_location): ?>
                • <?php echo htmlspecialchars($p_location); ?>
            <?php endif; ?>
            • Status:
            <?php if ($p_status === 'closed'): ?>
                <span class="badge bg-secondary">Dovršen</span>
            <?php else: ?>
                <span class="badge bg-success">Otvoren</span>
            <?php endif; ?>
        </div>
    </div>
    <div class="col-auto d-flex flex-wrap gap-2">
        <a href="projects.php" class="btn btn-outline-secondary btn-soft btn-sm">← Projekti</a>
        <a href="project_items_pdf.php?<?php echo $export_query; ?>"
           class="btn btn-outline-secondary btn-soft btn-sm" target="_blank">
            PDF
        </a>
        <a href="export_project_items_excel.php?<?php echo $export_query; ?>"
           class="btn btn-outline-success btn-soft btn-sm">
            Excel (stavke)
        </a>
        <a href="export_project_items_agg_excel.php?<?php echo $export_query; ?>"
           class="btn btn-outline-success btn-soft btn-sm">
            Excel (zbrojeno po artiklu)
        </a>
    </div>
</div>

<div class="card card-soft mb-3">
    <div class="card-header card-soft-header">
        <span class="fw-semibold">Filter po datumu</span>
    </div>
    <div class="card-body card-soft-body">
        <form method="get" class="row g-3">
            <input type="hidden" name="project_id" value="<?php echo $project_id; ?>">
            <div class="col-md-4 col-6">
                <label class="form-label">Datum od</label>
                <input type="text" name="date_from" class="form-control form-control-sm"
                       placeholder="dd.mm.yyyy"
                       value="<?php echo htmlspecialchars($date_from_display); ?>">
            </div>
            <div class="col-md-4 col-6">
                <label class="form-label">Datum do</label>
                <input type="text" name="date_to" class="form-control form-control-sm"
                       placeholder="dd.mm.yyyy"
                       value="<?php echo htmlspecialchars($date_to_display); ?>">
            </div>
            <div class="col-md-4 col-12 d-flex align-items-end">
                <button class="btn btn-outline-primary btn-soft w-100 btn-sm" type="submit">Primijeni filter</button>
            </div>
        </form>
    </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 utroška</span>
        <span class="pill-counter d-none d-sm-inline">
            <?php echo (int)$res->num_rows; ?> stavki
        </span>
    </div>
    <div class="card-body card-soft-body">

        <div class="d-md-none">
            <?php
            $res->data_seek(0);
            if ($res->num_rows === 0): ?>
                <div class="text-muted small">Nema stavki za zadane kriterije.</div>
            <?php endif; ?>
            <?php while ($row = $res->fetch_assoc()):
                $dt = DateTime::createFromFormat('Y-m-d', $row['usage_date']);
                $date_hr = $dt ? $dt->format('d.m.Y') : $row['usage_date'];
            ?>
                <div class="list-card">
                    <div class="list-card-title">
                        <?php echo htmlspecialchars($row['item_name']); ?>
                    </div>
                    <div class="list-card-sub">
                        Datum: <strong><?php echo $date_hr; ?></strong>
                        • Nalog #<?php echo $row['order_id']; ?>
                    </div>
                    <div class="list-card-meta">
                        Šifra: <?php echo htmlspecialchars($row['code']); ?><br>
                        Količina:
                        <strong>
                            <?php echo number_format((float)$row['quantity'], 3, ',', '.'); ?>
                            <?php echo htmlspecialchars($row['unit']); ?>
                        </strong>
                    </div>
                    <?php if (!empty($row['note'])): ?>
                        <div class="text-muted small mt-1">
                            Napomena naloga: <?php echo htmlspecialchars($row['note']); ?>
                        </div>
                    <?php endif; ?>
                </div>
            <?php endwhile; ?>
        </div>

        <div class="d-none d-md-block">
            <div class="table-responsive">
                <table class="table table-sm align-middle">
                    <thead class="small text-muted">
                    <tr>
                        <th>Datum</th>
                        <th># Nalog</th>
                        <th>Šifra</th>
                        <th>Artikl</th>
                        <th class="text-end">Količina</th>
                        <th>JM</th>
                        <th>Napomena naloga</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php
                    $res->data_seek(0);
                    while ($row = $res->fetch_assoc()):
                        $dt = DateTime::createFromFormat('Y-m-d', $row['usage_date']);
                        $date_hr = $dt ? $dt->format('d.m.Y') : $row['usage_date'];
                    ?>
                        <tr>
                            <td><?php echo $date_hr; ?></td>
                            <td><?php echo $row['order_id']; ?></td>
                            <td><?php echo htmlspecialchars($row['code']); ?></td>
                            <td><?php echo htmlspecialchars($row['item_name']); ?></td>
                            <td class="text-end">
                                <?php echo number_format((float)$row['quantity'], 3, ',', '.'); ?>
                            </td>
                            <td><?php echo htmlspecialchars($row['unit']); ?></td>
                            <td><?php echo htmlspecialchars($row['note']); ?></td>
                        </tr>
                    <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>

    </div>
</div>

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