<?php
require_once 'includes/db.php';

// Fetch all products
$products = fetchAll("SELECT p.*, b.name as buyer_name FROM products p LEFT JOIN buyers b ON p.buyer_id = b.id WHERE p.company_id = ? ORDER BY p.created_at DESC", [$_SESSION['company_id']]);
$buyers = fetchAll("SELECT id, name FROM buyers WHERE company_id = ? AND status = 'Active' ORDER BY name ASC", [$_SESSION['company_id']]);
$inventory_items = fetchAll("SELECT id, name, unit, sku FROM inventory_items WHERE company_id = ? AND status = 'In-Stock' ORDER BY name ASC", [$_SESSION['company_id']]);
?>

<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem; gap: 1rem;">
    <div style="position: relative; flex: 1; max-width: 400px;">
        <i class="fas fa-search" style="position: absolute; left: 1rem; top: 50%; transform: translateY(-50%); color: var(--text-muted); opacity: 0.5;"></i>
        <input type="text" id="productSearch" class="form-control" placeholder="Search by name, SKU, or buyer..." style="padding-left: 2.75rem; border-radius: 50px; background: var(--bg-card); border: 1px solid var(--border); box-shadow: var(--shadow);">
    </div>
    <button class="btn btn-primary" onclick="openAddProductModal()">
        <i class="fas fa-plus"></i> Add New Product
    </button>
</div>

    <div class="data-grid">
        <?php foreach ($products as $product): ?>
        <div class="data-card">
            <div class="data-card-header">
                <div style="display: flex; align-items: center; gap: 1rem;">
                    <div style="width: 48px; height: 48px; border-radius: 12px; background: rgba(99, 102, 241, 0.1); color: var(--primary); display: flex; align-items: center; justify-content: center; font-size: 1.25rem;">
                        <i class="fas fa-shirt"></i>
                    </div>
                    <div>
                        <h3 style="font-size: 1.125rem; font-weight: 700; margin-bottom: 0.25rem;"><?php echo $product['name']; ?></h3>
                        <div style="font-family: monospace; color: var(--accent); font-size: 0.875rem; font-weight: 700;"><?php echo $product['sku']; ?></div>
                    </div>
                </div>
                <span style="display: flex; align-items: center; gap: 0.375rem; font-size: 0.75rem; font-weight: 600; color: var(--success); background: rgba(16, 185, 129, 0.1); padding: 0.25rem 0.75rem; border-radius: 50px;">
                    <span style="width: 6px; height: 6px; border-radius: 50%; background: var(--success);"></span> Active
                </span>
            </div>
            
            <div class="data-card-body">
                <div class="data-card-item" style="margin-top: 0.5rem;">
                    <i class="fas fa-barcode"></i>
                    <span>SKU: <span style="font-family: monospace; font-weight: 700; color: var(--accent);"><?php echo $product['sku']; ?></span></span>
                </div>

                <div class="data-card-item">
                    <i class="fas fa-building"></i>
                    <span>Buyer: <?php echo $product['buyer_name'] ?? 'N/A'; ?></span>
                </div>

                <div class="data-card-item">
                    <i class="fas fa-tag"></i>
                    <span>Selling Price: <span style="font-weight: 700; color: var(--primary);"><?php echo ($_SESSION['company_currency'] ?? '$') . number_format($product['base_price'], 2); ?></span></span>
                </div>
                <?php if ($product['description']): ?>
                <div class="data-card-item">
                    <i class="fas fa-info-circle"></i>
                    <span style="font-size: 0.875rem; color: var(--text-muted);"><?php echo $product['description']; ?></span>
                </div>
                <?php endif; ?>
            </div>

            <div class="data-card-footer">
                <button class="btn" style="background: var(--bg-dark); padding: 0.5rem;" onclick='editProduct(<?php 
                    $materials = fetchAll("SELECT es.*, i.name, i.unit, i.sku FROM inventory_item_product es JOIN inventory_items i ON es.inventory_item_id = i.id WHERE es.product_id = ?", [$product['id']]);
                    $product['materials'] = $materials;
                    $product['samples'] = fetchAll("SELECT * FROM product_samples WHERE product_id = ?", [$product['id']]);
                    echo json_encode($product); 
                ?>)'>
                    <i class="fas fa-edit"></i> Edit
                </button>
                <button class="btn" style="background: rgba(239, 68, 68, 0.1); color: var(--danger); padding: 0.5rem;" onclick="deleteProduct(<?php echo $product['id']; ?>)">
                    <i class="fas fa-trash"></i>
                </button>
            </div>
        </div>
        <?php endforeach; ?>
        
        <?php if (empty($products)): ?>
        <div style="grid-column: 1 / -1; text-align: center; padding: 4rem; background: var(--bg-card); border-radius: 24px; border: 2px dashed var(--border);">
            <i class="fas fa-box-open fa-3x" style="margin-bottom: 1.5rem; color: var(--text-muted); opacity: 0.5;"></i>
            <h3 style="color: var(--text-main); margin-bottom: 0.5rem;">No Products Found</h3>
            <p style="color: var(--text-muted);">Start by adding your first garment style to the catalog.</p>
        </div>
        <?php endif; ?>
    </div>

<!-- Product Modal -->
<div id="productModal" class="modal-overlay">
    <div class="modal-content" style="max-width: 900px;">
        <div class="modal-header">
            <h2 id="modalTitle">Add New Product</h2>
            <button onclick="closeModal('productModal')" style="background: none; border: none; cursor: pointer; color: var(--text-muted);"><i class="fas fa-times"></i></button>
        </div>
        <div class="modal-body">
            <form id="productForm">
                <input type="hidden" id="product_id" name="id">
                <div class="form-group">
                    <label class="form-label">Style Name / Code <span class="required-mark">*</span></label>
                    <input type="text" id="product_name" name="name" class="form-control" placeholder="e.g. Slim Fit Denim" required>
                </div>
                <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 1rem;">
                    <div class="form-group">
                        <label class="form-label">Buyer <span class="required-mark">*</span></label>
                        <select id="product_buyer" name="buyer_id" class="form-control" required>
                            <option value="">Select Buyer</option>
                            <?php foreach ($buyers as $buyer): ?>
                            <option value="<?php echo $buyer['id']; ?>"><?php echo $buyer['name']; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">SKU</label>
                        <input type="text" id="product_sku" name="sku" class="form-control" readonly placeholder="PRD-12345678">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Selling Price (<?php echo $_SESSION['company_currency'] ?? '$'; ?>) <span class="required-mark">*</span></label>
                        <input type="number" id="product_price" name="base_price" class="form-control" step="0.01" min="0" placeholder="0.00" required>
                    </div>
                </div>
                <div class="form-group">
                    <label class="form-label">Description</label>
                    <textarea id="product_desc" name="description" class="form-control" rows="2"></textarea>
                </div>
                <div class="form-group">
                    <label class="form-label">Samples <span style="font-size: 0.75rem; color: var(--text-muted); font-weight: normal;">(Upload multiple attachments)</span></label>
                    <div id="existing_samples" style="display: flex; flex-wrap: wrap; gap: 0.5rem; margin-bottom: 0.5rem;"></div>
                    <input type="file" id="product_samples" name="samples[]" class="form-control" multiple accept="image/*,.pdf,.doc,.docx">
                </div>

                <!-- Bill of Materials Section -->
                <div style="margin-top: 1.5rem; padding-top: 1.5rem; border-top: 1px solid var(--border);">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
                        <h3 style="font-size: 1rem; font-weight: 700; color: var(--primary);">Required Materials (BOM)</h3>
                        <div style="width: 250px; position: relative;">
                            <input type="text" id="bom_search" class="form-control" placeholder="Search Material..." oninput="searchMaterials(this.value)" autocomplete="off">
                            <div id="bom_search_results" style="display: none; position: absolute; top: 100%; left: 0; right: 0; background: var(--bg-card); border: 1px solid var(--border); border-radius: 8px; z-index: 1000; max-height: 200px; overflow-y: auto; box-shadow: 0 4px 20px rgba(0,0,0,0.3);">
                                <!-- Search results will appear here -->
                            </div>
                        </div>
                    </div>
                    
                    <div class="table-container" style="background: var(--bg-dark); border-radius: 12px; max-height: 250px; overflow-y: auto;">
                        <table style="font-size: 0.875rem;">
                            <thead>
                                <tr>
                                    <th>Material</th>
                                    <th>UoM</th>
                                    <th width="130">Qty</th>
                                    <th width="130">Wastage</th>
                                    <th>Reason</th>
                                    <th width="50"></th>
                                </tr>
                            </thead>
                            <tbody id="bom_list">
                                <!-- Material rows will be added here -->
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="modal-footer" style="padding: 1rem 0 0 0; border-top: none;">
                    <button type="button" class="btn" style="background: var(--bg-dark); color: var(--text-main);" onclick="closeModal('productModal')">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save Product</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function openAddProductModal() {
    document.getElementById('modalTitle').innerText = 'Add New Product';
    document.getElementById('productForm').reset();
    document.getElementById('product_id').value = '';
    document.getElementById('product_price').value = '';
    document.getElementById('bom_list').innerHTML = '';
    const random8 = Math.floor(10000000 + Math.random() * 90000000);
    document.getElementById('product_sku').value = 'PRD-' + random8;
    document.getElementById('existing_samples').innerHTML = '';
    openModal('productModal');
}

const allInventoryItems = <?php echo json_encode($inventory_items); ?>;

function searchMaterials(query) {
    const resultsContainer = document.getElementById('bom_search_results');
    if (!query.trim()) {
        resultsContainer.style.display = 'none';
        return;
    }

    const filtered = allInventoryItems.filter(item => 
        item.name.toLowerCase().includes(query.toLowerCase()) || 
        item.sku.toLowerCase().includes(query.toLowerCase())
    );

    if (filtered.length === 0) {
        resultsContainer.innerHTML = '<div style="padding: 0.75rem 1rem; color: var(--text-muted); font-size: 0.875rem;">No materials found</div>';
    } else {
        resultsContainer.innerHTML = filtered.map(item => `
            <div class="search-result-item" onclick='addMaterialRow(${JSON.stringify(item)})' style="padding: 0.75rem 1rem; cursor: pointer; border-bottom: 1px solid var(--border); transition: all 0.2s;">
                <div style="font-weight: 600; color: var(--text-main); font-size: 0.875rem;">${item.name}</div>
                <div style="font-size: 0.7rem; color: var(--accent); font-weight: 700;">${item.sku}</div>
            </div>
        `).join('');
    }
    resultsContainer.style.display = 'block';
}

// Close search results when clicking outside
document.addEventListener('click', (e) => {
    if (!e.target.closest('#bom_search') && !e.target.closest('#bom_search_results')) {
        document.getElementById('bom_search_results').style.display = 'none';
    }
});

function addMaterialRow(data) {
    if (!data) return;
    const materialId = data.inventory_item_id || data.id;

    // Check if already added
    if (document.querySelector(`tr[data-id="${materialId}"]`)) {
        notify('Material already added', 'warning');
        document.getElementById('bom_search').value = '';
        document.getElementById('bom_search_results').style.display = 'none';
        return;
    }

    const row = document.createElement('tr');
    row.dataset.id = materialId;
    row.innerHTML = `
        <td>
            <div style="font-weight: 600;">${data.name}</div>
            <div style="font-size: 0.7rem; color: var(--text-muted);">${data.sku}</div>
            <input type="hidden" name="materials[${materialId}][id]" value="${materialId}">
        </td>
        <td>${data.unit}</td>
        <td><input type="number" name="materials[${materialId}][qty]" class="form-control" value="${data.quantity || 1}" step="0.0001" style="width: 110px;" required></td>
        <td><input type="number" name="materials[${materialId}][wastage]" class="form-control" value="${data.wastage_quantity || 0}" step="0.0001" style="width: 110px;"></td>
        <td><input type="text" name="materials[${materialId}][reason]" class="form-control" value="${data.wastage_reason || ''}" placeholder="e.g. Cutting"></td>
        <td>
            <button type="button" class="btn" style="color: var(--danger); background: none;" onclick="this.closest('tr').remove()">
                <i class="fas fa-times"></i>
            </button>
        </td>
    `;
    document.getElementById('bom_list').appendChild(row);
    document.getElementById('bom_search').value = '';
    document.getElementById('bom_search_results').style.display = 'none';
}

function editProduct(product) {
    document.getElementById('modalTitle').innerText = 'Edit Product';
    document.getElementById('product_id').value = product.id;
    document.getElementById('product_name').value = product.name;
    document.getElementById('product_buyer').value = product.buyer_id || '';
    document.getElementById('product_sku').value = product.sku;
    document.getElementById('product_price').value = parseFloat(product.base_price || 0).toFixed(2);
    document.getElementById('product_desc').value = product.description || '';
    
    // Load BOM
    const bomList = document.getElementById('bom_list');
    bomList.innerHTML = '';
    if (product.materials) {
        product.materials.forEach(m => addMaterialRow(m));
    }

    // Load Samples
    const samplesContainer = document.getElementById('existing_samples');
    samplesContainer.innerHTML = '';
    if (product.samples && product.samples.length > 0) {
        product.samples.forEach(sample => {
            const isImage = sample.file_type && sample.file_type.startsWith('image/');
            const div = document.createElement('div');
            div.style.cssText = 'position: relative; padding: 0.5rem; background: var(--bg-dark); border-radius: 12px; font-size: 0.75rem; display: flex; align-items: center; gap: 0.75rem; border: 1px solid var(--border); transition: all 0.2s;';
            div.innerHTML = `
                ${isImage ? `<img src="${sample.file_path}" style="width: 32px; height: 32px; object-fit: cover; border-radius: 6px; border: 1px solid rgba(0,0,0,0.1);">` : `<i class="fas fa-file-alt" style="color: var(--primary); font-size: 1.25rem;"></i>`}
                <div style="flex: 1; min-width: 0;">
                    <a href="${sample.file_path}" target="_blank" style="display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text-main); text-decoration: none; font-weight: 600;">${sample.file_name}</a>
                </div>
                <button type="button" onclick="removeSample(${sample.id}, this)" style="background: none; border: none; color: var(--danger); cursor: pointer; padding: 0.25rem; opacity: 0.7;" onmouseover="this.style.opacity=1" onmouseout="this.style.opacity=0.7">
                    <i class="fas fa-times-circle"></i>
                </button>
            `;
            samplesContainer.appendChild(div);
        });
    }
    
    openModal('productModal');
}

async function removeSample(sampleId, btn) {
    if (confirm('Are you sure you want to remove this sample?')) {
        const result = await apiCall('products', { action: 'remove_sample', sample_id: sampleId });
        if (result.success) {
            btn.closest('div').remove();
            notify(result.message);
        } else {
            notify(result.message, 'error');
        }
    }
}

async function deleteProduct(id) {
    if (await confirmAction({ 
        title: 'Delete Product', 
        message: 'Are you sure you want to delete this product? This will also remove its Bill of Materials. You cannot delete products currently assigned to production lines.' 
    })) {
        const result = await apiCall('products', { action: 'delete', id: id });
        if (result.success) {
            notify(result.message);
            setTimeout(() => location.reload(), 1000);
        } else {
            notify(result.message, 'error');
        }
    }
}

document.getElementById('productForm').onsubmit = async (e) => {
    e.preventDefault();
    const btn = e.target.querySelector('button[type="submit"]');
    const formData = new FormData(e.target);
    
    formData.append('action', 'save');

    // Collect materials
    const materials = [];
    document.querySelectorAll('#bom_list tr').forEach(tr => {
        const id = tr.dataset.id;
        materials.push({
            inventory_item_id: id,
            quantity: tr.querySelector(`input[name="materials[${id}][qty]"]`).value,
            wastage_quantity: tr.querySelector(`input[name="materials[${id}][wastage]"]`).value,
            wastage_reason: tr.querySelector(`input[name="materials[${id}][reason]"]`).value
        });
    });
    formData.append('materials', JSON.stringify(materials));
    
    const result = await apiCall('products', { data: formData, btn: btn });
    if (result.success) {
        notify(result.message);
        setTimeout(() => location.reload(), 1000);
    } else {
        notify(result.message, 'error');
    }
};

function openModal(id) {
    document.getElementById(id).classList.add('active');
}
function closeModal(id) {
    document.getElementById(id).classList.remove('active');
}

// Real-time Product Search
document.getElementById('productSearch').addEventListener('input', function(e) {
    const term = e.target.value.toLowerCase();
    const cards = document.querySelectorAll('.data-card');
    let hasResults = false;
    
    cards.forEach(card => {
        const name = card.querySelector('h3').innerText.toLowerCase();
        const sku = card.querySelector('.data-card-header div div div').innerText.toLowerCase();
        const buyer = card.querySelector('.data-card-item:nth-of-type(2)').innerText.toLowerCase();
        
        if (name.includes(term) || sku.includes(term) || buyer.includes(term)) {
            card.style.display = 'flex';
            hasResults = true;
        } else {
            card.style.display = 'none';
        }
    });

    // Handle "No Results" state
    const grid = document.querySelector('.data-grid');
    let noResultsMsg = document.getElementById('noSearchMsg');
    
    if (!hasResults) {
        if (!noResultsMsg) {
            noResultsMsg = document.createElement('div');
            noResultsMsg.id = 'noSearchMsg';
            noResultsMsg.style.cssText = 'grid-column: 1 / -1; text-align: center; padding: 4rem; color: var(--text-muted);';
            noResultsMsg.innerHTML = `
                <i class="fas fa-search-minus fa-3x" style="margin-bottom: 1rem; opacity: 0.5;"></i>
                <h3>No matches found for "${e.target.value}"</h3>
                <p>Try checking the spelling or use a different search term.</p>
            `;
            grid.appendChild(noResultsMsg);
        } else {
            noResultsMsg.querySelector('h3').innerText = `No matches found for "${e.target.value}"`;
        }
    } else if (noResultsMsg) {
        noResultsMsg.remove();
    }
});

// Real-time Previews for new file selection
document.getElementById('product_samples').addEventListener('change', function(e) {
    const files = e.target.files;
    const previewContainer = document.getElementById('existing_samples');
    
    // We don't clear existing_samples as they are already saved, 
    // but maybe we should show a clear distinction for "to be uploaded" files
    const newFilesLabel = document.getElementById('new_files_label');
    if (!newFilesLabel && files.length > 0) {
        const label = document.createElement('div');
        label.id = 'new_files_label';
        label.style.cssText = 'width: 100%; font-size: 0.7rem; font-weight: 700; color: var(--primary); text-transform: uppercase; margin-top: 1rem; margin-bottom: 0.5rem;';
        label.innerText = 'New Files to Upload:';
        previewContainer.appendChild(label);
    }

    for (const file of files) {
        const div = document.createElement('div');
        div.className = 'new-file-preview';
        div.style.cssText = 'position: relative; padding: 0.5rem; background: rgba(99, 102, 241, 0.05); border: 1px dashed var(--primary-light); border-radius: 12px; font-size: 0.75rem; display: flex; align-items: center; gap: 0.75rem; transition: all 0.2s;';
        
        if (file.type.startsWith('image/')) {
            const reader = new FileReader();
            reader.onload = function(e) {
                div.innerHTML = `
                    <img src="${e.target.result}" style="width: 32px; height: 32px; object-fit: cover; border-radius: 6px;">
                    <div style="flex: 1; min-width: 0;">
                        <span style="display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text-main); font-weight: 600;">${file.name}</span>
                    </div>
                `;
            };
            reader.readAsDataURL(file);
        } else {
            div.innerHTML = `
                <i class="fas fa-file-alt" style="color: var(--primary); font-size: 1.25rem;"></i>
                <div style="flex: 1; min-width: 0;">
                    <span style="display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text-main); font-weight: 600;">${file.name}</span>
                </div>
            `;
        }
        previewContainer.appendChild(div);
    }
});
</script>
