<?php
require_once 'require_login.php';
if (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] != 1) {
    header("Location: index.php");
    exit();
}

require_once 'db.php';

// Fetch all products
$stmt = $conn->prepare("SELECT * FROM products ORDER BY name ASC");
$stmt->execute();
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Summary Cards Calculations (unchanged)
$totalProducts = count($products);
$totalSold = array_sum(array_column($products, 'sold_quantity'));
$totalInStock = array_sum(array_column($products, 'stock'));
$outOfStock = count(array_filter($products, fn($p) => $p['stock'] == 0));

$topSellingQty = !empty($products) ? max(array_column($products, 'sold_quantity')) : 0;
$slowSellingQty = !empty($products) ? min(array_column($products, 'sold_quantity')) : 0;

$topSellingProducts = array_filter($products, fn($p) => $p['sold_quantity'] == $topSellingQty && $p['sold_quantity'] > 0);
$slowSellingProducts = array_filter($products, fn($p) => $p['sold_quantity'] == $slowSellingQty && $p['sold_quantity'] > 0);
$zeroSalesProducts = array_filter($products, fn($p) => $p['sold_quantity'] == 0);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Stock Overview - Admin</title>
<link rel="stylesheet" href="admin-sidebar.css">
<style>
body { font-family:'Segoe UI',sans-serif; background:#111; color:#fff; margin:0; }
header { display:flex; justify-content:space-between; align-items:center; padding:15px 30px; background:rgba(20,20,20,0.95); box-shadow:0 4px 15px rgba(0,0,0,0.6); position:sticky; top:0; z-index:1100; }
.dashboard-wrapper { display:flex; min-height:100vh; }
.admin-sidebar { width:250px; background:#222; flex-shrink:0; padding-top:20px; z-index:1001; }

/* Main Content */
.main-content { flex:1; padding:20px; margin-left:250px; }

/* Summary cards */
.card-container { display:flex; gap:15px; flex-wrap:wrap; margin-bottom:20px; }
.card { background:#222; width:180px; height:120px; padding:15px; border-radius:10px; text-align:center; display:flex; flex-direction:column; justify-content:center; align-items:center; }
.card h3 { margin:0 0 10px 0; font-size:16px; }
.card p { margin:0; font-size:18px; font-weight:bold; }
.view-all-btn { background:#28a745; color:#fff; margin-top:10px; display:block; border:none; padding:6px 12px; border-radius:4px; cursor:pointer; transition:0.3s; }
.view-all-btn:hover { opacity:0.85; }

/* Table */
table { width:100%; border-collapse:collapse; margin-top:20px; }
th, td { padding:12px; text-align:left; border-bottom:1px solid #333; font-size:14px; vertical-align: middle; }
th { background:#222; }
tr:hover { background:#222; cursor:pointer; }
button { background:#28a745; color:#fff; border:none; padding:6px 12px; border-radius:4px; cursor:pointer; transition:0.3s; }
button:hover { opacity:0.85; }

/* Search/filter inputs */
input, select { padding:8px; margin:5px 0; border-radius:6px; border:none; background:#222; color:#fff; width:200px; }

/* Product modal */
.modal { display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.8); justify-content:center; align-items:center; z-index:1050; overflow:auto; }
.modal-content { background:#111; padding:20px; border-radius:8px; width:90%; max-width:700px; color:#fff; position:relative; display:flex; gap:20px; flex-wrap:wrap; }
.modal-close { position:absolute; top:10px; right:15px; font-size:18px; cursor:pointer; color:#fff; }
.modal img { width:45%; max-width:250px; border-radius:8px; object-fit:cover; }
.modal-details { flex:1; min-width:200px; }
.modal-details label { font-weight:bold; display:block; margin-top:10px; }
.modal-details p { margin:5px 0; }

/* Product image column */
td img.product-img { width:50px; height:50px; object-fit:cover; border-radius:4px; }

/* Mobile responsive */
@media(max-width:768px) {
    .admin-sidebar { position:fixed; top:0; left:-250px; height:100%; z-index:1001; transition: left 0.3s ease; }
    .admin-sidebar.active { left:0; }
    .sidebar-overlay { display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:1000; }
    .sidebar-overlay.active { display:block; }
    #sidebarToggle { position:fixed; top:15px; left:15px; background:#28a745; border:none; padding:10px 12px; cursor:pointer; border-radius:4px; z-index:1002; }
}
</style>
</head>
<body>

<?php include 'navbar.php'; ?>
<div class="sidebar-overlay" id="sidebarOverlay"></div>
<button id="sidebarToggle">&#9776;</button>

<div class="dashboard-wrapper">
    <?php include 'admin-sidebar.php'; ?>
    <div class="main-content">
        <h1>Stock Overview</h1>

        <!-- Summary Cards -->
        <div class="card-container">
            <div class="card"><h3>Total Products</h3><p id="totalProducts"><?= $totalProducts ?></p></div>
            <div class="card"><h3>Total Sold</h3><p><?= $totalSold ?></p></div>
            <div class="card"><h3>In Stock</h3><p id="totalInStock"><?= $totalInStock ?></p><button class="view-all-btn" data-type="instock">View All</button></div>
            <div class="card"><h3>Out-of-stock</h3><p id="outOfStock"><?= $outOfStock ?></p><button class="view-all-btn" data-type="outofstock">View All</button></div>
        </div>

        <!-- Top / Slow / Zero Sales Cards -->
        <div class="card-container">
            <div class="card"><h3>Top Selling</h3><p><?= !empty($topSellingProducts) ? htmlspecialchars(array_values($topSellingProducts)[0]['name']) : "No sales yet" ?></p><?php if(!empty($topSellingProducts)): ?><button class="view-all-btn" data-type="top">View All</button><?php endif; ?></div>
            <div class="card"><h3>Slow Selling</h3><p><?= !empty($slowSellingProducts) ? htmlspecialchars(array_values($slowSellingProducts)[0]['name']) : "No sales yet" ?></p><?php if(!empty($slowSellingProducts)): ?><button class="view-all-btn" data-type="slow">View All</button><?php endif; ?></div>
            <div class="card"><h3>No Sell At All</h3><p><?= count($zeroSalesProducts) ?></p><?php if(!empty($zeroSalesProducts)): ?><button class="view-all-btn" data-type="zero">View All</button><?php endif; ?></div>
        </div>

        <!-- Search & Table -->
        <div>
            <input type="text" id="searchInput" placeholder="Search by name or slug">
            <select id="filterSelect">
                <option value="">All</option>
                <?php foreach(array_unique(array_column($products,'slug')) as $slug): ?>
                    <option value="<?= htmlspecialchars($slug) ?>"><?= htmlspecialchars($slug) ?></option>
                <?php endforeach; ?>
            </select>
        </div>

        <table id="productTable">
            <thead>
                <tr>
                    <th>Image</th>
                    <th>Name</th>
                    <th>Slug</th>
                    <th>Remaining Stock</th>
                    <th>Sold Quantity</th>
                    <th>Price</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($products as $p): ?>
                <tr data-id="<?= $p['id'] ?>"
                    data-name="<?= htmlspecialchars($p['name']) ?>"
                    data-slug="<?= htmlspecialchars($p['slug']) ?>"
                    data-price="<?= $p['price'] ?>"
                    data-stock="<?= $p['stock'] ?>"
                    data-sold="<?= $p['sold_quantity'] ?>"
                    data-description="<?= htmlspecialchars($p['description']) ?>"
                    data-image="<?= !empty($p['image']) ? 'uploads/' . htmlspecialchars($p['image']) : '' ?>"
                >
                    <td><?= !empty($p['image']) ? '<img src="uploads/'.htmlspecialchars($p['image']).'" class="product-img">' : '-' ?></td>
                    <td><?= htmlspecialchars($p['name']) ?></td>
                    <td><?= htmlspecialchars($p['slug']) ?></td>
                    <td><?= $p['stock'] ?></td>
                    <td><?= $p['sold_quantity'] ?></td>
                    <td><?= number_format($p['price'],2) ?></td>
                    <td><button class="view-btn">View</button></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

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

<!-- Product Modal -->
<div class="modal" id="productModal">
    <div class="modal-content">
        <span class="modal-close">&times;</span>
        <img id="modalImage" src="" alt="Product Image">
        <div class="modal-details">
            <h2 id="modalName"></h2>
            <p><strong>Slug:</strong> <span id="modalSlug"></span></p>
            <p><strong>Remaining Stock:</strong> <span id="modalStock"></span></p>
            <p><strong>Sold Quantity:</strong> <span id="modalSold"></span></p>
            <p><strong>Total Revenue:</strong> $<span id="modalRevenue"></span></p>
            <label>Description:</label>
            <p id="modalDescription"></p>
        </div>
    </div>
</div>

<!-- View All Modal -->
<div class="modal" id="viewAllModal">
    <div class="modal-content">
        <span class="modal-close">&times;</span>
        <h2 id="viewAllTitle"></h2>
        <ul id="viewAllList"></ul>
    </div>
</div>

<script>
const productModal = document.getElementById('productModal');
const viewAllModal = document.getElementById('viewAllModal');
const modalCloseBtns = document.querySelectorAll('.modal-close');

// Close modal
modalCloseBtns.forEach(btn => btn.addEventListener('click', () => {
    btn.closest('.modal').style.display = 'none';
}));

// View single product
document.querySelectorAll('.view-btn').forEach(btn => {
    btn.addEventListener('click', e => {
        const tr = e.target.closest('tr');
        document.getElementById('modalName').textContent = tr.dataset.name;
        document.getElementById('modalSlug').textContent = tr.dataset.slug;
        document.getElementById('modalStock').textContent = tr.dataset.stock;
        document.getElementById('modalSold').textContent = tr.dataset.sold;
        document.getElementById('modalRevenue').textContent = (tr.dataset.price * tr.dataset.sold).toFixed(2);
        document.getElementById('modalDescription').textContent = tr.dataset.description;
        document.getElementById('modalImage').src = tr.dataset.image || '';
        productModal.style.display = 'flex';
    });
});

// View all modal
document.querySelectorAll('.view-all-btn').forEach(btn => {
    btn.addEventListener('click', () => {
        const type = btn.dataset.type;
        const products = <?= json_encode($products) ?>;
        let items = [];
        let modalTitle = '';
        if(type === 'top') { items = products.filter(p=>p.sold_quantity>0).sort((a,b)=>b.sold_quantity - a.sold_quantity).slice(0,5); modalTitle="Top Selling Products"; }
        if(type === 'slow') { items = products.filter(p=>p.sold_quantity>0).sort((a,b)=>a.sold_quantity - b.sold_quantity).slice(0,5); modalTitle="Slow Selling Products"; }
        if(type === 'zero') { items = products.filter(p=>p.sold_quantity==0); modalTitle="Products Never Sold"; }
        if(type === 'instock') { items = products.filter(p=>p.stock>0); modalTitle="In Stock Products"; }
        if(type === 'outofstock') { items = products.filter(p=>p.stock==0); modalTitle="Out of Stock Products"; }

        document.getElementById('viewAllTitle').textContent = modalTitle;
        document.getElementById('viewAllList').innerHTML = items.length>0 ? items.map(p=>`<li>${p.name}</li>`).join('') : '<li>No products to display</li>';
        viewAllModal.style.display = 'flex';
    });
});

// Close modal when clicking outside content
window.addEventListener('click', e => {
    if(e.target.classList.contains('modal')) e.target.style.display='none';
});

// Live stock update (unchanged)
function updateStockCards() {
    fetch('get_stock_counts.php')
    .then(res => res.json())
    .then(data => {
        document.getElementById('totalInStock').textContent = data.totalInStock;
        document.getElementById('outOfStock').textContent = data.outOfStock;
        document.getElementById('totalProducts').textContent = data.totalProducts;
    });
}
setInterval(updateStockCards, 5000);
updateStockCards();
</script>
<script src="admin-sidebar.js"></script>
</body>
</html>
