<?php
require_once 'includes/db.php';
$suppliers = fetchAll("SELECT * FROM suppliers WHERE company_id = ? ORDER BY created_at DESC", [$_SESSION['company_id']]);
$categories = fetchAll("SELECT * FROM inventory_categories WHERE is_active = 1 ORDER BY name ASC");
?>

<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="supplierSearch" class="form-control" placeholder="Search by name, category, or contact..." 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="openAddSupplierModal()">
        <i class="fas fa-plus"></i> Add New Supplier
    </button>
</div>

    <div class="data-grid">
        <?php foreach ($suppliers as $supplier): ?>
        <div class="data-card">
            <div class="data-card-header">
                <div>
                    <h3 style="font-size: 1.125rem; font-weight: 700; margin-bottom: 0.25rem;"><?php echo $supplier['name']; ?></h3>
                    <span class="btn" style="padding: 0.25rem 0.75rem; font-size: 0.75rem; background: rgba(124, 58, 237, 0.1); color: var(--primary);"><?php echo $supplier['category']; ?></span>
                </div>
                <span class="btn" style="padding: 0.25rem 0.75rem; font-size: 0.75rem; background: <?php echo $supplier['status'] === 'Active' ? 'rgba(16, 185, 129, 0.1)' : 'rgba(239, 68, 68, 0.1)'; ?>; color: <?php echo $supplier['status'] === 'Active' ? 'var(--success)' : 'var(--danger)'; ?>;">
                    <?php echo $supplier['status']; ?>
                </span>
            </div>
            
            <div class="data-card-body">
                <div class="data-card-item">
                    <i class="fas fa-star" style="color: var(--warning);"></i>
                    <span>
                        <?php echo $supplier['rating']; ?>/5 Rating
                    </span>
                </div>
                <div class="data-card-item">
                    <i class="fas fa-clock"></i>
                    <span><?php echo $supplier['lead_time']; ?> Days Lead Time</span>
                </div>
                <div class="data-card-item">
                    <i class="fas fa-user"></i>
                    <span><?php echo $supplier['contact_person']; ?></span>
                </div>
                <div class="data-card-item">
                    <i class="fas fa-envelope"></i>
                    <span style="color: var(--text-muted);"><?php echo $supplier['email'] ?: 'No Email'; ?></span>
                </div>
            </div>

            <div class="data-card-footer">
                <button class="btn" style="background: var(--bg-dark); padding: 0.5rem;" onclick='editSupplier(<?php echo htmlspecialchars(json_encode($supplier), ENT_QUOTES, "UTF-8"); ?>)'>
                    <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="deleteSupplier(<?php echo $supplier['id']; ?>)">
                    <i class="fas fa-trash"></i>
                </button>
            </div>
        </div>
        <?php endforeach; ?>

        <?php if (empty($suppliers)): ?>
        <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 Suppliers Found</h3>
            <p style="color: var(--text-muted);">Add your supply partners to manage inventory better.</p>
        </div>
        <?php endif; ?>
    </div>

<!-- Supplier Modal -->
<div id="supplierModal" class="modal-overlay">
    <div class="modal-content">
        <div class="modal-header">
            <h2 id="modalTitle">Add New Supplier</h2>
            <button class="btn" style="background: none; color: var(--text-muted);" onclick="closeModal('supplierModal')">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <form id="supplierForm">
            <input type="hidden" id="supplier_id" name="id">
            <div class="modal-body">
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                    <div class="form-group">
                        <label class="form-label">Supplier Name <span class="required-mark">*</span></label>
                        <input type="text" id="supplier_name" name="name" class="form-control" placeholder="e.g. TexFabric Co" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Category <span class="required-mark">*</span></label>
                        <select id="supplier_category" name="category" class="form-control" required>
                            <option value="">Select Category</option>
                            <?php foreach ($categories as $category): ?>
                            <option value="<?php echo htmlspecialchars($category['name']); ?>"><?php echo htmlspecialchars($category['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label class="form-label">Contact Person <span class="required-mark">*</span></label>
                    <input type="text" id="supplier_contact" name="contact_person" class="form-control" required>
                </div>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                    <div class="form-group">
                        <label class="form-label">Email</label>
                        <input type="email" id="supplier_email" name="email" class="form-control">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Phone Number</label>
                        <input type="tel" id="supplier_phone" name="phone" class="form-control">
                    </div>
                </div>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                    <div class="form-group">
                        <label class="form-label">Lead Time (Days)</label>
                        <input type="number" id="supplier_lead_time" name="lead_time" class="form-control">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Initial Rating (1-5)</label>
                        <input type="number" id="supplier_rating" name="rating" min="1" max="5" class="form-control" value="5">
                    </div>
                </div>
                <div class="form-group">
                    <label class="form-label">Status</label>
                    <select id="supplier_status" name="status" class="form-control">
                        <option value="Active">Active</option>
                        <option value="Inactive">Inactive</option>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn" style="background: var(--glass-bg);" onclick="closeModal('supplierModal')">Cancel</button>
                <button type="submit" class="btn btn-primary">Save Supplier</button>
            </div>
        </form>
    </div>
</div>

<script>
function openAddSupplierModal() {
    document.getElementById('modalTitle').innerText = 'Add New Supplier';
    document.getElementById('supplierForm').reset();
    document.getElementById('supplier_id').value = '';
    openModal('supplierModal');
}

function editSupplier(supplier) {
    document.getElementById('modalTitle').innerText = 'Edit Supplier';
    document.getElementById('supplier_id').value = supplier.id;
    document.getElementById('supplier_name').value = supplier.name;
    document.getElementById('supplier_category').value = supplier.category;
    document.getElementById('supplier_lead_time').value = supplier.lead_time;
    document.getElementById('supplier_contact').value = supplier.contact_person;
    document.getElementById('supplier_email').value = supplier.email;
    document.getElementById('supplier_phone').value = supplier.phone || '';
    document.getElementById('supplier_rating').value = supplier.rating;
    document.getElementById('supplier_status').value = supplier.status;
    openModal('supplierModal');
}

document.getElementById('supplierForm').onsubmit = async (e) => {
    e.preventDefault();
    const btn = e.target.querySelector('button[type="submit"]');
    const formData = new FormData(e.target);
    const data = Object.fromEntries(formData.entries());
    
    const result = await apiCall('suppliers', { data: { action: 'save', supplier: data }, btn: btn });
    if (result.success) {
        notify(result.message);
        setTimeout(() => location.reload(), 1000);
    } else {
        notify(result.message, 'error');
    }
};

async function deleteSupplier(id) {
    if (await confirmAction({ title: 'Delete Supplier', message: 'Are you sure you want to delete this supplier?' })) {
        const result = await apiCall('suppliers', { action: 'delete', id: id });
        if (result.success) {
            notify(result.message);
            setTimeout(() => location.reload(), 1000);
        } else {
            notify(result.message, 'error');
        }
    }
}

// Real-time Supplier Search
document.getElementById('supplierSearch').addEventListener('input', function(e) {
    const term = e.target.value.toLowerCase();
    const cards = document.querySelectorAll('.data-card');
    let hasResults = false;
    
    cards.forEach(card => {
        const text = card.innerText.toLowerCase();
        if (text.includes(term)) {
            card.style.display = 'flex';
            hasResults = true;
        } else {
            card.style.display = 'none';
        }
    });

    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 searching for a different supplier name or category.</p>
            `;
            grid.appendChild(noResultsMsg);
        } else {
            noResultsMsg.querySelector('h3').innerText = `No matches found for "${e.target.value}"`;
        }
    } else if (noResultsMsg) {
        noResultsMsg.remove();
    }
});
</script>
