<?php
require_once __DIR__ . '/../includes/config.php';

$page_title = 'Produse';

require_once __DIR__ . '/../includes/header.php';
?>

<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px">
    <div class="search-bar" style="flex:1">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
        <input placeholder="Caută produs..." id="search-input" style="background:none;border:none;outline:none;color:var(--text);font-size:13.5px;font-family:'DM Sans',sans-serif;width:100%" oninput="filterProducts()">
    </div>
    <a href="<?php echo APP_URL; ?>/admin/product-form.php" class="btn btn-primary" style="margin-left:10px">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" width="15" height="15"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
        Adaugă produs
    </a>
</div>

<?php
$search = $_GET['q'] ?? '';
$search = escape($search);

$query = "SELECT p.*, c.name as category_name, c.color as category_color 
          FROM products p 
          JOIN categories c ON p.category_id = c.id 
          WHERE 1=1";

if (!empty($search)) {
    $query .= " AND (p.name LIKE '%$search%' OR p.sku LIKE '%$search%')";
}

$query .= " ORDER BY p.active DESC, p.name ASC";

$result = $db->query($query);
$products = [];
if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $products[] = $row;
    }
}
?>

<div class="product-grid" id="product-grid">
    <?php if (empty($products)): ?>
        <div class="empty-state" style="grid-column:1/-1">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 7V5a2 2 0 00-2-2h-4a2 2 0 00-2 2v2"/></svg>
            <h3>Niciun produs</h3>
            <p>Adaugă primul produs</p>
        </div>
    <?php else: ?>
        <?php foreach ($products as $p): ?>
            <div class="product-card" data-name="<?php echo strtolower($p['name']); ?>" data-sku="<?php echo strtolower($p['sku'] ?? ''); ?>">
                <div class="product-img">
                    <?php if ($p['image_path'] && file_exists(__DIR__ . '/../uploads/' . $p['image_path'])): ?>
                        <img src="<?php echo APP_URL . '/uploads/' . urlencode($p['image_path']); ?>" alt="<?php echo htmlspecialchars($p['name']); ?>" style="width:100%;height:100%;object-fit:cover">
                    <?php else: ?>
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.2"><path d="M20 7H4a2 2 0 00-2 2v10a2 2 0 002 2h16a2 2 0 002-2V9a2 2 0 00-2-2z"/><path d="M16 7V5a2 2 0 00-2-2h-4a2 2 0 00-2 2v2"/></svg>
                    <?php endif; ?>
                    <?php if (!$p['active']): ?>
                        <div style="position:absolute;top:8px;right:8px"><span class="badge badge-gray">Inactiv</span></div>
                    <?php endif; ?>
                    <?php if ($p['stock'] <= 0): ?>
                        <div style="position:absolute;top:8px;left:8px"><span class="badge badge-red">Epuizat</span></div>
                    <?php elseif ($p['stock'] <= $p['min_stock']): ?>
                        <div style="position:absolute;top:8px;left:8px"><span class="badge badge-yellow">Stoc mic</span></div>
                    <?php endif; ?>
                </div>
                <div class="product-info">
                    <div class="product-name"><?php echo htmlspecialchars($p['name']); ?></div>
                    <div class="product-cat" style="font-size:11.5px;color:<?php echo $p['category_color']; ?>;margin-bottom:10px">● <?php echo htmlspecialchars($p['category_name']); ?></div>
                    <div style="display:flex;justify-content:space-between;align-items:center">
                        <div style="font-size:16px;font-weight:600;color:var(--accent);font-family:'Syne',sans-serif"><?php echo number_format($p['price'], 2, '.', ''); ?> lei</div>
                        <div style="font-size:12px;color:<?php echo $p['stock'] <= 0 ? 'var(--red)' : ($p['stock'] <= $p['min_stock'] ? 'var(--yellow)' : 'var(--green)'); ?>">Stoc: <?php echo $p['stock']; ?></div>
                    </div>
                    <div style="display:flex;gap:6px;margin-top:10px">
                        <a href="<?php echo APP_URL; ?>/admin/product-form.php?id=<?php echo $p['id']; ?>" class="btn btn-ghost btn-sm" style="flex:1">✎ Editează</a>
                        <button type="button" class="btn btn-ghost btn-sm" onclick="openNotesModal(<?php echo $p['id']; ?>, '<?php echo htmlspecialchars($p['name']); ?>')">📝 Note</button>
                        <form method="POST" action="<?php echo APP_URL; ?>/api/delete-product.php" style="display:inline" onsubmit="return confirm('Ștergi produsul: ' + '<?php echo htmlspecialchars($p['name']); ?>' + '?')">
                            <input type="hidden" name="id" value="<?php echo $p['id']; ?>">
                            <button type="submit" class="btn btn-danger btn-sm">✕</button>
                        </form>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

<style>
    .product-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:14px}
    .product-card{background:var(--bg2);border:1px solid var(--border);border-radius:var(--radius2);overflow:hidden;transition:border-color 0.15s,transform 0.15s}
    .product-card:hover{border-color:var(--border2);transform:translateY(-2px)}
    .product-img{width:100%;height:130px;background:var(--bg3);display:flex;align-items:center;justify-content:center;position:relative;overflow:hidden}
    .product-img svg{width:34px;height:34px;color:var(--text3)}
    .product-img img{width:100%;height:100%;object-fit:cover}
    .product-info{padding:14px}
    .product-name{font-family:'Syne',sans-serif;font-size:13.5px;font-weight:600;margin-bottom:3px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
</style>

<script>
function filterProducts() {
    const query = document.getElementById('search-input').value.toLowerCase();
    const cards = document.querySelectorAll('.product-card');
    
    cards.forEach(card => {
        const name = card.dataset.name || '';
        const sku = card.dataset.sku || '';
        const matches = name.includes(query) || sku.includes(query) || query === '';
        card.style.display = matches ? '' : 'none';
    });
}

// Notes Modal
function openNotesModal(productId, productName) {
    fetch('<?php echo APP_URL; ?>/api/get-product-comments.php?product_id=' + productId)
        .then(r => r.json())
        .then(data => {
            document.getElementById('notes-product-id').value = productId;
            document.getElementById('notes-product-name').textContent = productName;
            document.getElementById('notes-list').innerHTML = '';
            
            if (data.comments && data.comments.length > 0) {
                data.comments.forEach(c => {
                    const time = new Date(c.created_at).toLocaleString('ro-RO');
                    const html = `
                    <div style="background:var(--bg3);padding:12px;border-radius:8px;margin-bottom:10px">
                        <div style="display:flex;justify-content:space-between;align-items:start;font-size:12px">
                            <div style="color:var(--text2);font-weight:600">${escapeHtml(c.name)}</div>
                            <div style="color:var(--text3)">${time}</div>
                        </div>
                        <div style="margin-top:6px;font-size:13px;color:var(--text)">${escapeHtml(c.comment)}</div>
                    </div>
                    `;
                    document.getElementById('notes-list').innerHTML += html;
                });
            } else {
                document.getElementById('notes-list').innerHTML = '<div style="color:var(--text3);text-align:center;padding:20px">Nicio notă</div>';
            }
            
            document.getElementById('notes-modal').style.display = 'block';
        });
}

function closeNotesModal() {
    document.getElementById('notes-modal').style.display = 'none';
}

function addNote() {
    const productId = document.getElementById('notes-product-id').value;
    const comment = document.getElementById('notes-input').value.trim();
    
    if (!comment) {
        alert('Scrie o notă');
        return;
    }
    
    const formData = new FormData();
    formData.append('product_id', productId);
    formData.append('comment', comment);
    
    fetch('<?php echo APP_URL; ?>/api/add-product-comment.php', {
        method: 'POST',
        body: formData
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            document.getElementById('notes-input').value = '';
            openNotesModal(productId, document.getElementById('notes-product-name').textContent);
        } else {
            alert('Eroare: ' + data.error);
        }
    });
}

function escapeHtml(text) {
    const map = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
    };
    return text.replace(/[&<>"']/g, m => map[m]);
}
</script>

<!-- Notes Modal -->
<div id="notes-modal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:100;overflow-y:auto;padding:20px">
    <div style="background:var(--bg2);border:1px solid var(--border);border-radius:var(--radius2);max-width:500px;margin:20px auto;overflow:hidden">
        <div style="padding:20px;border-bottom:1px solid var(--border)">
            <div style="display:flex;justify-content:space-between;align-items:center">
                <h3 style="font-family:'Syne',sans-serif;font-size:15px;font-weight:600">Note produs: <span id="notes-product-name"></span></h3>
                <button onclick="closeNotesModal()" style="background:none;border:none;color:var(--text2);font-size:20px;cursor:pointer">×</button>
            </div>
        </div>
        
        <div style="padding:20px">
            <div id="notes-list" style="max-height:300px;overflow-y:auto;margin-bottom:16px"></div>
            
            <div style="display:flex;gap:10px">
                <textarea id="notes-input" placeholder="Adaugă o notă..." style="flex:1;background:var(--bg3);border:1px solid var(--border);color:var(--text);border-radius:8px;padding:10px;font-family:'DM Sans',sans-serif;font-size:13px;resize:none;height:60px"></textarea>
                <button onclick="addNote()" class="btn btn-primary" style="align-self:flex-end">Adaugă</button>
            </div>
            <input type="hidden" id="notes-product-id">
        </div>
    </div>
</div>

<?php
require_once __DIR__ . '/../includes/footer.php';
?>

