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

$product_id = $_GET['id'] ?? null;
$product = null;
$page_title = 'Produs';

if ($product_id) {
    $product_id = (int)$product_id;
    $result = $db->query("SELECT * FROM products WHERE id = $product_id");
    $product = $result ? $result->fetch_assoc() : null;
    
    if (!$product) {
        redirectWithMessage(APP_URL . '/admin/products.php', 'Produs nu a fost găsit', 'error');
    }
    $page_title = 'Editează: ' . htmlspecialchars($product['name']);
}

// Get categories
$categories_result = $db->query("SELECT * FROM categories ORDER BY name");
$categories = [];
while ($cat = $categories_result->fetch_assoc()) {
    $categories[] = $cat;
}

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

<div class="card" style="max-width:600px">
    <div class="card-header">
        <div class="card-title"><?php echo $product ? 'Editează produs' : 'Adaugă produs nou'; ?></div>
    </div>
    <div class="card-body">
        <form method="POST" action="<?php echo APP_URL; ?>/api/save-product.php" style="display:grid;gap:14px">
            <?php if ($product): ?>
                <input type="hidden" name="id" value="<?php echo $product['id']; ?>">
            <?php endif; ?>

            <div class="form-group full">
                <label class="form-label">Nume produs *</label>
                <input class="form-input" name="name" value="<?php echo $product ? htmlspecialchars($product['name']) : ''; ?>" placeholder="Ex: Set farfurii ceramică" required>
            </div>

            <div class="form-grid">
                <div class="form-group">
                    <label class="form-label">Preț vânzare (lei) *</label>
                    <input class="form-input" type="number" name="price" step="0.01" value="<?php echo $product ? $product['price'] : ''; ?>" placeholder="0.00" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Preț cost (lei)</label>
                    <input class="form-input" type="number" name="cost" step="0.01" value="<?php echo $product ? $product['cost'] : ''; ?>" placeholder="0.00">
                </div>
            </div>

            <div class="form-grid">
                <div class="form-group">
                    <label class="form-label">Stoc curent</label>
                    <input class="form-input" type="number" name="stock" value="<?php echo $product ? $product['stock'] : '0'; ?>" min="0">
                </div>
                <div class="form-group">
                    <label class="form-label">Alertă stoc minim</label>
                    <input class="form-input" type="number" name="min_stock" value="<?php echo $product ? $product['min_stock'] : '5'; ?>" min="0">
                </div>
            </div>

            <div class="form-grid">
                <div class="form-group">
                    <label class="form-label">Categorie *</label>
                    <select class="form-select form-input" name="category_id" required>
                        <?php foreach ($categories as $cat): ?>
                            <option value="<?php echo $cat['id']; ?>" <?php echo $product && $product['category_id'] == $cat['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($cat['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">SKU / Cod</label>
                    <input class="form-input" name="sku" value="<?php echo $product ? htmlspecialchars($product['sku'] ?? '') : ''; ?>" placeholder="FAR-001">
                </div>
            </div>

            <div class="form-group full">
                <label class="form-label">Descriere</label>
                <textarea class="form-input" name="description" placeholder="Descrierea produsului"><?php echo $product ? htmlspecialchars($product['description'] ?? '') : ''; ?></textarea>
            </div>

            <?php if ($product): ?>
                <div class="form-group full" style="border-top:1px solid var(--border);padding-top:14px">
                    <label class="form-label">Imagine Produs</label>
                    <?php if ($product['image_path'] && file_exists(__DIR__ . '/../uploads/' . $product['image_path'])): ?>
                        <div style="margin-bottom:10px">
                            <img src="<?php echo APP_URL . '/uploads/' . urlencode($product['image_path']); ?>" alt="<?php echo htmlspecialchars($product['name']); ?>" style="max-width:200px;max-height:200px;border-radius:8px;border:1px solid var(--border)">
                        </div>
                    <?php endif; ?>
                    <div class="form-group">
                        <label class="form-label">Selectează imagine (JPG, PNG, GIF, WebP - max 5MB)</label>
                        <input type="file" id="imageInput" name="test_image" accept="image/jpeg,image/png,image/gif,image/webp" style="display:block;width:100%;margin-bottom:10px;padding:8px;background:var(--bg3);border:1px solid var(--border);border-radius:6px;color:var(--text);cursor:pointer;font-family:'DM Sans',sans-serif;font-size:13px">
                    </div>
                    <button type="button" id="uploadImageBtn" class="btn btn-secondary" style="width:100%">📤 Încarcă imagine</button>
                    <div id="uploadStatus" style="margin-top:10px;font-size:13px;padding:8px;border-radius:6px;display:none" role="alert"></div>
                </div>
            <?php endif; ?>

            <div class="form-group">
                <label class="form-label">Status</label>
                <select class="form-select form-input" name="active">
                    <option value="1" <?php echo !$product || $product['active'] ? 'selected' : ''; ?>>Activ</option>
                    <option value="0" <?php echo $product && !$product['active'] ? 'selected' : ''; ?>>Inactiv</option>
                </select>
            </div>

            <div style="display:flex;gap:10px;margin-top:20px">
                <a href="<?php echo APP_URL; ?>/admin/products.php" class="btn btn-ghost" style="flex:1;text-align:center;text-decoration:none">Anulează</a>
                <button type="submit" class="btn btn-primary" style="flex:1">✓ Salvează</button>
            </div>
        </form>
    </div>
</div>

<?php if ($product): ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const uploadBtn = document.getElementById('uploadImageBtn');
    const fileInput = document.getElementById('imageInput');
    const statusDiv = document.getElementById('uploadStatus');
    
    if (!uploadBtn) {
        console.error('Upload button not found');
        return;
    }
    
    uploadBtn.addEventListener('click', async function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        const file = fileInput.files[0];
        
        if (!file) {
            statusDiv.style.display = 'block';
            statusDiv.style.background = 'rgba(224,82,82,0.1)';
            statusDiv.style.color = 'var(--red)';
            statusDiv.style.border = '1px solid rgba(224,82,82,0.3)';
            statusDiv.innerHTML = '❌ <strong>Selectează un fișier</strong>';
            return;
        }
        
        console.log('File selected:', file.name, file.type, file.size);
        
        const maxSize = 5 * 1024 * 1024; // 5MB
        if (file.size > maxSize) {
            statusDiv.style.display = 'block';
            statusDiv.style.background = 'rgba(224,82,82,0.1)';
            statusDiv.style.color = 'var(--red)';
            statusDiv.style.border = '1px solid rgba(224,82,82,0.3)';
            statusDiv.innerHTML = '❌ <strong>Fișierul e prea mare</strong> (max 5MB, ai ' + (file.size / 1024 / 1024).toFixed(2) + 'MB)';
            return;
        }
        
        uploadBtn.disabled = true;
        statusDiv.style.display = 'block';
        statusDiv.style.background = 'rgba(74,143,212,0.1)';
        statusDiv.style.color = 'var(--text2)';
        statusDiv.style.border = '1px solid rgba(74,143,212,0.3)';
        statusDiv.innerHTML = '⏳ <strong>Se încarcă...</strong>';
        
        const formData = new FormData();
        formData.append('product_id', <?php echo $product['id']; ?>);
        formData.append('image', file);
        
        console.log('Uploading to: <?php echo APP_URL; ?>/api/upload-image.php');
        
        try {
            const response = await fetch('<?php echo APP_URL; ?>/api/upload-image.php', {
                method: 'POST',
                body: formData
            });
            
            console.log('Response status:', response.status);
            const text = await response.text();
            console.log('Response text:', text);
            
            let data;
            try {
                data = JSON.parse(text);
            } catch (e) {
                console.error('JSON parse error:', e);
                statusDiv.style.background = 'rgba(224,82,82,0.1)';
                statusDiv.style.color = 'var(--red)';
                statusDiv.style.border = '1px solid rgba(224,82,82,0.3)';
                statusDiv.innerHTML = '❌ <strong>Eroare server</strong> (response invalid). Mergi la: <a href="<?php echo APP_URL; ?>/test-upload.php" target="_blank" style="color:inherit">test-upload.php</a>';
                uploadBtn.disabled = false;
                return;
            }
            
            if (data.success) {
                statusDiv.style.background = 'rgba(61,184,122,0.1)';
                statusDiv.style.color = 'var(--green)';
                statusDiv.style.border = '1px solid rgba(61,184,122,0.3)';
                statusDiv.innerHTML = '✓ <strong>Imagine încărcată cu succes!</strong>';
                setTimeout(() => location.reload(), 1500);
            } else {
                statusDiv.style.background = 'rgba(224,82,82,0.1)';
                statusDiv.style.color = 'var(--red)';
                statusDiv.style.border = '1px solid rgba(224,82,82,0.3)';
                statusDiv.innerHTML = '❌ <strong>' + (data.error || 'Eroare necunoscută') + '</strong>';
                console.error('API error:', data);
                uploadBtn.disabled = false;
            }
        } catch (error) {
            console.error('Fetch error:', error);
            statusDiv.style.background = 'rgba(224,82,82,0.1)';
            statusDiv.style.color = 'var(--red)';
            statusDiv.style.border = '1px solid rgba(224,82,82,0.3)';
            statusDiv.innerHTML = '❌ <strong>Eroare de conexiune:</strong> ' + error.message;
            uploadBtn.disabled = false;
        }
    });
});
</script>
<?php endif; ?>

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