<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= esc($product['title']) ?> - Flex Market</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Poppins', sans-serif; background-color: #f8f9fa; }
        @media (min-width: 1400px) { .container { max-width: 1457px !important; } }
        .navbar { padding: 1.2rem 0; box-shadow: 0 2px 10px rgba(0,0,0,0.05); background: white; }
        .navbar-brand { font-weight: 700; font-size: 1.9rem; color: #000 !important; }
        .nav-link { font-weight: 500; color: #000 !important; padding: 0.5rem 1rem; }
        .nav-link:hover { color: #9c27b0 !important; }
        .btn-login { background: #9c27b0; color: white; border-radius: 25px; padding: 0.5rem 1.5rem; font-weight: 600; }
        .btn-login:hover { background: #7b1fa2; color: white; }
        
        .product-gallery { background: white; border-radius: 15px; padding: 20px; box-shadow: 0 2px 15px rgba(0,0,0,0.08); }
        .main-image { width: 100%; height: 500px; object-fit: contain; border-radius: 10px; background: #f5f5f5; }
        .thumbnail { width: 80px; height: 80px; object-fit: cover; border-radius: 8px; cursor: pointer; border: 2px solid transparent; }
        .thumbnail:hover, .thumbnail.active { border-color: #9c27b0; }
        
        .product-info { background: white; border-radius: 15px; padding: 30px; box-shadow: 0 2px 15px rgba(0,0,0,0.08); }
        .price-section { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 25px; border-radius: 12px; margin-bottom: 20px; }
        .price-main { font-size: 2.5rem; font-weight: 700; }
        .price-original { text-decoration: line-through; opacity: 0.8; }
        .seller-card { background: #f8f9fa; border-radius: 12px; padding: 20px; margin-top: 20px; }
        .btn-offer { background: #9c27b0; color: white; padding: 15px; border-radius: 10px; font-weight: 600; width: 100%; }
        .btn-offer:hover { background: #7b1fa2; color: white; }
        .spec-item { padding: 12px 0; border-bottom: 1px solid #e0e0e0; }
        .spec-item:last-child { border-bottom: none; }
        .badge-new { background: #4caf50; color: white; padding: 6px 12px; border-radius: 20px; }
        .badge-used { background: #ff9800; color: white; padding: 6px 12px; border-radius: 20px; }
    </style>
</head>
<body>
    <!-- Header -->
    <nav class="navbar navbar-expand-lg navbar-light sticky-top">
        <div class="container">
            <a class="navbar-brand" href="<?= base_url('buyer') ?>"><i class="bi bi-shop"></i> Flex Market</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto align-items-center">
                    <li class="nav-item"><a class="nav-link" href="<?= base_url('buyer') ?>">Home</a></li>
                    <?php if ($user): ?>
                        <li class="nav-item"><a class="nav-link" href="<?= base_url('buyer/my-offers') ?>">My Offers</a></li>
                        <li class="nav-item"><a class="nav-link" href="<?= base_url('buyer/transactions') ?>">Orders</a></li>
                        <li class="nav-item dropdown">
                            <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                                <i class="bi bi-person-circle"></i> <?= esc($user['name']) ?>
                            </a>
                            <ul class="dropdown-menu">
                                <li><a class="dropdown-item" href="<?= base_url('seller/dashboard') ?>"><i class="bi bi-shop"></i> Sell Products</a></li>
                                <li><hr class="dropdown-divider"></li>
                                <li><a class="dropdown-item" href="<?= base_url('auth/logout') ?>"><i class="bi bi-box-arrow-right"></i> Logout</a></li>
                            </ul>
                        </li>
                    <?php else: ?>
                        <li class="nav-item"><a href="<?= base_url('login') ?>" class="btn btn-login">Login / Sign Up</a></li>
                    <?php endif; ?>
                </ul>
            </div>
        </div>
    </nav>

    <!-- Product Details -->
    <div class="container mt-4">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="<?= base_url('buyer') ?>">Home</a></li>
                <li class="breadcrumb-item"><a href="<?= base_url('buyer?category=' . urlencode($product['category'])) ?>"><?= esc($product['category']) ?></a></li>
                <li class="breadcrumb-item active"><?= esc($product['title']) ?></li>
            </ol>
        </nav>

        <div class="row">
            <!-- Image Gallery -->
            <div class="col-lg-7">
                <div class="product-gallery">
                    <img src="<?= base_url(esc($images[0]['image_path'] ?? 'placeholder.jpg')) ?>" alt="Product" class="main-image mb-3" id="mainImage">
                    <div class="d-flex gap-2 flex-wrap">
                        <?php foreach ($images as $index => $image): ?>
                            <img src="<?= base_url(esc($image['image_path'])) ?>" class="thumbnail <?= $index === 0 ? 'active' : '' ?>" 
                                 onclick="changeImage(this.src, this)" alt="Thumbnail">
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>

            <!-- Product Info -->
            <div class="col-lg-5">
                <div class="product-info">
                    <h2 class="mb-3"><?= esc($product['title']) ?></h2>
                    
                    <?php if ($brand): ?>
                        <div class="mb-3">
                            <span class="badge bg-dark"><i class="bi bi-award"></i> <?= esc($brand['brand_name']) ?></span>
                        </div>
                    <?php endif; ?>

                    <!-- Price Section -->
                    <div class="price-section">
                        <?php if ($product['listing_type'] === 'sell'): ?>
                            <div class="price-main">₹<?= number_format($product['price'], 0) ?></div>
                            <?php if ($product['original_price'] > $product['price']): ?>
                                <div class="price-original">₹<?= number_format($product['original_price'], 0) ?></div>
                                <div class="mt-2">
                                    <span class="badge bg-success">
                                        <?= round((($product['original_price'] - $product['price']) / $product['original_price']) * 100) ?>% OFF
                                    </span>
                                </div>
                            <?php endif; ?>
                        <?php else: ?>
                            <div class="price-main">₹<?= number_format($product['rental_cost'], 0) ?><small style="font-size: 1rem;">/day</small></div>
                            <div class="mt-3">
                                <strong>Deposit:</strong> ₹<?= number_format($product['rental_deposit'], 0) ?>
                                <?php if ($product['fitting_charge'] > 0): ?>
                                    <br><strong>Fitting Charge:</strong> ₹<?= number_format($product['fitting_charge'], 0) ?>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    </div>

                    <!-- Specifications -->
                    <h6 class="mb-3">Specifications</h6>
                    <div class="mb-4">
                        <?php if ($product['size']): ?>
                            <div class="spec-item">
                                <strong>Size:</strong> <?= esc($product['size']) ?>
                            </div>
                        <?php endif; ?>
                        <?php if ($product['color']): ?>
                            <div class="spec-item">
                                <strong>Color:</strong> <?= esc($product['color']) ?>
                            </div>
                        <?php endif; ?>
                        <?php if ($product['gender']): ?>
                            <div class="spec-item">
                                <strong>Gender:</strong> <?= esc($product['gender']) ?>
                            </div>
                        <?php endif; ?>
                        <div class="spec-item">
                            <strong>Condition:</strong> 
                            <?php if ($product['used_times'] == 0): ?>
                                <span class="badge-new">Brand New</span>
                            <?php else: ?>
                                <span class="badge-used">Used <?= $product['used_times'] ?> times</span>
                            <?php endif; ?>
                        </div>
                        <?php if ($product['has_bill']): ?>
                            <div class="spec-item">
                                <strong><i class="bi bi-check-circle text-success"></i> Original Bill Available</strong>
                            </div>
                        <?php endif; ?>
                        <?php if ($product['listing_type'] === 'rent' && $product['allow_alter_fitting']): ?>
                            <div class="spec-item">
                                <strong><i class="bi bi-check-circle text-success"></i> Fitting Alteration Allowed</strong>
                            </div>
                        <?php endif; ?>
                    </div>

                    <!-- Action Buttons -->
                    <!-- <?php if ($user && ($user['id'] ?? 0) != ($product['seller_id'] ?? 0)): ?>
                        <button class="btn btn-offer mb-2" data-bs-toggle="modal" data-bs-target="#offerModal">
                            <i class="bi bi-tag"></i> Make an Offer
                        </button> -->
                        
                        <!-- Self-Delivery Mode Button -->
                        <button class="btn btn-outline-primary mb-2 w-100" onclick="viewSellerContact(<?= $product['id'] ?>)">
                            <i class="bi bi-telephone"></i> View Seller Contact (Self-Delivery)
                        </button>
                        
                        <!-- Fitting Alteration Request (for rentals only) -->
                        <?php if ($product['listing_type'] === 'rent' && $product['allow_alter_fitting']): ?>
                            <button class="btn btn-outline-secondary mb-2 w-100" data-bs-toggle="modal" data-bs-target="#fittingModal">
                                <i class="bi bi-scissors"></i> Request Fitting Alteration
                            </button>
                        <?php endif; ?>
                    <?php else: ?>
                        <a href="<?= base_url('login') ?>" class="btn btn-offer mb-2">
                            <i class="bi bi-box-arrow-in-right"></i> Login to Make Offer
                        </a>
                    <?php endif; ?>

                    <!-- Seller Info -->
                    <div class="seller-card">
                        <h6 class="mb-3">Seller Information</h6>
                        <div class="d-flex align-items-center mb-3">
                            <i class="bi bi-person-circle" style="font-size: 3rem; color: #9c27b0;"></i>
                            <div class="ms-3">
                                <strong>Verified Seller</strong><br>
                                <span class="badge bg-warning text-dark">
                                    <i class="bi bi-star-fill"></i> <?= number_format($seller['seller_reliability_score'], 1) ?> Rating
                                </span>
                            </div>
                        </div>
                        <p class="text-muted small mb-0">
                            <i class="bi bi-geo-alt"></i> Ships from: <?= esc($product['dispatch_pin_code']) ?> area
                        </p>
                        <small class="text-muted"><i class="bi bi-shield-check"></i> Contact details shared only after order confirmation</small>
                    </div>
                </div>
            </div>
        </div>

        <!-- Description -->
        <div class="row mt-4">
            <div class="col-12">
                <div class="product-info">
                    <h5 class="mb-3">Description</h5>
                    <p><?= nl2br(esc($product['description'])) ?></p>
                </div>
            </div>
        </div>

        <!-- Similar Products -->
        <?php if (!empty($similarProducts)): ?>
            <div class="mt-5">
                <h4 class="mb-4">Similar Products</h4>
                <div class="row">
                    <?php foreach ($similarProducts as $similar): ?>
                        <div class="col-md-3">
                            <div class="product-gallery text-center" onclick="window.location.href='<?= base_url('buyer/product/' . $similar['id']) ?>'" style="cursor: pointer;">
                                <img src="<?= base_url(esc($similar['primary_image'] ?? 'placeholder.jpg')) ?>" style="width: 100%; height: 200px; object-fit: cover; border-radius: 10px;">
                                <h6 class="mt-2"><?= esc($similar['title']) ?></h6>
                                <strong class="text-purple">₹<?= number_format($similar['price'] ?? $similar['rental_cost'], 0) ?></strong>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <!-- Make Offer Modal -->
    <div class="modal fade" id="offerModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Make an Offer</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="offerForm">
                    <div class="modal-body">
                        <input type="hidden" name="product_id" value="<?= $product['id'] ?>">
                        <input type="hidden" name="offer_type" value="<?= $product['listing_type'] === 'sell' ? 'buy' : 'rent' ?>">
                        
                        <div class="mb-3">
                            <label class="form-label">Your Offer Price</label>
                            <div class="input-group">
                                <span class="input-group-text">₹</span>
                                <input type="number" class="form-control" name="offered_price" required>
                            </div>
                            <small class="text-muted">
                                Asking: ₹<?= number_format($product['listing_type'] === 'sell' ? $product['price'] : $product['rental_cost'], 0) ?>
                            </small>
                        </div>

                        <?php if ($product['listing_type'] === 'rent'): ?>
                            <div class="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="deposit_amount" value="<?= $product['rental_deposit'] ?>" required>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Rental Start Date</label>
                                <input type="date" class="form-control" name="rental_start_date" min="<?= date('Y-m-d') ?>" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Rental End Date</label>
                                <input type="date" class="form-control" name="rental_end_date" min="<?= date('Y-m-d') ?>" required>
                            </div>
                        <?php endif; ?>

                        <div class="mb-3">
                            <label class="form-label">Message (Optional)</label>
                            <textarea class="form-control" name="message" rows="3" placeholder="Add a message to the seller..."></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-login">Send Offer</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Fitting Alteration Modal -->
    <div class="modal fade" id="fittingModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <form id="fittingForm">
                    <div class="modal-header">
                        <h5 class="modal-title"><i class="bi bi-scissors"></i> Request Fitting Alteration</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="product_id" value="<?= $product['id'] ?>">
                        <div class="mb-3">
                            <label class="form-label">Alteration Details <span class="text-danger">*</span></label>
                            <textarea class="form-control" name="alteration_details" rows="4" 
                                      placeholder="Describe the alterations you need (e.g., hem length, waist adjustment...)" 
                                      minlength="10" maxlength="500" required></textarea>
                            <small class="text-muted">Please provide clear details about the fitting changes you need.</small>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Send Request</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Seller Contact Modal (Self-Delivery) -->
    <div class="modal fade" id="contactModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="bi bi-telephone"></i> Seller Contact Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="contactDetails">
                    <div class="text-center">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-warning" onclick="showRatingModal()">
                        <i class="bi bi-star"></i> Rate Seller (Self-Delivery)
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Self-Delivery Rating Modal -->
    <div class="modal fade" id="ratingModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <form id="ratingForm">
                    <div class="modal-header">
                        <h5 class="modal-title"><i class="bi bi-star-fill"></i> Rate Seller (Self-Delivery)</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="seller_id" value="<?= $seller['id'] ?>">
                        <input type="hidden" name="product_id" value="<?= $product['id'] ?>">
                        
                        <div class="alert alert-info">
                            <i class="bi bi-info-circle"></i> <strong>Self-Delivery Rating</strong><br>
                            <small>This gives the seller +1 reliability star. You can only rate within 20 days of viewing contact.</small>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Comment (Optional)</label>
                            <textarea class="form-control" name="comment" rows="3" 
                                      placeholder="Share your experience with this seller..."></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-warning">
                            <i class="bi bi-star-fill"></i> Submit Rating (+1 Star)
                        </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>
        function changeImage(src, thumb) {
            document.getElementById('mainImage').src = src;
            document.querySelectorAll('.thumbnail').forEach(t => t.classList.remove('active'));
            thumb.classList.add('active');
        }

        // View Seller Contact (Self-Delivery Mode)
        function viewSellerContact(productId) {
            const contactModal = new bootstrap.Modal(document.getElementById('contactModal'));
            contactModal.show();
            
            fetch('/buyer/viewSellerContact/' + productId, {
                method: 'POST',
                headers: {'Content-Type': 'application/json'}
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    document.getElementById('contactDetails').innerHTML = `
                        <div class="alert alert-success">
                            <i class="bi bi-check-circle"></i> ${data.message}
                        </div>
                        <div class="card">
                            <div class="card-body">
                                <h6 class="card-title"><i class="bi bi-person"></i> ${data.seller.name}</h6>
                                <p class="mb-2"><i class="bi bi-telephone"></i> <strong>${data.seller.mobile}</strong></p>
                                <p class="mb-2"><i class="bi bi-geo-alt"></i> ${data.seller.address}</p>
                                <p class="mb-0"><i class="bi bi-mailbox"></i> PIN: ${data.seller.pin_code}</p>
                            </div>
                        </div>
                        <small class="text-muted mt-3 d-block">
                            <i class="bi bi-clock"></i> You can rate this seller within 20 days.
                        </small>
                    `;
                } else {
                    document.getElementById('contactDetails').innerHTML = `
                        <div class="alert alert-danger">${data.message}</div>
                    `;
                }
            })
            .catch(err => {
                document.getElementById('contactDetails').innerHTML = `
                    <div class="alert alert-danger">Error loading contact details</div>
                `;
            });
        }

        // Show Rating Modal
        function showRatingModal() {
            bootstrap.Modal.getInstance(document.getElementById('contactModal')).hide();
            setTimeout(() => {
                new bootstrap.Modal(document.getElementById('ratingModal')).show();
            }, 300);
        }

        // Self-Delivery Rating Form
        document.getElementById('ratingForm')?.addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            
            fetch('/buyer/rateSelfDeliverySeller', {
                method: 'POST',
                body: formData
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    alert('✅ ' + data.message);
                    bootstrap.Modal.getInstance(document.getElementById('ratingModal')).hide();
                } else {
                    alert('❌ ' + data.message);
                }
            })
            .catch(err => alert('Error submitting rating'));
        });

        // Fitting Alteration Request Form
        document.getElementById('fittingForm')?.addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            
            fetch('/buyer/requestFittingAlteration', {
                method: 'POST',
                body: formData
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    alert('✅ ' + data.message);
                    bootstrap.Modal.getInstance(document.getElementById('fittingModal')).hide();
                    this.reset();
                } else {
                    alert('❌ ' + (data.message || 'Failed to send request'));
                }
            })
            .catch(err => alert('Error sending request'));
        });

        document.getElementById('offerForm')?.addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            
            fetch('/buyer/make-offer', {
                method: 'POST',
                body: formData
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    location.reload();
                } else {
                    alert('Error: ' + (data.message || 'Failed to send offer'));
                }
            })
            .catch(err => {
                console.error(err);
                alert('Error sending offer');
            });
        });
    </script>
</body>
</html>
