<?php
require_once 'includes/db.php';
$buyers = fetchAll("SELECT * FROM buyers WHERE company_id = ? ORDER BY created_at DESC", [$_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="buyerSearch" class="form-control" placeholder="Search by name, brand, 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="openAddBuyerModal()">
        <i class="fas fa-plus"></i> Add New Buyer
    </button>
</div>

<div class="data-grid">
    <?php foreach ($buyers as $buyer): ?>
    <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 $buyer['name']; ?></h3>
                <div style="color: var(--primary); font-size: 0.875rem; font-weight: 600;"><?php echo $buyer['brand']; ?></div>
            </div>
            <span class="btn" style="padding: 0.25rem 0.75rem; font-size: 0.75rem; background: <?php echo $buyer['status'] === 'Active' ? 'rgba(16, 185, 129, 0.1)' : 'rgba(239, 68, 68, 0.1)'; ?>; color: <?php echo $buyer['status'] === 'Active' ? 'var(--success)' : 'var(--danger)'; ?>;">
                <?php echo $buyer['status']; ?>
            </span>
        </div>
        
        <div class="data-card-body">
            <div class="data-card-item">
                <i class="fas fa-location-dot"></i>
                <span><?php echo $buyer['country']; ?></span>
            </div>
            <div class="data-card-item">
                <i class="fas fa-user"></i>
                <span><?php echo $buyer['contact_person']; ?></span>
            </div>
            <div class="data-card-item">
                <i class="fas fa-envelope"></i>
                <span style="color: var(--text-muted);"><?php echo $buyer['email'] ?: 'No Email'; ?></span>
            </div>
            <div class="data-card-item">
                <i class="fas fa-phone"></i>
                <span style="color: var(--text-muted);"><?php echo $buyer['phone']; ?></span>
            </div>
        </div>

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

    <?php if (empty($buyers)): ?>
    <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 Buyers Found</h3>
        <p style="color: var(--text-muted);">Register your first client to start managing orders.</p>
    </div>
    <?php endif; ?>
</div>

<!-- Add/Edit Buyer Modal -->
<div id="buyerModal" class="modal-overlay">
    <div class="modal-content">
        <div class="modal-header">
            <h2 id="modalTitle">Add New Buyer</h2>
            <button class="btn" style="background: none; color: var(--text-muted);" onclick="closeModal('buyerModal')">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <form id="buyerForm">
            <input type="hidden" id="buyer_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">Buyer Name <span class="required-mark">*</span></label>
                        <input type="text" id="buyer_name" name="name" class="form-control" placeholder="e.g. Zara" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Brand <span class="required-mark">*</span></label>
                        <input type="text" id="buyer_brand" name="brand" class="form-control" placeholder="e.g. Zara Man" required>
                    </div>
                </div>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                    <div class="form-group">
                        <label class="form-label">Country <span class="required-mark">*</span></label>
                        <select id="buyer_country" name="country" class="form-control" required>
                            <option value="">— Select Country —</option>
                            <option value="Sri Lanka">Sri Lanka</option>
                            <option value="Spain">Spain</option>
                            <option value="United States">United States</option>
                            <option value="United Kingdom">United Kingdom</option>
                            <option value="Bangladesh">Bangladesh</option>
                            <option value="India">India</option>
                            <option value="China">China</option>
                            <option value="Vietnam">Vietnam</option>
                            <option value="France">France</option>
                            <option value="Germany">Germany</option>
                            <option value="Italy">Italy</option>
                            <option value="Canada">Canada</option>
                            <option value="Australia">Australia</option>
                            <option value="Japan">Japan</option>
                            <option value="Netherlands">Netherlands</option>
                            <option value="Sweden">Sweden</option>
                            <option value="Turkey">Turkey</option>
                            <option value="Portugal">Portugal</option>
                            <option value="Brazil">Brazil</option>
                            <option value="Belgium">Belgium</option>
                            <option value="Denmark">Denmark</option>
                            <option value="Switzerland">Switzerland</option>
                            <option value="Singapore">Singapore</option>
                            <option value="Hong Kong">Hong Kong</option>
                            <option value="UAE">UAE</option>
                            <option value="South Africa">South Africa</option>
                            <option value="Mexico">Mexico</option>
                            <option value="New Zealand">New Zealand</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Contact Person <span class="required-mark">*</span></label>
                        <input type="text" id="buyer_contact" name="contact_person" class="form-control" required>
                    </div>
                </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="buyer_email" name="email" class="form-control">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Phone <span class="required-mark">*</span></label>
                        <input type="tel" id="buyer_phone" name="phone" class="form-control" required>
                    </div>
                </div>
                <div class="form-group">
                    <label class="form-label">Status</label>
                    <select id="buyer_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('buyerModal')">Cancel</button>
                <button type="submit" class="btn btn-primary">Save Buyer</button>
            </div>
        </form>
    </div>
</div>

<script>
function openAddBuyerModal() {
    document.getElementById('modalTitle').innerText = 'Add New Buyer';
    document.getElementById('buyerForm').reset();
    document.getElementById('buyer_id').value = '';
    openModal('buyerModal');
}

function editBuyer(buyer) {
    document.getElementById('modalTitle').innerText = 'Edit Buyer';
    document.getElementById('buyer_id').value = buyer.id;
    document.getElementById('buyer_name').value = buyer.name;
    document.getElementById('buyer_brand').value = buyer.brand;

    // Ensure buyer.country is in the dropdown list, otherwise add it dynamically
    const countrySelect = document.getElementById('buyer_country');
    if (buyer.country) {
        let hasOption = false;
        for (let i = 0; i < countrySelect.options.length; i++) {
            if (countrySelect.options[i].value === buyer.country) {
                hasOption = true;
                break;
            }
        }
        if (!hasOption) {
            const opt = document.createElement('option');
            opt.value = buyer.country;
            opt.textContent = buyer.country;
            countrySelect.appendChild(opt);
        }
    }
    countrySelect.value = buyer.country;

    document.getElementById('buyer_contact').value = buyer.contact_person;
    document.getElementById('buyer_email').value = buyer.email;
    document.getElementById('buyer_phone').value = buyer.phone;
    document.getElementById('buyer_status').value = buyer.status;
    openModal('buyerModal');
}

document.getElementById('buyerForm').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('buyers', { data: { action: 'save', buyer: data }, btn: btn });
    if (result.success) {
        notify(result.message);
        setTimeout(() => location.reload(), 1000);
    } else {
        notify(result.message, 'error');
    }
};

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

// Real-time Buyer Search
document.getElementById('buyerSearch').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 brand = card.querySelector('.data-card-header div div').innerText.toLowerCase();
        const details = card.querySelector('.data-card-body').innerText.toLowerCase();
        
        if (name.includes(term) || brand.includes(term) || details.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();
    }
});
</script>
