<?php
/**
 * ============================================================================
 * marketplace/add-product.php - Add New Product
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

requireLogin();

// Only farmers can add products
if (getUserType() !== 'farmer') {
    redirect('/marketplace/', 'Only farmers can list products', 'error');
}

$pageTitle = 'Sell Product - Marketplace';
$userId = getUserId();

// Initialize database
$database = new Database();
$db = $database->getConnection();

// Get user's enterprises
$sql = "SELECT e.* FROM enterprises e
        JOIN farms f ON e.farm_id = f.id
        WHERE f.user_id = ?
        ORDER BY e.created_at DESC";
$stmt = $db->prepare($sql);
$stmt->execute([$userId]);
$enterprises = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Handle form submission
if (isPost()) {
    $productClass = new \App\Product($db);
    
    // Handle image uploads
    $uploadedImages = [];
    if (isset($_FILES['images']) && !empty($_FILES['images']['name'][0])) {
        foreach ($_FILES['images']['tmp_name'] as $key => $tmp_name) {
            if (!empty($tmp_name)) {
                $file = [
                    'name' => $_FILES['images']['name'][$key],
                    'type' => $_FILES['images']['type'][$key],
                    'tmp_name' => $tmp_name,
                    'error' => $_FILES['images']['error'][$key],
                    'size' => $_FILES['images']['size'][$key]
                ];
                
                $uploadResult = uploadFile($file, 'products', ALLOWED_IMAGE_TYPES);
                if ($uploadResult['success']) {
                    $uploadedImages[] = $uploadResult['path'];
                }
            }
        }
    }
    
    $data = [
        'seller_id' => $userId,
        'enterprise_id' => !empty($_POST['enterprise_id']) ? $_POST['enterprise_id'] : null,
        'product_name' => $_POST['product_name'],
        'category' => $_POST['category'],
        'description' => $_POST['description'],
        'quantity' => $_POST['quantity'],
        'unit' => $_POST['unit'],
        'price_per_unit' => $_POST['price_per_unit'],
        'location' => $_POST['location'],
        'images' => $uploadedImages
    ];
    
    $result = $productClass->create($data);
    
    if ($result['success']) {
        redirect('/marketplace/product-details.php?id=' . $result['product_id'], $result['message'], 'success');
    } else {
        setFlashMessage($result['message'], 'error');
    }
}

global $PRODUCT_CATEGORIES, $UNITS;

include_once __DIR__ . '/../includes/meta.php';
include_once __DIR__ . '/../includes/header.php';
?>

<div class="container-fluid py-4">
    <!-- Breadcrumb -->
    <nav aria-label="breadcrumb" class="mb-4">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="<?php echo APP_URL; ?>/dashboard/">Home</a></li>
            <li class="breadcrumb-item"><a href="<?php echo APP_URL; ?>/marketplace/">Marketplace</a></li>
            <li class="breadcrumb-item active">Sell Product</li>
        </ol>
    </nav>

    <div class="row justify-content-center">
        <div class="col-lg-8">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-bottom">
                    <h4 class="mb-0">
                        <i class="bi bi-plus-circle text-success"></i> List a Product for Sale
                    </h4>
                </div>
                <div class="card-body p-4">
                    <form method="POST" enctype="multipart/form-data" id="addProductForm">
                        
                        <!-- Product Images -->
                        <div class="mb-4">
                            <label class="form-label fw-semibold">
                                Product Images <span class="text-danger">*</span>
                            </label>
                            <input type="file" class="form-control" name="images[]" 
                                   id="productImages" accept="image/*" multiple required>
                            <small class="form-text text-muted">
                                Upload up to 5 images (JPG, PNG). First image will be the main display.
                            </small>
                            
                            <!-- Image Preview -->
                            <div id="imagePreview" class="mt-3 d-flex flex-wrap gap-2"></div>
                        </div>

                        <!-- Product Name -->
                        <div class="mb-3">
                            <label class="form-label fw-semibold">
                                Product Name <span class="text-danger">*</span>
                            </label>
                            <input type="text" class="form-control" name="product_name" 
                                   placeholder="e.g., Fresh Maize" required>
                        </div>

                        <!-- Category -->
                        <div class="mb-3">
                            <label class="form-label fw-semibold">
                                Category <span class="text-danger">*</span>
                            </label>
                            <select class="form-select" name="category" required>
                                <option value="">Select Category</option>
                                <?php foreach ($PRODUCT_CATEGORIES as $key => $cat): ?>
                                    <option value="<?php echo $key; ?>">
                                        <?php echo $cat['icon'] . ' ' . $cat['name']; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <!-- Link to Enterprise (Optional) -->
                        <?php if (!empty($enterprises)): ?>
                        <div class="mb-3">
                            <label class="form-label fw-semibold">
                                Link to Enterprise (Optional)
                            </label>
                            <select class="form-select" name="enterprise_id">
                                <option value="">Not linked to any enterprise</option>
                                <?php foreach ($enterprises as $enterprise): ?>
                                    <option value="<?php echo $enterprise['id']; ?>">
                                        <?php echo htmlspecialchars($enterprise['enterprise_name'] ?? ucfirst($enterprise['enterprise_type'])); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <small class="form-text text-muted">
                                Link this product to track it in your farm records
                            </small>
                        </div>
                        <?php endif; ?>

                        <!-- Description -->
                        <div class="mb-3">
                            <label class="form-label fw-semibold">
                                Description
                            </label>
                            <textarea class="form-control" name="description" rows="4" 
                                      placeholder="Describe your product, quality, harvest date, etc."></textarea>
                        </div>

                        <!-- Quantity and Unit -->
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label fw-semibold">
                                    Quantity Available <span class="text-danger">*</span>
                                </label>
                                <input type="number" class="form-control" name="quantity" 
                                       step="0.01" min="0.01" placeholder="e.g., 500" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-semibold">
                                    Unit <span class="text-danger">*</span>
                                </label>
                                <select class="form-select" name="unit" required>
                                    <option value="">Select Unit</option>
                                    <?php foreach ($UNITS as $key => $unit): ?>
                                        <option value="<?php echo $key; ?>"><?php echo $unit; ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>

                        <!-- Price -->
                        <div class="mb-3">
                            <label class="form-label fw-semibold">
                                Price per Unit (UGX) <span class="text-danger">*</span>
                            </label>
                            <input type="number" class="form-control" name="price_per_unit" 
                                   min="1" placeholder="e.g., 1500" required>
                            <small class="form-text text-muted">
                                Set a competitive price based on market rates
                            </small>
                        </div>

                        <!-- Location -->
                        <div class="mb-4">
                            <label class="form-label fw-semibold">
                                Location
                            </label>
                            <input type="text" class="form-control" name="location" 
                                   placeholder="e.g., Luuka District, Bukanga Subcounty">
                        </div>

                        <!-- Submit Buttons -->
                        <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                            <a href="<?php echo APP_URL; ?>/marketplace/" class="btn btn-outline-secondary">
                                <i class="bi bi-x-circle"></i> Cancel
                            </a>
                            <button type="submit" class="btn btn-success">
                                <i class="bi bi-check-circle"></i> List Product
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Tips Card -->
            <div class="card border-0 shadow-sm mt-4 bg-light">
                <div class="card-body">
                    <h5 class="mb-3">
                        <i class="bi bi-lightbulb text-warning"></i> Tips for Better Sales
                    </h5>
                    <ul class="mb-0">
                        <li class="mb-2">Upload clear, well-lit photos showing product quality</li>
                        <li class="mb-2">Write detailed descriptions including harvest date and quality</li>
                        <li class="mb-2">Price competitively based on current market rates</li>
                        <li class="mb-2">Respond quickly to buyer inquiries</li>
                        <li class="mb-2">Keep your product listings updated</li>
                        <li>Specify exact location for easier buyer access</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Image preview
document.getElementById('productImages').addEventListener('change', function(e) {
    const preview = document.getElementById('imagePreview');
    preview.innerHTML = '';
    
    const files = Array.from(e.target.files);
    
    if (files.length > 5) {
        showToast('Maximum 5 images allowed', 'warning');
        e.target.value = '';
        return;
    }
    
    files.forEach((file, index) => {
        if (file.type.startsWith('image/')) {
            const reader = new FileReader();
            reader.onload = function(e) {
                const div = document.createElement('div');
                div.className = 'position-relative';
                div.innerHTML = `
                    <img src="${e.target.result}" class="img-thumbnail" style="width: 120px; height: 120px; object-fit: cover;">
                    ${index === 0 ? '<span class="position-absolute top-0 start-0 badge bg-primary">Main</span>' : ''}
                `;
                preview.appendChild(div);
            };
            reader.readAsDataURL(file);
        }
    });
});

// Form validation
document.getElementById('addProductForm').addEventListener('submit', function(e) {
    const quantity = parseFloat(document.querySelector('[name="quantity"]').value);
    const price = parseFloat(document.querySelector('[name="price_per_unit"]').value);
    
    if (quantity <= 0) {
        e.preventDefault();
        showToast('Quantity must be greater than 0', 'error');
        return false;
    }
    
    if (price <= 0) {
        e.preventDefault();
        showToast('Price must be greater than 0', 'error');
        return false;
    }
    
    showLoading();
});
</script>

<?php
include_once __DIR__ . '/../includes/footer.php';
include_once __DIR__ . '/../includes/bottom-nav.php';
?>
