<?php
// app/Views/inventory/reports.php
$isInventoryRole = ($_SESSION['role'] === 'inventory');
$baseUrl  = $isInventoryRole ? '/inventory' : '/admin/inventory';
$cashierQs = $ctx['cashier_id'] ? '?cashier_id=' . $ctx['cashier_id'] : '';
$cashierQsAmp = $ctx['cashier_id'] ? '&cashier_id=' . $ctx['cashier_id'] : '';

$currency = '৳';
$stockInVal = $report['kpis']['stock_in'];
$stockOutVal = $report['kpis']['stock_out'];
$wasteVal = $report['kpis']['waste'];

$exportUrl = $baseUrl . '/reports/export?range_type=' . $range_type . '&from=' . $report['from'] . '&to=' . $report['to'] . $cashierQsAmp;
?>
<div class="space-y-6">

    <!-- HEADER -->
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
        <div>
            <h2 class="text-xl font-bold text-white flex items-center gap-2">
                <i class="fas fa-chart-line text-amber-400"></i> Stock &amp; Inventory Reports
                <?php if ($cashierName): ?>
                    <span class="text-sm font-medium px-2 py-0.5 rounded-lg" style="background:rgba(245,158,11,0.15);color:#fcd34d">
                        <i class="fas fa-store text-xs mr-1"></i><?php echo htmlspecialchars($cashierName); ?>
                    </span>
                <?php elseif (!$ctx['cashier_id']): ?>
                    <span class="text-sm font-medium px-2 py-0.5 rounded-lg" style="background:rgba(100,116,139,0.2);color:#94a3b8">All Branches</span>
                <?php endif; ?>
            </h2>
            <p class="text-xs text-slate-500 mt-0.5">Analyze purchases, usage, and waste patterns</p>
        </div>
        <div class="flex items-center gap-2 flex-wrap">
            <?php if ($ctx['is_admin'] && !empty($cashiers)): ?>
            <form method="GET" action="<?php echo $baseUrl; ?>/reports" class="flex items-center gap-2">
                <input type="hidden" name="range_type" value="<?php echo htmlspecialchars($range_type); ?>">
                <input type="hidden" name="from" value="<?php echo htmlspecialchars($report['from']); ?>">
                <input type="hidden" name="to" value="<?php echo htmlspecialchars($report['to']); ?>">
                <select name="cashier_id" onchange="this.form.submit()"
                        class="text-xs px-3 py-2 rounded-xl text-white outline-none"
                        style="background:rgba(13,33,55,1);border:1px solid rgba(255,255,255,0.12)">
                    <option value="">All Branches</option>
                    <?php foreach($cashiers as $c): ?>
                    <option value="<?php echo $c['id']; ?>" <?php echo $ctx['cashier_id']==$c['id']?'selected':''; ?>>
                        <?php echo htmlspecialchars($c['name']); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </form>
            <?php endif; ?>
            <a href="<?php echo $exportUrl; ?>" target="_blank"
               class="flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-semibold text-white transition hover:opacity-90"
               style="background:linear-gradient(135deg,#10b981,#059669)">
                <i class="fas fa-file-pdf"></i> Export PDF
            </a>
        </div>
    </div>

    <!-- SUB-NAVIGATION BAR (COHESIVE TABS) -->
    <div class="flex items-center gap-2 border-b border-white/5 pb-0.5">
        <a href="<?php echo $baseUrl; ?><?php echo $cashierQs; ?>" 
           class="text-sm font-medium px-4 py-2 text-slate-400 hover:text-white transition">
            <i class="fas fa-box text-xs mr-1.5"></i>Stock Items
        </a>
        <a href="<?php echo $baseUrl; ?>/categories<?php echo $cashierQs; ?>" 
           class="text-sm font-medium px-4 py-2 text-slate-400 hover:text-white transition">
            <i class="fas fa-tags text-xs mr-1.5"></i>Categories
        </a>
        <a href="<?php echo $baseUrl; ?>/suppliers<?php echo $cashierQs; ?>" 
           class="text-sm font-medium px-4 py-2 text-slate-400 hover:text-white transition">
            <i class="fas fa-truck text-xs mr-1.5"></i>Suppliers
        </a>
        <a href="<?php echo $baseUrl; ?>/reports<?php echo $cashierQs; ?>" 
           class="text-sm font-semibold px-4 py-2 text-amber-400 border-b-2 border-amber-500 transition">
            <i class="fas fa-chart-line text-xs mr-1.5"></i>Reports
        </a>
    </div>

    <!-- REPORT FILTERS BAR -->
    <div class="p-4 rounded-2xl flex flex-wrap items-center justify-between gap-4"
         style="background:rgba(255,255,255,0.02);border:1px solid rgba(255,255,255,0.06)">
        <div class="flex items-center gap-1.5 flex-wrap">
            <?php foreach (['daily' => 'Daily', 'weekly' => 'Weekly', 'monthly' => 'Monthly', 'custom' => 'Custom Date'] as $rt => $lbl): ?>
                <a href="<?php echo $baseUrl; ?>/reports?range_type=<?php echo $rt; ?><?php echo $cashierQsAmp; ?>"
                   class="px-3 py-1.5 rounded-lg text-xs font-semibold transition <?php echo $range_type === $rt ? 'bg-amber-500/20 text-amber-300 border border-amber-500/30' : 'bg-white/5 text-slate-400 hover:text-white'; ?>">
                    <?php echo $lbl; ?>
                </a>
            <?php endforeach; ?>
        </div>

        <?php if ($range_type === 'custom'): ?>
        <form method="GET" action="<?php echo $baseUrl; ?>/reports" class="flex items-center gap-2">
            <input type="hidden" name="range_type" value="custom">
            <?php if ($ctx['cashier_id']): ?>
                <input type="hidden" name="cashier_id" value="<?php echo $ctx['cashier_id']; ?>">
            <?php endif; ?>
            <div class="flex items-center gap-1.5">
                <input type="date" name="from" required value="<?php echo htmlspecialchars($report['from']); ?>"
                       class="text-xs px-3 py-2 rounded-xl text-white outline-none"
                       style="background:rgba(13,33,55,1);border:1px solid rgba(255,255,255,0.12)">
                <span class="text-slate-500 text-xs">to</span>
                <input type="date" name="to" required value="<?php echo htmlspecialchars($report['to']); ?>"
                       class="text-xs px-3 py-2 rounded-xl text-white outline-none"
                       style="background:rgba(13,33,55,1);border:1px solid rgba(255,255,255,0.12)">
            </div>
            <button type="submit" class="px-3 py-2 rounded-xl text-xs font-semibold text-white transition hover:opacity-90"
                    style="background:rgba(245,158,11,1)">
                Apply
            </button>
        </form>
        <?php else: ?>
        <div class="text-xs text-slate-400 font-medium">
            Period: <span class="text-white"><?php echo date('M d, Y', strtotime($report['from'])); ?></span> — <span class="text-white"><?php echo date('M d, Y', strtotime($report['to'])); ?></span>
        </div>
        <?php endif; ?>
    </div>

    <!-- STATS CARDS -->
    <div class="grid grid-cols-1 md:grid-cols-3 gap-5">
        <div class="rounded-2xl p-5" style="background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.06)">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-xs text-slate-500 mb-1">Stock Purchased (In)</p>
                    <p class="text-2xl font-bold text-emerald-400"><?php echo $currency; ?> <?php echo number_format($stockInVal, 2); ?></p>
                    <p class="text-[10px] text-slate-400 mt-1"><?php echo $report['kpiCounts']['stock_in']; ?> inbound transactions</p>
                </div>
                <div class="w-12 h-12 rounded-2xl flex items-center justify-center bg-emerald-500/10 text-emerald-400">
                    <i class="fas fa-arrow-down text-lg"></i>
                </div>
            </div>
        </div>
        <div class="rounded-2xl p-5" style="background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.06)">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-xs text-slate-500 mb-1">Stock Usage (Out)</p>
                    <p class="text-2xl font-bold text-blue-400"><?php echo $currency; ?> <?php echo number_format($stockOutVal, 2); ?></p>
                    <p class="text-[10px] text-slate-400 mt-1"><?php echo $report['kpiCounts']['stock_out']; ?> usage logs</p>
                </div>
                <div class="w-12 h-12 rounded-2xl flex items-center justify-center bg-blue-500/10 text-blue-400">
                    <i class="fas fa-arrow-up text-lg"></i>
                </div>
            </div>
        </div>
        <div class="rounded-2xl p-5" style="background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.06)">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-xs text-slate-500 mb-1">Stock Waste / Loss</p>
                    <p class="text-2xl font-bold text-orange-400"><?php echo $currency; ?> <?php echo number_format($wasteVal, 2); ?></p>
                    <p class="text-[10px] text-slate-400 mt-1"><?php echo $report['kpiCounts']['waste']; ?> waste records</p>
                </div>
                <div class="w-12 h-12 rounded-2xl flex items-center justify-center bg-orange-500/10 text-orange-400">
                    <i class="fas fa-trash-restore-alt text-lg"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- BREAKDOWN METERS -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <!-- Category-wise movement -->
        <div class="rounded-2xl p-5 space-y-4" style="background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.06)">
            <h3 class="text-sm font-semibold text-white flex items-center gap-2"><i class="fas fa-tags text-slate-400"></i> Category Valuation</h3>
            <?php if (empty($report['categoryBreakdown'])): ?>
                <p class="text-xs text-slate-500 py-6 text-center">No movements recorded in this period.</p>
            <?php else: ?>
                <div class="space-y-3 pt-2">
                    <?php 
                    $maxCatVal = 1;
                    foreach ($report['categoryBreakdown'] as $c => $vals) {
                        $sum = array_sum($vals);
                        if ($sum > $maxCatVal) $maxCatVal = $sum;
                    }
                    foreach ($report['categoryBreakdown'] as $cat => $vals):
                        $totalCat = array_sum($vals);
                        $percent = ($totalCat / $maxCatVal) * 100;
                    ?>
                    <div class="space-y-1">
                        <div class="flex justify-between text-xs">
                            <span class="text-slate-300 font-medium"><?php echo htmlspecialchars($cat); ?></span>
                            <span class="text-white font-bold"><?php echo $currency; ?> <?php echo number_format($totalCat, 2); ?></span>
                        </div>
                        <div class="h-2 w-full rounded-full bg-white/5 overflow-hidden flex">
                            <?php if ($vals['stock_in'] > 0): ?>
                                <div style="width: <?php echo ($vals['stock_in'] / $totalCat) * $percent; ?>%" class="bg-emerald-500 h-full"></div>
                            <?php endif; ?>
                            <?php if ($vals['stock_out'] > 0): ?>
                                <div style="width: <?php echo ($vals['stock_out'] / $totalCat) * $percent; ?>%" class="bg-blue-500 h-full"></div>
                            <?php endif; ?>
                            <?php if ($vals['waste'] > 0): ?>
                                <div style="width: <?php echo ($vals['waste'] / $totalCat) * $percent; ?>%" class="bg-orange-500 h-full"></div>
                            <?php endif; ?>
                        </div>
                        <div class="flex items-center gap-3 text-[10px] text-slate-500">
                            <span class="flex items-center gap-1"><span class="w-1.5 h-1.5 rounded-full bg-emerald-500"></span>In: <?php echo number_format($vals['stock_in'],2); ?></span>
                            <span class="flex items-center gap-1"><span class="w-1.5 h-1.5 rounded-full bg-blue-500"></span>Out: <?php echo number_format($vals['stock_out'],2); ?></span>
                            <span class="flex items-center gap-1"><span class="w-1.5 h-1.5 rounded-full bg-orange-500"></span>Waste: <?php echo number_format($vals['waste'],2); ?></span>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>

        <!-- Supplier purchases -->
        <div class="rounded-2xl p-5 space-y-4" style="background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.06)">
            <h3 class="text-sm font-semibold text-white flex items-center gap-2"><i class="fas fa-truck text-slate-400"></i> Purchases by Supplier</h3>
            <?php if (empty($report['supplierPurchases'])): ?>
                <p class="text-xs text-slate-500 py-6 text-center">No purchases recorded in this period.</p>
            <?php else: ?>
                <div class="space-y-4 pt-2">
                    <?php 
                    $maxSupVal = max(1, (float)($report['supplierPurchases'][0]['total_value'] ?? 1));
                    foreach ($report['supplierPurchases'] as $sup):
                        $val = (float)$sup['total_value'];
                        $percent = ($val / $maxSupVal) * 100;
                    ?>
                    <div class="space-y-1">
                        <div class="flex justify-between text-xs">
                            <span class="text-slate-300 font-medium"><?php echo htmlspecialchars($sup['supplier_name']); ?></span>
                            <span class="text-white font-bold"><?php echo $currency; ?> <?php echo number_format($val, 2); ?></span>
                        </div>
                        <div class="h-2 w-full rounded-full bg-white/5 overflow-hidden">
                            <div style="width: <?php echo $percent; ?>%" class="bg-amber-500 h-full rounded-full"></div>
                        </div>
                        <div class="flex justify-between text-[10px] text-slate-500">
                            <span>Qty purchased: <?php echo number_format($sup['total_qty'], 2); ?></span>
                            <span><?php echo $sup['purchases_count']; ?> deliveries</span>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- DETAILED MOVEMENTS TABLE -->
    <div class="rounded-2xl overflow-hidden" style="background:rgba(255,255,255,0.04);border:1px solid rgba(255,255,255,0.07)">
        <div class="px-5 py-4 border-b border-white/5">
            <h3 class="text-sm font-semibold text-white">Movement Ledger</h3>
            <p class="text-xs text-slate-500 mt-0.5">Showing all stock logs within selected dates</p>
        </div>
        <?php if (empty($report['logs'])): ?>
            <div class="p-8 text-center text-slate-500 text-xs">
                No ledger records found for this range.
            </div>
        <?php else: ?>
            <div class="overflow-x-auto">
                <table class="w-full text-left text-xs border-collapse">
                    <thead>
                        <tr class="text-slate-400 border-b border-white/5" style="background:rgba(255,255,255,0.01)">
                            <th class="p-3">Date / Time</th>
                            <th class="p-3">Item</th>
                            <th class="p-3">Type</th>
                            <th class="p-3">Movement</th>
                            <th class="p-3">Financial Value</th>
                            <th class="p-3">Supplier / Reference</th>
                            <th class="p-3">Performed By</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-white/5">
                        <?php foreach ($report['logs'] as $l):
                            $val = abs((float)$l['quantity_change']) * ((float)($l['unit_price'] ?? $l['notes'] ? 0 : 0)); // valuation
                            // let's calculate proper transaction financial value
                            $priceUsed = (float)($l['unit_price'] ?? 0);
                            $txnValue = abs((float)$l['quantity_change']) * $priceUsed;

                            $lblColor = '#94a3b8';
                            $lblText = $l['type'];
                            if ($l['type'] === 'stock_in') { $lblColor = '#34d399'; $lblText = 'Stock In'; }
                            elseif ($l['type'] === 'stock_out') { $lblColor = '#60a5fa'; $lblText = 'Stock Out'; }
                            elseif ($l['type'] === 'waste') { $lblColor = '#fb923c'; $lblText = 'Waste'; }
                            elseif ($l['type'] === 'adjustment') { $lblColor = '#c084fc'; $lblText = 'Adjustment'; }
                            elseif ($l['type'] === 'initial') { $lblColor = '#fcd34d'; $lblText = 'Initial Stock'; }
                        ?>
                        <tr class="hover:bg-white/[0.01] transition duration-150">
                            <td class="p-3 text-slate-400 whitespace-nowrap">
                                <?php echo date('Y-m-d H:i', strtotime($l['created_at'])); ?>
                            </td>
                            <td class="p-3 font-semibold text-white">
                                <?php echo htmlspecialchars($l['item_name']); ?>
                            </td>
                            <td class="p-3">
                                <span class="font-bold" style="color: <?php echo $lblColor; ?>"><?php echo $lblText; ?></span>
                            </td>
                            <td class="p-3 whitespace-nowrap">
                                <span class="font-bold <?php echo (float)$l['quantity_change'] >= 0 ? 'text-emerald-400' : 'text-red-400'; ?>">
                                    <?php echo (float)$l['quantity_change'] >= 0 ? '+' : ''; ?><?php echo rtrim(rtrim(number_format($l['quantity_change'], 2), '0'), '.'); ?>
                                </span>
                                <span class="text-slate-500 text-[10px]"><?php echo htmlspecialchars($l['item_unit']); ?></span>
                            </td>
                            <td class="p-3 font-medium">
                                <?php if ($txnValue > 0): ?>
                                    <span class="text-white"><?php echo $currency; ?> <?php echo number_format($txnValue, 2); ?></span>
                                    <?php if ($l['unit_price']): ?>
                                        <span class="text-[10px] text-slate-500 block">@ <?php echo $currency; ?><?php echo number_format($l['unit_price'],2); ?></span>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <span class="text-slate-500">—</span>
                                <?php endif; ?>
                            </td>
                            <td class="p-3 text-slate-300">
                                <div class="flex flex-col gap-0.5">
                                    <?php if ($l['supplier_name']): ?>
                                        <span><i class="fas fa-truck text-[9px] text-slate-500 mr-1"></i><?php echo htmlspecialchars($l['supplier_name']); ?></span>
                                    <?php endif; ?>
                                    <?php if ($l['reference']): ?>
                                        <span class="text-[10px] text-blue-400">Ref: <?php echo htmlspecialchars($l['reference']); ?></span>
                                    <?php endif; ?>
                                    <?php if ($l['notes'] && !$l['supplier_name'] && !$l['reference']): ?>
                                        <span class="text-[10px] text-slate-400 italic"><?php echo htmlspecialchars($l['notes']); ?></span>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td class="p-3 text-slate-400">
                                <?php echo htmlspecialchars($l['user_name'] ?? 'System'); ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>

</div>
