<?php
require_once __DIR__ . '/includes/base.php';

$breadcrumbs = [['title' => 'Products', 'url' => '']];

// Fetch products
try {
    $sql = "SELECT p.*, u.full_name as seller_name, u.phone_number as seller_phone,
            d.district_name, s.subcounty_name
            FROM products p
            JOIN users u ON p.seller_id = u.id
            LEFT JOIN districts d ON u.district_id = d.id
            LEFT JOIN subcounties s ON u.subcounty_id = s.id
            ORDER BY p.created_at DESC";
    
    $stmt = $db->query($sql);
    $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $stats = [
        'total' => count($products),
        'available' => count(array_filter($products, fn($p) => $p['status'] === 'available')),
        'sold' => count(array_filter($products, fn($p) => $p['status'] === 'sold')),
        'reserved' => count(array_filter($products, fn($p) => $p['status'] === 'reserved'))
    ];
    
} catch (PDOException $e) {
    $products = [];
    $stats = ['total' => 0, 'available' => 0, 'sold' => 0, 'reserved' => 0];
}

renderAdminHeader('Products', $breadcrumbs);
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-1 fw-bold">Marketplace Products</h2>
        <p class="text-muted mb-0">Moderate and manage product listings</p>
    </div>
</div>

<!-- Stats -->
<div class="row mb-4">
    <div class="col-md-3 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body text-center">
                <h4 class="text-primary mb-0"><?php echo $stats['total']; ?></h4>
                <small class="text-muted">Total Products</small>
            </div>
        </div>
    </div>
    <div class="col-md-3 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body text-center">
                <h4 class="text-success mb-0"><?php echo $stats['available']; ?></h4>
                <small class="text-muted">Available</small>
            </div>
        </div>
    </div>
    <div class="col-md-3 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body text-center">
                <h4 class="text-info mb-0"><?php echo $stats['reserved']; ?></h4>
                <small class="text-muted">Reserved</small>
            </div>
        </div>
    </div>
    <div class="col-md-3 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body text-center">
                <h4 class="text-warning mb-0"><?php echo $stats['sold']; ?></h4>
                <small class="text-muted">Sold</small>
            </div>
        </div>
    </div>
</div>

<!-- Products Table -->
<div class="card shadow-sm border-0">
    <div class="card-header bg-white py-3">
        <h5 class="mb-0 fw-bold"><i class="bi bi-box-seam me-2"></i>All Products</h5>
    </div>
    <div class="card-body p-0">
        <table class="table table-hover mb-0" id="productsTable">
            <thead class="table-light">
                <tr>
                    <th>Product</th>
                    <th>Seller</th>
                    <th>Category</th>
                    <th>Quantity</th>
                    <th>Price/Unit</th>
                    <th>Location</th>
                    <th>Views</th>
                    <th>Status</th>
                    <th>Posted</th>
                    <th class="text-end">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($products as $product): ?>
                <tr>
                    <td class="fw-semibold"><?php echo htmlspecialchars($product['product_name']); ?></td>
                    <td>
                        <small>
                            <?php echo htmlspecialchars($product['seller_name']); ?><br>
                            <span class="text-muted"><?php echo htmlspecialchars($product['seller_phone']); ?></span>
                        </small>
                    </td>
                    <td><span class="badge bg-success"><?php echo ucfirst($product['category']); ?></span></td>
                    <td><?php echo $product['quantity']; ?> <?php echo $product['unit']; ?></td>
                    <td><strong class="text-success">UGX <?php echo number_format($product['price_per_unit']); ?></strong></td>
                    <td><small><?php echo htmlspecialchars($product['district_name'] ?? 'N/A'); ?></small></td>
                    <td><span class="badge bg-info"><?php echo $product['views']; ?></span></td>
                    <td>
                        <span class="badge bg-<?php 
                            echo $product['status'] === 'available' ? 'success' : 
                                ($product['status'] === 'sold' ? 'warning' : 'secondary'); 
                        ?>">
                            <?php echo ucfirst($product['status']); ?>
                        </span>
                    </td>
                    <td><small class="text-muted"><?php echo date('M d', strtotime($product['created_at'])); ?></small></td>
                    <td class="text-end">
                        <div class="btn-group btn-group-sm">
                            <button class="btn btn-outline-info" onclick="viewProduct(<?php echo $product['id']; ?>)">
                                <i class="bi bi-eye"></i>
                            </button>
                            <button class="btn btn-outline-danger" onclick="deleteProduct(<?php echo $product['id']; ?>)">
                                <i class="bi bi-trash"></i>
                            </button>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
$(document).ready(function() {
    $('#productsTable').DataTable({
        pageLength: 25,
        order: [[8, 'desc']]
    });
});

function viewProduct(id) {
    window.open(APP_URL + '/products/view.php?id=' + id, '_blank');
}

function deleteProduct(id) {
    Swal.fire({
        title: 'Delete Product?',
        text: 'This will permanently remove the product listing',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#ef4444',
        confirmButtonText: 'Yes, delete'
    }).then((result) => {
        if (result.isConfirmed) {
            $.post(APP_URL + '/api/admin.php', {action: 'delete_product', id: id})
            .done(function(r) {
                if (r.success) {
                    showToast(r.message, 'success');
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showToast(r.message, 'error');
                }
            });
        }
    });
}
</script>

<?php renderAdminFooter(); ?>