<?php
/**
 * ============================================================================
 * marketplace/my-products.php - Enhanced Manage My Products
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

requireLogin();

// Only farmers can list products
if (getUserType() !== 'farmer') {
    redirect('/marketplace/', 'Only farmers can manage products', 'error');
}

$pageTitle = 'My Products';
$userId = getUserId();

// Initialize database
$database = new Database();
$db = $database->getConnection();
$productClass = new \App\Product($db);

// Get status filter
$statusFilter = $_GET['status'] ?? 'all';

// Get user's products
$products = $productClass->getBySeller($userId);

// Filter by status if needed
if ($statusFilter !== 'all') {
    $products = array_filter($products, function($p) use ($statusFilter) {
        return $p['status'] === $statusFilter;
    });
}

// Count by status
$statusCounts = [
    'all' => count($productClass->getBySeller($userId)),
    'available' => 0,
    'sold' => 0,
    'reserved' => 0,
    'expired' => 0
];

foreach ($productClass->getBySeller($userId) as $p) {
    if (isset($statusCounts[$p['status']])) {
        $statusCounts[$p['status']]++;
    }
}

// Calculate total value
$totalValue = 0;
$totalProducts = 0;
foreach ($products as $p) {
    if ($p['status'] === 'available') {
        $totalValue += ($p['price_per_unit'] * $p['quantity']);
        $totalProducts += $p['quantity'];
    }
}

global $PRODUCT_CATEGORIES;

include_once __DIR__ . '/../includes/meta.php';
include_once __DIR__ . '/../includes/header.php';
?>

<div class="container-fluid py-4">
    <!-- Header -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card border-0 shadow-sm bg-gradient-primary text-white">
                <div class="card-body py-4">
                    <div class="row align-items-center">
                        <div class="col-md-8">
                            <h2 class="mb-2">
                                <i class="bi bi-box-seam"></i> My Products
                            </h2>
                            <p class="mb-0 opacity-75">Manage and track your product listings</p>
                        </div>
                        <div class="col-md-4 text-md-end mt-3 mt-md-0">
                            <a href="<?php echo APP_URL; ?>/marketplace/add-product.php" 
                               class="btn btn-light btn-lg">
                                <i class="bi bi-plus-circle"></i> Add New Product
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Stats Cards -->
    <div class="row mb-4">
        <div class="col-md-3 mb-3">
            <div class="card border-0 shadow-sm">
                <div class="card-body">
                    <div class="d-flex align-items-center">
                        <div class="flex-shrink-0">
                            <div class="rounded-circle bg-primary bg-opacity-10 p-3">
                                <i class="bi bi-box-seam text-primary fs-3"></i>
                            </div>
                        </div>
                        <div class="flex-grow-1 ms-3">
                            <div class="text-muted small">Total Products</div>
                            <h3 class="mb-0"><?php echo $statusCounts['all']; ?></h3>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-3 mb-3">
            <div class="card border-0 shadow-sm">
                <div class="card-body">
                    <div class="d-flex align-items-center">
                        <div class="flex-shrink-0">
                            <div class="rounded-circle bg-success bg-opacity-10 p-3">
                                <i class="bi bi-check-circle text-success fs-3"></i>
                            </div>
                        </div>
                        <div class="flex-grow-1 ms-3">
                            <div class="text-muted small">Available</div>
                            <h3 class="mb-0"><?php echo $statusCounts['available']; ?></h3>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-3 mb-3">
            <div class="card border-0 shadow-sm">
                <div class="card-body">
                    <div class="d-flex align-items-center">
                        <div class="flex-shrink-0">
                            <div class="rounded-circle bg-warning bg-opacity-10 p-3">
                                <i class="bi bi-currency-dollar text-warning fs-3"></i>
                            </div>
                        </div>
                        <div class="flex-grow-1 ms-3">
                            <div class="text-muted small">Total Value</div>
                            <h3 class="mb-0"><?php echo formatCurrency($totalValue); ?></h3>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-3 mb-3">
            <div class="card border-0 shadow-sm">
                <div class="card-body">
                    <div class="d-flex align-items-center">
                        <div class="flex-shrink-0">
                            <div class="rounded-circle bg-info bg-opacity-10 p-3">
                                <i class="bi bi-graph-up text-info fs-3"></i>
                            </div>
                        </div>
                        <div class="flex-grow-1 ms-3">
                            <div class="text-muted small">Sold</div>
                            <h3 class="mb-0"><?php echo $statusCounts['sold']; ?></h3>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Status Filter Tabs -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-body p-3">
                    <ul class="nav nav-pills flex-nowrap overflow-auto">
                        <li class="nav-item">
                            <a class="nav-link <?php echo $statusFilter === 'all' ? 'active' : ''; ?>" 
                               href="?status=all">
                                <i class="bi bi-grid"></i> All 
                                <span class="badge bg-secondary ms-1"><?php echo $statusCounts['all']; ?></span>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link <?php echo $statusFilter === 'available' ? 'active' : ''; ?>" 
                               href="?status=available">
                                <i class="bi bi-check-circle"></i> Available 
                                <span class="badge bg-success ms-1"><?php echo $statusCounts['available']; ?></span>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link <?php echo $statusFilter === 'sold' ? 'active' : ''; ?>" 
                               href="?status=sold">
                                <i class="bi bi-currency-dollar"></i> Sold 
                                <span class="badge bg-secondary ms-1"><?php echo $statusCounts['sold']; ?></span>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link <?php echo $statusFilter === 'reserved' ? 'active' : ''; ?>" 
                               href="?status=reserved">
                                <i class="bi bi-bookmark"></i> Reserved 
                                <span class="badge bg-warning ms-1"><?php echo $statusCounts['reserved']; ?></span>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link <?php echo $statusFilter === 'expired' ? 'active' : ''; ?>" 
                               href="?status=expired">
                                <i class="bi bi-x-circle"></i> Expired 
                                <span class="badge bg-danger ms-1"><?php echo $statusCounts['expired']; ?></span>
                            </a>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <!-- Products List -->
    <div class="row">
        <?php if (!empty($products)): ?>
            <?php foreach ($products as $product): ?>
                <div class="col-md-6 col-xl-4 mb-4">
                    <div class="card h-100 border-0 shadow-sm hover-lift">
                        <!-- Product Image -->
                        <div class="position-relative product-image-container">
                            <?php 
                            $firstImage = !empty($product['images']) && is_array($product['images']) 
                                ? $product['images'][0] 
                                : null; 
                            ?>
                            
                            <a href="<?php echo APP_URL; ?>/marketplace/product-details.php?id=<?php echo $product['id']; ?>">
                                <?php if ($firstImage): ?>
                                    <img src="<?php echo APP_URL . '/' . htmlspecialchars($firstImage); ?>" 
                                         class="card-img-top product-image" 
                                         alt="<?php echo htmlspecialchars($product['product_name']); ?>"
                                         onerror="this.src='<?php echo APP_URL; ?>/assets/images/no-image.png'">
                                <?php else: ?>
                                    <div class="bg-light d-flex align-items-center justify-content-center product-image-placeholder">
                                        <i class="bi bi-image text-muted" style="font-size: 3rem;"></i>
                                    </div>
                                <?php endif; ?>
                            </a>
                            
                            <!-- Status Badge -->
                            <span class="position-absolute top-0 end-0 m-2 badge bg-<?php echo getStatusBadgeClass($product['status']); ?>">
                                <?php echo ucfirst($product['status']); ?>
                            </span>

                            <!-- Image Count Badge -->
                            <?php if (!empty($product['images']) && count($product['images']) > 1): ?>
                            <span class="position-absolute top-0 start-0 m-2 badge bg-dark bg-opacity-75">
                                <i class="bi bi-images"></i> <?php echo count($product['images']); ?>
                            </span>
                            <?php endif; ?>

                            <!-- Category Badge -->
                            <span class="position-absolute bottom-0 start-0 m-2 badge" 
                                  style="background-color: <?php echo getCategoryColor($product['category']); ?>">
                                <?php echo $PRODUCT_CATEGORIES[$product['category']]['icon'] ?? ''; ?>
                                <?php echo $PRODUCT_CATEGORIES[$product['category']]['name'] ?? $product['category']; ?>
                            </span>
                        </div>

                        <div class="card-body">
                            <h5 class="card-title mb-2">
                                <a href="<?php echo APP_URL; ?>/marketplace/product-details.php?id=<?php echo $product['id']; ?>"
                                   class="text-decoration-none text-dark">
                                    <?php echo htmlspecialchars($product['product_name']); ?>
                                </a>
                            </h5>
                            
                            <p class="card-text text-muted small mb-3">
                                <?php echo truncate($product['description'], 80); ?>
                            </p>
                            
                            <!-- Price & Quantity -->
                            <div class="mb-2">
                                <h4 class="text-success mb-1">
                                    <?php echo formatCurrency($product['price_per_unit']); ?>
                                    <small class="text-muted fs-6">/ <?php echo htmlspecialchars($product['unit']); ?></small>
                                </h4>
                                <div class="small text-muted">
                                    Total Value: <strong><?php echo formatCurrency($product['price_per_unit'] * $product['quantity']); ?></strong>
                                </div>
                            </div>
                            
                            <!-- Stats Row -->
                            <div class="row g-2 mb-3 text-center small">
                                <div class="col-4">
                                    <div class="bg-light rounded p-2">
                                        <i class="bi bi-box text-primary"></i>
                                        <div class="fw-semibold"><?php echo number_format($product['quantity'], 1); ?></div>
                                        <div class="text-muted" style="font-size: 0.75rem;"><?php echo htmlspecialchars($product['unit']); ?></div>
                                    </div>
                                </div>
                                <div class="col-4">
                                    <div class="bg-light rounded p-2">
                                        <i class="bi bi-eye text-info"></i>
                                        <div class="fw-semibold"><?php echo number_format($product['views']); ?></div>
                                        <div class="text-muted" style="font-size: 0.75rem;">Views</div>
                                    </div>
                                </div>
                                <div class="col-4">
                                    <div class="bg-light rounded p-2">
                                        <i class="bi bi-calendar text-success"></i>
                                        <div class="fw-semibold small"><?php echo formatDate($product['created_at'], 'd M'); ?></div>
                                        <div class="text-muted" style="font-size: 0.75rem;">Listed</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="card-footer bg-transparent border-top">
                            <div class="d-flex gap-2">
                                <a href="<?php echo APP_URL; ?>/marketplace/product-details.php?id=<?php echo $product['id']; ?>" 
                                   class="btn btn-sm btn-outline-primary flex-fill">
                                    <i class="bi bi-eye"></i> View
                                </a>
                                <a href="<?php echo APP_URL; ?>/marketplace/edit-product.php?id=<?php echo $product['id']; ?>" 
                                   class="btn btn-sm btn-primary flex-fill">
                                    <i class="bi bi-pencil"></i> Edit
                                </a>
                                <div class="dropdown">
                                    <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" 
                                            data-bs-toggle="dropdown">
                                        <i class="bi bi-three-dots-vertical"></i>
                                    </button>
                                    <ul class="dropdown-menu dropdown-menu-end">
                                        <li>
                                            <h6 class="dropdown-header">Change Status</h6>
                                        </li>
                                        <li>
                                            <a class="dropdown-item" href="#" 
                                               onclick="changeStatus(<?php echo $product['id']; ?>, 'available'); return false;">
                                                <i class="bi bi-check-circle text-success"></i> Available
                                            </a>
                                        </li>
                                        <li>
                                            <a class="dropdown-item" href="#" 
                                               onclick="changeStatus(<?php echo $product['id']; ?>, 'reserved'); return false;">
                                                <i class="bi bi-bookmark text-warning"></i> Reserved
                                            </a>
                                        </li>
                                        <li>
                                            <a class="dropdown-item" href="#" 
                                               onclick="changeStatus(<?php echo $product['id']; ?>, 'sold'); return false;">
                                                <i class="bi bi-currency-dollar text-info"></i> Sold
                                            </a>
                                        </li>
                                        <li><hr class="dropdown-divider"></li>
                                        <li>
                                            <a class="dropdown-item text-danger" href="#" 
                                               onclick="deleteProduct(<?php echo $product['id']; ?>); return false;">
                                                <i class="bi bi-trash"></i> Delete
                                            </a>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php else: ?>
            <div class="col-12">
                <div class="card border-0 shadow-sm">
                    <div class="card-body text-center py-5">
                        <i class="bi bi-inbox text-muted" style="font-size: 4rem;"></i>
                        <h4 class="mt-3">No Products Found</h4>
                        <p class="text-muted">
                            <?php if ($statusFilter !== 'all'): ?>
                                You don't have any <?php echo $statusFilter; ?> products yet
                            <?php else: ?>
                                You haven't listed any products yet
                            <?php endif; ?>
                        </p>
                        <a href="<?php echo APP_URL; ?>/marketplace/add-product.php" 
                           class="btn btn-success mt-2">
                            <i class="bi bi-plus-circle"></i> List Your First Product
                        </a>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<style>
.bg-gradient-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.hover-lift {
    transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.hover-lift:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 25px rgba(0,0,0,0.15) !important;
}

.product-image-container {
    height: 200px;
    overflow: hidden;
    background: #f8f9fa;
    position: relative;
}

.product-image {
    width: 100%;
    height: 200px;
    object-fit: cover;
    transition: transform 0.3s ease;
}

.product-image-placeholder {
    height: 200px;
}

.hover-lift:hover .product-image {
    transform: scale(1.05);
}
</style>

<script>
// Change product status
function changeStatus(productId, newStatus) {
    const statusText = newStatus.charAt(0).toUpperCase() + newStatus.slice(1);
    
    confirmAction(
        'Change Status',
        `Mark this product as ${statusText}?`,
        function() {
            showLoading();
            fetch(APP_URL + '/ajax/update-product-status.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({
                    product_id: productId,
                    status: newStatus
                })
            })
            .then(response => response.json())
            .then(data => {
                hideLoading();
                if (data.success) {
                    showToast(data.message, 'success');
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showToast(data.message, 'error');
                }
            })
            .catch(error => {
                hideLoading();
                showToast('Connection error', 'error');
            });
        }
    );
}

// Delete product
function deleteProduct(productId) {
    confirmAction(
        'Delete Product',
        'Are you sure? This action cannot be undone and will permanently remove all product data and images.',
        function() {
            showLoading();
            fetch(APP_URL + '/ajax/delete-product.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({
                    product_id: productId
                })
            })
            .then(response => response.json())
            .then(data => {
                hideLoading();
                if (data.success) {
                    showToast(data.message, 'success');
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showToast(data.message, 'error');
                }
            })
            .catch(error => {
                hideLoading();
                showToast('Connection error', 'error');
            });
        }
    );
}
</script>

<?php
include_once __DIR__ . '/../includes/footer.php';
include_once __DIR__ . '/../includes/bottom-nav.php';
?>