<!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">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        * { font-family: 'Poppins', sans-serif; }
        body { background: #f5f5f5; }
        .sidebar {
            min-height: 100vh;
            background: linear-gradient(180deg, #9c27b0 0%, #673ab7 100%);
            box-shadow: 2px 0 10px rgba(0,0,0,0.1);
        }
        .sidebar .nav-link {
            color: rgba(255,255,255,0.85);
            padding: 14px 20px;
            border-radius: 10px;
            margin: 6px 0;
            transition: all 0.3s;
        }
        .sidebar .nav-link:hover, .sidebar .nav-link.active {
            background: rgba(255,255,255,0.15);
            color: #fff;
            transform: translateX(5px);
        }
        .sidebar .nav-link i { margin-right: 10px; width: 20px; }
        .upload-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 2px 20px rgba(0,0,0,0.08);
        }
        .form-section {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        .price-suggestion {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px;
            border-radius: 10px;
            margin-top: 10px;
        }
        .image-preview-container {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
            gap: 10px;
            margin-top: 15px;
        }
        .image-preview-item {
            position: relative;
            padding-top: 100%;
            border-radius: 8px;
            overflow: hidden;
            border: 2px solid #e0e0e0;
        }
        .image-preview-item img {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        .image-preview-item .remove-btn {
            position: absolute;
            top: 5px;
            right: 5px;
            background: rgba(255,0,0,0.8);
            color: white;
            border: none;
            border-radius: 50%;
            width: 25px;
            height: 25px;
            cursor: pointer;
        }
        .rental-section { display: none; }
        .subscription-alert {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <?php include 'sidebar.php'; ?>

            <!-- Main Content -->
            <div class="col-md-9 col-lg-10 p-4">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <div>
                        <h2><i class="bi bi-cloud-upload"></i> Upload New Product</h2>
                        <p class="text-muted mb-0">Fill in the details below to list your product</p>
                    </div>
                    <a href="<?= base_url('seller/dashboard') ?>" class="btn btn-outline-secondary">
                        <i class="bi bi-arrow-left"></i> Back
                    </a>
                </div>

                <!-- Subscription Alert -->
                <?php 
                    $uploadedCount = $user['products_uploaded_count'] ?? 0;
                    $tier = $user['subscription_tier'] ?? 'free';
                    $limits = [
                        'free' => ['max' => 3, 'price' => 0],
                        'basic' => ['max' => 10, 'price' => 99],
                        'pro' => ['max' => 50, 'price' => 299]
                    ];
                    $currentLimit = $limits[$tier];
                    $remaining = $currentLimit['max'] - $uploadedCount;
                ?>
                <?php if ($remaining <= 0): ?>
                    <div class="subscription-alert">
                        <h5><i class="bi bi-exclamation-triangle"></i> Upload Limit Reached!</h5>
                        <p class="mb-0">You've used all <?= $currentLimit['max'] ?> uploads in your <?= ucfirst($tier) ?> plan. 
                        <a href="<?= base_url('seller/subscription') ?>" class="text-white text-decoration-underline"><strong>Upgrade now</strong></a> to upload more products!</p>
                    </div>
                <?php elseif ($remaining <= 1): ?>
                    <div class="alert alert-warning">
                        <i class="bi bi-info-circle"></i> Only <strong><?= $remaining ?></strong> upload(s) remaining in your <?= ucfirst($tier) ?> plan. 
                        <a href="<?= base_url('seller/subscription') ?>">Upgrade now</a>
                    </div>
                <?php endif; ?>

                <form id="uploadForm" enctype="multipart/form-data" class="upload-card p-4">
                    <?= csrf_field() ?>

                    <!-- Listing Type -->
                    <div class="form-section">
                        <h5 class="mb-3"><i class="bi bi-tag"></i> Listing Type</h5>
                        <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>

                    <!-- Basic Details -->
                    <div class="form-section">
                        <h5 class="mb-3"><i class="bi bi-info-circle"></i> Basic Details</h5>
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label">Product Title <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="title" required>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Gender</label>
                                <select class="form-select" name="gender">
                                    <option value="">Select</option>
                                    <option value="Male">Male</option>
                                    <option value="Female">Female</option>
                                    <option value="Unisex">Unisex</option>
                                    <option value="Kids">Kids</option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Listing Type <span class="text-danger">*</span></label>
                                <select class="form-select" name="listing_type_category" id="listingTypeCategory" required>
                                    <option value="">Select Type</option>
                                    <option value="Clothing">Clothing</option>
                                    <option value="Accessories">Accessories</option>
                                    <option value="Electronics">Electronics</option>
                                    <option value="Home & Living">Home & Living</option>
                                    <option value="Sports & Fitness">Sports & Fitness</option>
                                    <option value="Others">Others</option>
                                </select>
                                <small class="text-muted">This will be dynamic in future</small>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Product Type <span class="text-danger">*</span></label>
                                <select class="form-select" name="product_type" id="productType" required>
                                    <option value="">Select Product Type</option>
                                    <option value="Shirt">Shirt</option>
                                    <option value="Dress">Dress</option>
                                    <option value="Pants">Pants</option>
                                    <option value="Shoes">Shoes</option>
                                    <option value="Watch">Watch</option>
                                    <option value="Bag">Bag</option>
                                </select>
                                <small class="text-muted">Depends on Listing Type</small>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Category <span class="text-danger">*</span></label>
                                <select class="form-select" name="category" id="category" required>
                                    <option value="">Select Category</option>
                                    <option value="Fashion">Fashion</option>
                                    <option value="Electronics">Electronics</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>
                                <small class="text-muted">Depends on Product Type</small>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Sub-Category</label>
                                <select class="form-select" name="sub_category" id="subCategory">
                                    <option value="">Select Sub-Category</option>
                                    <option value="Casual Wear">Casual Wear</option>
                                    <option value="Formal Wear">Formal Wear</option>
                                    <option value="Party Wear">Party Wear</option>
                                    <option value="Sports Wear">Sports Wear</option>
                                </select>
                                <small class="text-muted">Depends on Category</small>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Brand</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>
                            <div class="col-md-12">
                                <label class="form-label">Description <span class="text-danger">*</span></label>
                                <textarea class="form-control" name="description" rows="4" required></textarea>
                            </div>
                        </div>
                    </div>

                    <!-- Product Specifications -->
                    <div class="form-section">
                        <h5 class="mb-3"><i class="bi bi-rulers"></i> Specifications</h5>
                        <div class="row g-3">
                            <div class="col-md-3">
                                <label class="form-label">Size</label>
                                <input type="text" class="form-control" name="size" placeholder="e.g., M, L, XL">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Color</label>
                                <input type="text" class="form-control" name="color" placeholder="e.g., Red, Blue">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Number of times - used <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" name="used_times" id="usedTimes" min="0" value="0" required>
                                <small class="text-muted">Enter 0 if brand new</small>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Original Price <span class="text-danger">*</span></label>
                                <div class="input-group">
                                    <span class="input-group-text">₹</span>
                                    <input type="number" class="form-control" name="original_price" id="originalPrice" step="0.01" required>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Pricing Section (Sell) -->
                    <div class="form-section sell-section">
                        <h5 class="mb-3"><i class="bi bi-currency-rupee"></i> Sale Pricing</h5>
                        <div class="row g-3">
                            <div class="col-md-12">
                                <button type="button" class="btn btn-sm btn-primary" id="calculateSalePrice">
                                    <i class="bi bi-calculator"></i> Calculate Suggested Price
                                </button>
                                <div id="salePriceSuggestion" class="price-suggestion" style="display: none;">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <small>Suggested Sale Price</small>
                                            <h4 class="mb-0">₹<span id="suggestedSalePrice">0</span></h4>
                                        </div>
                                        <button type="button" class="btn btn-light btn-sm" id="useSuggestedSale">Use This Price</button>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Sale 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" id="salePrice" step="0.01">
                                </div>
                                <small class="text-muted">Must be at least 5% less than original price</small>
                                <div id="salePriceError" class="text-danger small" style="display: none;"></div>
                            </div>
                        </div>
                    </div>

                    <!-- Pricing Section (Rent) -->
                    <div class="form-section rental-section">
                        <h5 class="mb-3"><i class="bi bi-clock-history"></i> Rental Pricing</h5>
                        <div class="row g-3">
                            <div class="col-md-12">
                                <button type="button" class="btn btn-sm btn-info" id="calculateRentalPrice">
                                    <i class="bi bi-calculator"></i> Calculate Suggested Prices
                                </button>
                                <div id="rentalPriceSuggestion" class="price-suggestion" style="display: none;">
                                    <div class="row">
                                        <div class="col-md-6 mb-2">
                                            <small>Suggested Deposit</small>
                                            <h5>₹<span id="suggestedDeposit">0</span></h5>
                                        </div>
                                        <div class="col-md-6 mb-2">
                                            <small>Suggested Rental Cost (per day)</small>
                                            <h5>₹<span id="suggestedRental">0</span></h5>
                                        </div>
                                    </div>
                                    <button type="button" class="btn btn-light btn-sm mt-2" id="useSuggestedRental">Use These Prices</button>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <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" id="rentalCost" step="0.01">
                                </div>
                                <small class="text-muted">Max 40% of deposit</small>
                                <div id="rentalCostError" class="text-danger small" style="display: none;"></div>
                            </div>
                            <div class="col-md-4">
                                <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" id="rentalDeposit" step="0.01">
                                </div>
                                <small class="text-muted">At least 10% less than original</small>
                                <div id="depositError" class="text-danger small" style="display: none;"></div>
                            </div>
                            <div class="col-md-4">
                                <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 class="col-md-12">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="allow_alter_fitting" id="allowFitting" value="1">
                                    <label class="form-check-label" for="allowFitting">
                                        Allow buyer to alter the fitting
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Dispatch Address -->
                    <div class="form-section">
                        <h5 class="mb-3"><i class="bi bi-geo-alt"></i> Dispatch Address</h5>
                        <div class="row g-3">
                            <div class="col-md-9">
                                <label class="form-label">Dispatch From <span class="text-danger">*</span></label>
                                <textarea class="form-control" name="dispatch_address" rows="2" required><?= esc($user['address'] ?? '') ?></textarea>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">PIN Code <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="dispatch_pin_code" value="<?= esc($user['pin_code'] ?? '') ?>" required>
                            </div>
                        </div>
                    </div>

                    <!-- Product Images -->
                    <div class="form-section">
                        <h5 class="mb-3"><i class="bi bi-images"></i> Product Images</h5>
                        <input type="file" class="form-control" name="product_images[]" multiple accept="image/*" id="productImages" required>
                        <small class="text-muted">Upload up to 7 images (Max 2MB each)</small>
                        <div id="imagePreview" class="image-preview-container"></div>
                    </div>

                    <!-- Bill Upload -->
                    <div class="form-section">
                        <h5 class="mb-3"><i class="bi bi-receipt"></i> Bill (Optional)</h5>
                        <div class="form-check mb-3">
                            <input class="form-check-input" type="checkbox" id="hasBill" name="has_bill" value="1">
                            <label class="form-check-label" for="hasBill">
                                I have the original bill/invoice
                            </label>
                        </div>
                        <div id="billUploadSection" style="display: none;">
                            <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>
                    </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/sell sections
        document.querySelectorAll('input[name="listing_type"]').forEach(radio => {
            radio.addEventListener('change', function() {
                if (this.value === 'rent') {
                    document.querySelector('.rental-section').style.display = 'block';
                    document.querySelector('.sell-section').style.display = 'none';
                    document.getElementById('salePrice').removeAttribute('required');
                } else {
                    document.querySelector('.rental-section').style.display = 'none';
                    document.querySelector('.sell-section').style.display = 'block';
                    document.getElementById('salePrice').setAttribute('required', 'required');
                }
            });
        });

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

        // Calculate suggested sale price
        document.getElementById('calculateSalePrice').addEventListener('click', function() {
            const original = parseFloat(document.getElementById('originalPrice').value) || 0;
            const usedTimes = parseInt(document.getElementById('usedTimes').value) || 0;
            
            if (original <= 0) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Missing Information',
                    text: 'Please enter original price first',
                    confirmButtonColor: '#9c27b0'
                });
                return;
            }

            // Calculate depreciation
            let depPercent = 5 + Math.min(usedTimes * 2, 45);
            let suggested = original * (1 - (depPercent / 100));
            suggested = Math.min(suggested, original * 0.95);

            document.getElementById('suggestedSalePrice').textContent = suggested.toFixed(2);
            document.getElementById('salePriceSuggestion').style.display = 'block';
        });

        // Use suggested sale price
        document.getElementById('useSuggestedSale').addEventListener('click', function() {
            const suggested = document.getElementById('suggestedSalePrice').textContent;
            document.getElementById('salePrice').value = suggested;
        });

        // Calculate rental prices
        document.getElementById('calculateRentalPrice').addEventListener('click', function() {
            const original = parseFloat(document.getElementById('originalPrice').value) || 0;
            const usedTimes = parseInt(document.getElementById('usedTimes').value) || 0;
            
            if (original <= 0) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Missing Information',
                    text: 'Please enter original price first',
                    confirmButtonColor: '#9c27b0'
                });
                return;
            }

            // Calculate deposit (at least 10% less than original)
            let depositPercent = 90 - Math.min(usedTimes, 10);
            let deposit = original * (depositPercent / 100);
            deposit = Math.min(deposit, original * 0.90);

            // Calculate rental (30-40% of deposit based on usage)
            let rentalPercent = 30 + Math.min(usedTimes * 0.5, 10);
            let rental = deposit * (rentalPercent / 100);
            rental = Math.min(rental, deposit * 0.40);

            document.getElementById('suggestedDeposit').textContent = deposit.toFixed(2);
            document.getElementById('suggestedRental').textContent = rental.toFixed(2);
            document.getElementById('rentalPriceSuggestion').style.display = 'block';
        });

        // Use suggested rental prices
        document.getElementById('useSuggestedRental').addEventListener('click', function() {
            document.getElementById('rentalDeposit').value = document.getElementById('suggestedDeposit').textContent;
            document.getElementById('rentalCost').value = document.getElementById('suggestedRental').textContent;
        });

        // Validate sale price
        document.getElementById('salePrice').addEventListener('input', function() {
            const original = parseFloat(document.getElementById('originalPrice').value) || 0;
            const sale = parseFloat(this.value) || 0;
            const maxAllowed = original * 0.95;
            const errorDiv = document.getElementById('salePriceError');

            if (sale > maxAllowed) {
                errorDiv.textContent = `Sale price must be ≤ ₹${maxAllowed.toFixed(2)} (95% of original)`;
                errorDiv.style.display = 'block';
                this.setCustomValidity('Price too high');
            } else {
                errorDiv.style.display = 'none';
                this.setCustomValidity('');
            }
        });

        // Validate deposit
        document.getElementById('rentalDeposit').addEventListener('input', function() {
            const original = parseFloat(document.getElementById('originalPrice').value) || 0;
            const deposit = parseFloat(this.value) || 0;
            const maxAllowed = original * 0.90;
            const errorDiv = document.getElementById('depositError');

            if (deposit > maxAllowed) {
                errorDiv.textContent = `Deposit must be ≤ ₹${maxAllowed.toFixed(2)} (90% of original)`;
                errorDiv.style.display = 'block';
                this.setCustomValidity('Deposit too high');
            } else {
                errorDiv.style.display = 'none';
                this.setCustomValidity('');
            }
        });

        // Validate rental cost
        document.getElementById('rentalCost').addEventListener('input', function() {
            const deposit = parseFloat(document.getElementById('rentalDeposit').value) || 0;
            const rental = parseFloat(this.value) || 0;
            const maxAllowed = deposit * 0.40;
            const errorDiv = document.getElementById('rentalCostError');

            if (rental > maxAllowed) {
                errorDiv.textContent = `Rental cost must be ≤ ₹${maxAllowed.toFixed(2)} (40% of deposit)`;
                errorDiv.style.display = 'block';
                this.setCustomValidity('Rental cost too high');
            } else {
                errorDiv.style.display = 'none';
                this.setCustomValidity('');
            }
        });

        // Image preview
        let selectedFiles = [];
        document.getElementById('productImages').addEventListener('change', function(e) {
            const files = Array.from(e.target.files);
            
            if (files.length > 7) {
                Swal.fire({
                    icon: 'error',
                    title: 'Too Many Images',
                    text: 'Maximum 7 images allowed',
                    confirmButtonColor: '#9c27b0'
                });
                this.value = '';
                return;
            }

            selectedFiles = files;
            const preview = document.getElementById('imagePreview');
            preview.innerHTML = '';
            
            files.forEach((file, index) => {
                if (file.type.startsWith('image/')) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        const div = document.createElement('div');
                        div.className = 'image-preview-item';
                        div.innerHTML = `
                            <img src="${e.target.result}" alt="Product ${index + 1}">
                            <button type="button" class="remove-btn" onclick="removeImage(${index})">×</button>
                        `;
                        preview.appendChild(div);
                    };
                    reader.readAsDataURL(file);
                }
            });
        });

        function removeImage(index) {
            selectedFiles.splice(index, 1);
            const dataTransfer = new DataTransfer();
            selectedFiles.forEach(file => dataTransfer.items.add(file));
            document.getElementById('productImages').files = dataTransfer.files;
            document.getElementById('productImages').dispatchEvent(new Event('change'));
        }

        // 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) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success!',
                        text: data.message || 'Product uploaded successfully',
                        confirmButtonColor: '#9c27b0',
                        timer: 2000
                    }).then(() => {
                        window.location.href = '/seller/products';
                    });
                } else {
                    let errorMessage = data.message || 'Upload failed';
                    
                    // Show detailed validation errors if present
                    if (data.errors) {
                        errorMessage = '<ul style="text-align: left;">';
                        for (let field in data.errors) {
                            errorMessage += `<li>${data.errors[field]}</li>`;
                        }
                        errorMessage += '</ul>';
                    }
                    
                    Swal.fire({
                        icon: 'error',
                        title: 'Upload Failed',
                        html: errorMessage,
                        confirmButtonColor: '#9c27b0'
                    });
                    
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = '<i class="bi bi-cloud-upload"></i> Upload Product';
                }
            })
            .catch(err => {
                console.error(err);
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'An error occurred while uploading product',
                    confirmButtonColor: '#9c27b0'
                });
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="bi bi-cloud-upload"></i> Upload Product';
            });
        });
    </script>
</body>
</html>
