<?php
session_start();
include_once('../includes/config.php');

// Check if user is logged in
if (!isset($_SESSION['uid'])) {
    header('location:../login.php');
    exit();
}

$userId = $_SESSION['uid'];
$message = '';

// Handle form submission for updating item status only (we don't add/edit items here as they're managed in the items module)
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['action'])) {
        if ($_POST['action'] == 'toggle_status') {
            $id = intval($_POST['id']);
            $currentStatus = mysqli_real_escape_string($con, $_POST['current_status']);
            $newStatus = ($currentStatus == 'Active') ? 'Inactive' : 'Active';
            
            $sql = "UPDATE tblitems SET Status = '$newStatus' WHERE ID = $id";
            if (mysqli_query($con, $sql)) {
                $success = "Item status updated successfully!";
            } else {
                $error = "Error: " . mysqli_error($con);
            }
        }
    }
}

// Get all items with their related information
$itemsQuery = "
    SELECT 
        i.*,
        b.BrandName,
        c.CategoryName,
        u.UnitName,
        s.SupplierName,
        l.LocationName,
        r.RackName
    FROM tblitems i
    LEFT JOIN tblbrands b ON i.BrandID = b.ID
    LEFT JOIN tblcategories c ON i.CategoryID = c.ID
    LEFT JOIN tblunits u ON i.UnitID = u.ID
    LEFT JOIN tblsuppliers s ON i.SupplierID = s.ID
    LEFT JOIN tbllocations l ON i.LocationID = l.ID
    LEFT JOIN tblracks r ON i.RackID = r.ID
    ORDER BY i.ItemCode
";
$itemsResult = mysqli_query($con, $itemsQuery);
$items = [];
$itemStats = ['total' => 0, 'active' => 0, 'inactive' => 0, 'low_stock' => 0];

if ($itemsResult) {
    while ($item = mysqli_fetch_assoc($itemsResult)) {
        $items[] = $item;
        $itemStats['total']++;
        if ($item['Status'] == 'Active') {
            $itemStats['active']++;
        } else {
            $itemStats['inactive']++;
        }
        
        // Check for low stock
        if ($item['CurrentStock'] <= $item['AlertQuantity']) {
            $itemStats['low_stock']++;
        }
    }
}
?>

<!DOCTYPE html>
<html lang="ta">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Items Overview - Products Management</title>
    
    <link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet">
    <link href="../css/sb-admin-2.min.css" rel="stylesheet">
    <link href="../css/modern-messagebox.css" rel="stylesheet">
    <style>
        /* Compact global paddings */
        .container-fluid {
            padding: 8px 10px;
            background: #f8f9fc;
            min-height: 100vh;
        }

        .product-card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 1px 4px rgba(0,0,0,0.1);
            transition: all 0.2s ease;
            border: 1px solid #e8e8e8;
            margin-bottom: 8px;
            overflow: hidden;
        }
        
        .product-card:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        
        .product-card-header {
            background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
            color: white;
            padding: 8px 10px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .product-avatar {
            width: 32px;
            height: 32px;
            background: rgba(255,255,255,0.2);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.9rem;
            border: 1px solid rgba(255,255,255,0.3);
            flex-shrink: 0;
        }
        
        .product-header-info {
            flex: 1;
            min-width: 0;
        }
        
        .product-name {
            font-size: 0.9rem;
            font-weight: 600;
            margin-bottom: 2px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .product-code {
            background: rgba(255,255,255,0.2);
            padding: 1px 6px;
            border-radius: 10px;
            font-size: 0.65rem;
            display: inline-block;
        }
        
        .product-card-body {
            padding: 8px 10px;
        }
        
        .product-info {
            margin-bottom: 6px;
        }
        
        .info-item {
            display: flex;
            align-items: center;
            margin-bottom: 4px;
            font-size: 0.78rem;
        }
        
        .info-item i {
            width: 14px;
            color: #6c757d;
            margin-right: 8px;
            font-size: 0.75rem;
        }
        
        .info-item .label {
            color: #6c757d;
            margin-right: 6px;
        }
        
        .info-item .value {
            color: #495057;
            font-weight: 600;
            flex: 1;
        }
        
        .price-display {
            background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%);
            color: white;
            padding: 8px 10px;
            border-radius: 6px;
            margin-top: 6px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .price-label {
            font-size: 0.7rem;
            opacity: 0.9;
        }
        
        .price-value {
            font-size: 1.1rem;
            font-weight: 700;
        }
        
        .product-actions {
            border-top: 1px solid #f0f0f0;
            padding: 6px 8px;
            background: #fafafa;
            display: flex;
            gap: 6px;
        }
        
        .edit-btn, .delete-btn {
            background: linear-gradient(135deg, #ffc107 0%, #e0a800 100%);
            color: white;
            border: none;
            border-radius: 6px;
            padding: 6px 10px;
            font-weight: 600;
            font-size: 0.78rem;
            transition: all 0.2s ease;
            flex: 1;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
        }
        
        .delete-btn {
            background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
            flex: 0 0 auto;
            padding: 6px 8px;
        }
        
        .edit-btn:hover, .delete-btn:hover {
            filter: brightness(0.95);
            transform: translateY(-1px);
        }
        
        .search-box {
            background: white;
            border-radius: 8px;
            padding: 8px 10px;
            margin-bottom: 10px;
            box-shadow: 0 1px 4px rgba(0,0,0,0.1);
        }
        
        .search-input {
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            padding: 6px 30px 6px 10px;
            font-size: 0.85rem;
            transition: all 0.2s ease;
        }
        
        .search-input:focus {
            border-color: #4e73df;
            box-shadow: 0 0 0 2px rgba(78,115,223,0.25);
        }
        
        .search-icon {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #6c757d;
            font-size: 0.85rem;
        }
        
        #productsGrid {
            margin-left: -6px;
            margin-right: -6px;
        }
        
        #productsGrid > .col-6 {
            padding-left: 6px;
            padding-right: 6px;
        }

        .modal-content {
            border-radius: 8px;
            border: none;
            box-shadow: 0 8px 25px rgba(0,0,0,0.2);
        }
        
        .modal-header {
            background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
            color: white;
            border-radius: 8px 8px 0 0;
            padding: 12px 16px;
        }
        
        .modal-title {
            font-weight: 600;
            font-size: 1rem;
        }
        
        .form-control {
            border-radius: 4px;
            border: 1px solid #e9ecef;
            padding: 8px 12px;
            font-size: 0.9rem;
            transition: all 0.3s ease;
        }
        
        .form-control:focus {
            border-color: #4e73df;
            box-shadow: 0 0 0 2px rgba(78,115,223,0.1);
        }

        .header-section {
            background: white;
            border-radius: 8px;
            padding: 10px;
            margin-bottom: 10px;
            box-shadow: 0 1px 4px rgba(0,0,0,0.1);
        }

        .page-title {
            font-size: 1.2rem;
            font-weight: 700;
            color: #4e73df;
            margin-bottom: 5px;
        }

        .stats-row {
            display: flex;
            gap: 8px;
            margin-bottom: 10px;
        }

        .stat-box {
            flex: 1;
            background: white;
            border-radius: 6px;
            padding: 8px;
            text-align: center;
            box-shadow: 0 1px 4px rgba(0,0,0,0.1);
        }

        .stat-value {
            font-size: 1.2rem;
            font-weight: 700;
            color: #4e73df;
        }

        .stat-label {
            font-size: 0.7rem;
            color: #6c757d;
        }

        .inactive-item {
            opacity: 0.6;
        }
        
        .inactive-item .product-card {
            border-left: 4px solid #dc3545;
        }
        
        .product-card.low-stock {
            border-left: 4px solid #ffc107;
        }
        
        .badge-sm {
            font-size: 0.6rem;
            padding: 0.15rem 0.4rem;
        }

        @media (max-width: 768px) {
            .product-card-body {
                padding: 6px 8px;
            }
        }
    </style>
</head>

<body>
    <div class="container-fluid">
        <!-- Header -->
        <div class="header-section">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <div class="page-title">
                        <i class="fas fa-boxes"></i> Items Overview
                    </div>
                    <small class="text-muted">Browse and manage inventory items for sales</small>
                </div>
                <div>
                    <a href="index.php" class="btn btn-primary btn-sm">
                        <i class="fas fa-cash-register"></i> POS
                    </a>
                    <a href="../customer/index.php" class="btn btn-secondary btn-sm">
                        <i class="fas fa-home"></i>
                    </a>
                </div>
            </div>
        </div>

        <!-- Alert Messages -->
        <?php if (isset($success)): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle mr-2"></i><?php echo $success; ?>
            <button type="button" class="close" data-dismiss="alert">
                <span>&times;</span>
            </button>
        </div>
        <?php endif; ?>
        
        <?php if (isset($error)): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-circle mr-2"></i><?php echo $error; ?>
            <button type="button" class="close" data-dismiss="alert">
                <span>&times;</span>
            </button>
        </div>
        <?php endif; ?>

        <!-- Manage Items Button -->
        <div class="d-flex justify-content-end mb-3">
            <a href="../items/item-management.php" class="btn btn-primary btn-sm mr-2">
                <i class="fas fa-cog mr-1"></i>Manage Items
            </a>
            <a href="../items/add-item.php" class="btn btn-success btn-sm">
                <i class="fas fa-plus mr-1"></i>Add New Item
            </a>
        </div>

        <!-- Statistics -->
        <div class="stats-row">
            <div class="stat-box">
                <div class="stat-value"><?php echo $itemStats['total']; ?></div>
                <div class="stat-label">Total Items</div>
            </div>
            <div class="stat-box">
                <div class="stat-value"><?php echo $itemStats['active']; ?></div>
                <div class="stat-label">Active</div>
            </div>
            <div class="stat-box">
                <div class="stat-value"><?php echo $itemStats['inactive']; ?></div>
                <div class="stat-label">Inactive</div>
            </div>
            <div class="stat-box">
                <div class="stat-value" style="color: #dc3545;"><?php echo $itemStats['low_stock']; ?></div>
                <div class="stat-label">Low Stock</div>
            </div>
        </div>

        <!-- Search Box -->
        <div class="search-box">
            <div class="position-relative">
                <input type="text" class="form-control search-input" id="itemSearch" 
                       placeholder="Search items by code, name, brand, or category...">
                <i class="fas fa-search search-icon"></i>
            </div>
        </div>

        <!-- Items Grid -->
        <div class="row" id="itemsGrid">
            <?php foreach($items as $item): ?>
            <div class="col-6 item-item <?php echo $item['Status'] == 'Inactive' ? 'inactive-item' : ''; ?>">
                <div class="product-card <?php echo $item['CurrentStock'] <= $item['AlertQuantity'] ? 'low-stock' : ''; ?>">
                    <div class="product-card-header">
                        <div class="product-avatar">
                            <?php if ($item['Status'] == 'Inactive'): ?>
                            <i class="fas fa-ban" style="color: #dc3545;"></i>
                            <?php elseif ($item['CurrentStock'] <= $item['AlertQuantity']): ?>
                            <i class="fas fa-exclamation-triangle" style="color: #ffc107;"></i>
                            <?php else: ?>
                            <i class="fas fa-box"></i>
                            <?php endif; ?>
                        </div>
                        <div class="product-header-info">
                            <div class="product-name"><?php echo htmlspecialchars($item['ItemName']); ?></div>
                            <div>
                                <span class="product-code"><?php echo htmlspecialchars($item['ItemCode']); ?></span>
                                <span class="badge badge-<?php echo $item['Status'] == 'Active' ? 'success' : 'danger'; ?> badge-sm ml-1"><?php echo $item['Status']; ?></span>
                            </div>
                        </div>
                    </div>
                    <div class="product-card-body">
                        <div class="product-info">
                            <?php if (!empty($item['BrandName'])): ?>
                            <div class="info-item">
                                <i class="fas fa-tag"></i>
                                <span class="label">Brand:</span>
                                <span class="value"><?php echo htmlspecialchars($item['BrandName']); ?></span>
                            </div>
                            <?php endif; ?>
                            <?php if (!empty($item['CategoryName'])): ?>
                            <div class="info-item">
                                <i class="fas fa-layer-group"></i>
                                <span class="label">Category:</span>
                                <span class="value"><?php echo htmlspecialchars($item['CategoryName']); ?></span>
                            </div>
                            <?php endif; ?>
                            <div class="info-item">
                                <i class="fas fa-balance-scale"></i>
                                <span class="label">Unit:</span>
                                <span class="value"><?php echo htmlspecialchars($item['UnitName'] ?? 'N/A'); ?></span>
                            </div>
                            <div class="info-item">
                                <i class="fas fa-warehouse"></i>
                                <span class="label">Stock:</span>
                                <span class="value <?php echo $item['CurrentStock'] <= $item['AlertQuantity'] ? 'text-danger' : 'text-success'; ?>">
                                    <?php echo number_format($item['CurrentStock'], 2); ?>
                                    <?php if ($item['CurrentStock'] <= $item['AlertQuantity']): ?>
                                    <small class="text-danger">(Low)</small>
                                    <?php endif; ?>
                                </span>
                            </div>
                            <?php if (!empty($item['HSN'])): ?>
                            <div class="info-item">
                                <i class="fas fa-barcode"></i>
                                <span class="label">HSN:</span>
                                <span class="value"><?php echo htmlspecialchars($item['HSN']); ?></span>
                            </div>
                            <?php endif; ?>
                        </div>
                        <div class="price-display">
                            <div>
                                <div class="price-label">Sales Price</div>
                                <div class="price-value">₹<?php echo number_format($item['SalesPrice'] ?? $item['Price'] ?? 0, 2); ?></div>
                            </div>
                            <?php if (!empty($item['MRP']) && $item['MRP'] > 0): ?>
                            <div style="text-align: right;">
                                <div style="font-size: 0.6rem; opacity: 0.7;">MRP</div>
                                <div style="font-size: 0.8rem; text-decoration: line-through; opacity: 0.7;">₹<?php echo number_format($item['MRP'], 2); ?></div>
                            </div>
                            <?php else: ?>
                            <i class="fas fa-rupee-sign fa-2x" style="opacity: 0.3;"></i>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="product-actions">
                        <a href="../items/item-management.php?edit=<?php echo $item['ID']; ?>" class="edit-btn">
                            <i class="fas fa-edit"></i>
                            <span>Edit</span>
                        </a>
                        <button class="delete-btn" onclick="toggleItemStatus(<?php echo $item['ID']; ?>, '<?php echo htmlspecialchars($item['ItemName']); ?>', '<?php echo $item['Status']; ?>')">
                            <i class="fas fa-<?php echo $item['Status'] == 'Active' ? 'pause' : 'play'; ?>"></i>
                        </button>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>

        <?php if (empty($items)): ?>
        <div class="text-center py-5">
            <i class="fas fa-box-open fa-3x text-muted mb-3"></i>
            <h5 class="text-muted">No items found</h5>
            <p class="text-muted">Items are managed in the Items module. <a href="../items/add-item.php">Add your first item</a></p>
        </div>
        <?php endif; ?>

    </div>



    <script src="../vendor/jquery/jquery.min.js"></script>
    <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="../js/modern-messagebox.js"></script>

    <script>
        $(document).ready(function() {
            // Add animation on page load
            $('.product-card').each(function(index) {
                $(this).css('opacity', '0').css('transform', 'translateY(30px)');
                $(this).delay(index * 50).animate({
                    opacity: 1
                }, 400, function() {
                    $(this).css('transform', 'translateY(0)');
                });
            });
            
            // Search functionality
            $('#itemSearch').on('keyup', function() {
                const searchTerm = $(this).val().toLowerCase();
                
                $('.item-item').each(function() {
                    const itemName = $(this).find('.product-name').text().toLowerCase();
                    const itemCode = $(this).find('.product-code').text().toLowerCase();
                    const brandName = $(this).find('.info-item:contains("Brand:")').find('.value').text().toLowerCase();
                    const categoryName = $(this).find('.info-item:contains("Category:")').find('.value').text().toLowerCase();
                    
                    if (itemName.includes(searchTerm) || 
                        itemCode.includes(searchTerm) || 
                        brandName.includes(searchTerm) || 
                        categoryName.includes(searchTerm)) {
                        $(this).show();
                    } else {
                        $(this).hide();
                    }
                });
            });
        });

        function toggleItemStatus(id, itemName, currentStatus) {
            const action = currentStatus === 'Active' ? 'deactivate' : 'activate';
            const message = `${action.charAt(0).toUpperCase() + action.slice(1)} item "${itemName}"?`;
            
            MsgBox.confirm(message, {
                confirmText: action === 'deactivate' ? 'Deactivate' : 'Activate',
                cancelText: 'Cancel',
                type: currentStatus === 'Active' ? 'warning' : 'confirm'
            }).then(function(confirmed) {
                if (confirmed) {
                    const form = document.createElement('form');
                    form.method = 'POST';
                    form.innerHTML = `
                        <input type="hidden" name="action" value="toggle_status">
                        <input type="hidden" name="id" value="${id}">
                        <input type="hidden" name="current_status" value="${currentStatus}">
                    `;
                    document.body.appendChild(form);
                    form.submit();
                }
            });
        }

        // Auto-dismiss alerts
        setTimeout(function() {
            $('.alert').fadeOut();
        }, 5000);
    </script>
</body>
</html>
