<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload Product - Flex Market</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        * {
            font-family: 'Poppins', sans-serif;
        }
        .upload-container {
            max-width: 900px;
            margin: 50px auto;
        }
        .image-preview {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            margin-top: 15px;
        }
        .image-preview img {
            width: 100px;
            height: 100px;
            object-fit: cover;
            border-radius: 8px;
            border: 2px solid #ddd;
        }
        .rental-fields {
            display: none;
        }
    </style>
</head>
<body class="bg-light">
    <div class="container upload-container">
        <div class="card shadow-lg border-0">
            <div class="card-header bg-primary text-white">
                <h4 class="mb-0"><i class="bi bi-upload"></i> Upload Product</h4>
            </div>
            <div class="card-body p-4">
                <?php if (session()->getFlashdata('success')): ?>
                    <div class="alert alert-success"><?= session()->getFlashdata('success') ?></div>
                <?php endif; ?>

                <?php if (session()->getFlashdata('error')): ?>
                    <div class="alert alert-danger"><?= session()->getFlashdata('error') ?></div>
                <?php endif; ?>

                <form id="uploadForm" enctype="multipart/form-data">
                    <?= csrf_field() ?>

                    <!-- Listing Type -->
                    <div class="mb-3">
                        <label class="form-label">Listing Type <span class="text-danger">*</span></label>
                        <div class="btn-group w-100" role="group">
                            <input type="radio" class="btn-check" name="listing_type" id="sell" value="sell" checked>
                            <label class="btn btn-outline-primary" for="sell">
                                <i class="bi bi-currency-rupee"></i> Sell
                            </label>
                            
                            <input type="radio" class="btn-check" name="listing_type" id="rent" value="rent">
                            <label class="btn btn-outline-info" for="rent">
                                <i class="bi bi-clock-history"></i> Rent
                            </label>
                        </div>
                    </div>

                    <!-- Brand Selection -->
                    <?php if (count($brands) > 0): ?>
                    <div class="mb-3">
                        <label class="form-label">Brand (Optional)</label>
                        <select class="form-select" name="brand_id">
                            <option value="">No Brand</option>
                            <?php foreach ($brands as $brand): ?>
                                <option value="<?= $brand['id'] ?>"><?= esc($brand['brand_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <?php endif; ?>

                    <?php if ($canCreateBrand && count($brands) == 0): ?>
                    <div class="alert alert-info">
                        <i class="bi bi-info-circle"></i> You can create your own brand now! Your reliability score is >=25.
                        <button type="button" class="btn btn-sm btn-primary float-end" data-bs-toggle="modal" data-bs-target="#brandModal">
                            Create Brand
                        </button>
                    </div>
                    <?php endif; ?>

                    <div class="row">
                        <!-- Title -->
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Product Title <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="title" required>
                        </div>

                        <!-- Category -->
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Category <span class="text-danger">*</span></label>
                            <select class="form-select" name="category" required>
                                <option value="">Select Category</option>
                                <option value="Electronics">Electronics</option>
                                <option value="Fashion">Fashion</option>
                                <option value="Home & Living">Home & Living</option>
                                <option value="Books">Books</option>
                                <option value="Sports">Sports & Fitness</option>
                                <option value="Toys">Toys & Games</option>
                                <option value="Furniture">Furniture</option>
                                <option value="Others">Others</option>
                            </select>
                        </div>
                    </div>

                    <!-- Description -->
                    <div class="mb-3">
                        <label class="form-label">Description <span class="text-danger">*</span></label>
                        <textarea class="form-control" name="description" rows="4" required></textarea>
                    </div>

                    <div class="row">
                        <!-- Size -->
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Size (if applicable)</label>
                            <input type="text" class="form-control" name="size" placeholder="e.g., M, L, XL">
                        </div>

                        <!-- Color -->
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Color (if applicable)</label>
                            <input type="text" class="form-control" name="color" placeholder="e.g., Red, Blue">
                        </div>

                        <!-- Price for Sell -->
                        <div class="col-md-4 mb-3 sell-field">
                            <label class="form-label">Selling Price <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <span class="input-group-text">₹</span>
                                <input type="number" class="form-control" name="price" step="0.01" required>
                            </div>
                        </div>
                    </div>

                    <!-- Rental Fields (Hidden by default) -->
                    <div class="rental-fields">
                        <div class="alert alert-info">
                            <strong>Rental Details:</strong> Fill in the rental cost and deposit information.
                        </div>
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Rental Cost (per day)</label>
                                <div class="input-group">
                                    <span class="input-group-text">₹</span>
                                    <input type="number" class="form-control" name="rental_cost" step="0.01">
                                </div>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Deposit Amount</label>
                                <div class="input-group">
                                    <span class="input-group-text">₹</span>
                                    <input type="number" class="form-control" name="rental_deposit" step="0.01">
                                </div>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Fitting Charge</label>
                                <div class="input-group">
                                    <span class="input-group-text">₹</span>
                                    <input type="number" class="form-control" name="fitting_charge" step="0.01">
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Product Images -->
                    <div class="mb-3">
                        <label class="form-label">Product Images (Max 7) <span class="text-danger">*</span></label>
                        <input type="file" class="form-control" name="product_images[]" multiple accept="image/*" id="productImages" required>
                        <small class="text-muted">Select up to 7 images. Max 2MB per image.</small>
                        <div id="imagePreview" class="image-preview"></div>
                    </div>

                    <!-- Bill Upload -->
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="hasBill" name="has_bill">
                            <label class="form-check-label" for="hasBill">
                                I have the original bill
                            </label>
                        </div>
                        <div id="billUploadSection" style="display: none;" class="mt-2">
                            <input type="file" class="form-control" name="bill_image" accept="image/*">
                            <small class="text-muted">Upload a clear photo of the bill</small>
                        </div>
                    </div>

                    <div class="d-grid gap-2">
                        <button type="submit" class="btn btn-primary btn-lg">
                            <i class="bi bi-cloud-upload"></i> Upload Product
                        </button>
                        <a href="<?= base_url('seller/dashboard') ?>" class="btn btn-outline-secondary">
                            <i class="bi bi-arrow-left"></i> Back to Dashboard
                        </a>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Toggle rental fields
        document.querySelectorAll('input[name="listing_type"]').forEach(radio => {
            radio.addEventListener('change', function() {
                const rentalFields = document.querySelector('.rental-fields');
                if (this.value === 'rent') {
                    rentalFields.style.display = 'block';
                } else {
                    rentalFields.style.display = 'none';
                }
            });
        });

        // Toggle bill upload
        document.getElementById('hasBill').addEventListener('change', function() {
            document.getElementById('billUploadSection').style.display = this.checked ? 'block' : 'none';
        });

        // Image preview
        document.getElementById('productImages').addEventListener('change', function() {
            const preview = document.getElementById('imagePreview');
            preview.innerHTML = '';
            
            if (this.files.length > 7) {
                alert('Maximum 7 images allowed');
                this.value = '';
                return;
            }
            
            Array.from(this.files).forEach(file => {
                if (file.type.startsWith('image/')) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        const img = document.createElement('img');
                        img.src = e.target.result;
                        preview.appendChild(img);
                    };
                    reader.readAsDataURL(file);
                }
            });
        });

        // Form submission
        document.getElementById('uploadForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const submitBtn = this.querySelector('button[type="submit"]');
            
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Uploading...';
            
            fetch('/seller/process-upload', {
                method: 'POST',
                body: formData
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    window.location.href = '/seller/dashboard';
                } else {
                    alert('Error: ' + (data.message || 'Upload failed'));
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = '<i class="bi bi-cloud-upload"></i> Upload Product';
                }
            })
            .catch(err => {
                alert('Error uploading product');
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="bi bi-cloud-upload"></i> Upload Product';
            });
        });
    </script>
</body>
</html>
