<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Orders - 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; }
        .navbar { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
        .order-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.06);
        }
        .rating-stars { color: #ffc107; }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark">
        <div class="container">
            <a class="navbar-brand fw-bold" href="<?= base_url('buyer') ?>"><i class="bi bi-shop"></i> Flex Market</a>
            <div class="navbar-nav ms-auto">
                <a href="<?= base_url('buyer') ?>" class="nav-link">Browse</a>
                <a href="<?= base_url('buyer/my-offers') ?>" class="nav-link">My Offers</a>
                <a href="<?= base_url('buyer/my-orders') ?>" class="nav-link active">My Orders</a>
                <a href="<?= base_url('auth/logout') ?>" class="nav-link">Logout</a>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <h2 class="mb-4"><i class="bi bi-box-seam"></i> My Orders</h2>

        <?php if (!empty($orders)): ?>
            <?php foreach ($orders as $order): ?>
                <div class="order-card">
                    <div class="row align-items-center">
                        <div class="col-md-2">
                            <?php if (!empty($order['primary_image'])): ?>
                                <img src="<?= base_url('writable/uploads/products/' . $order['primary_image']) ?>" 
                                     class="img-fluid rounded" alt="Product">
                            <?php endif; ?>
                        </div>
                        <div class="col-md-4">
                            <h6><?= esc($order['product_name']) ?></h6>
                            <small class="text-muted">Order #<?= $order['id'] ?></small><br>
                            <small class="text-muted">Seller: <?= esc($order['seller_name']) ?></small>
                        </div>
                        <div class="col-md-2">
                            <strong>₹<?= number_format($order['final_price']) ?></strong><br>
                            <small class="text-muted"><?= ucfirst($order['order_type']) ?></small>
                        </div>
                        <div class="col-md-2">
                            <span class="badge bg-<?= $order['status'] === 'delivered' ? 'success' : 'warning' ?>">
                                <?= ucwords(str_replace('_', ' ', $order['status'])) ?>
                            </span><br>
                            <small class="text-muted"><?= date('d M Y', strtotime($order['created_at'])) ?></small>
                        </div>
                        <div class="col-md-2 text-end">
                            <?php if ($order['can_review']): ?>
                                <button onclick="openReviewModal(<?= $order['id'] ?>, '<?= esc($order['product_name']) ?>')" 
                                        class="btn btn-sm btn-primary">
                                    <i class="bi bi-star"></i> Review
                                </button>
                            <?php elseif (!empty($order['review'])): ?>
                                <div class="rating-stars">
                                    <?php for ($i = 1; $i <= 5; $i++): ?>
                                        <i class="bi bi-star<?= $i <= $order['review']['rating'] ? '-fill' : '' ?>"></i>
                                    <?php endfor; ?>
                                </div>
                                <small class="text-muted">Reviewed</small>
                            <?php else: ?>
                                <small class="text-muted">Complete order to review</small>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php else: ?>
            <div class="alert alert-info">
                <i class="bi bi-info-circle"></i> No orders found. Start shopping now!
            </div>
        <?php endif; ?>
    </div>

    <!-- Review Modal -->
    <div class="modal fade" id="reviewModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Write a Review</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="reviewForm">
                    <div class="modal-body">
                        <input type="hidden" id="review_order_id" name="order_id">
                        <div class="mb-3">
                            <label class="form-label">Product</label>
                            <p id="review_product_name" class="fw-bold"></p>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Rating</label>
                            <div class="rating-input" id="ratingInput">
                                <i class="bi bi-star" data-rating="1"></i>
                                <i class="bi bi-star" data-rating="2"></i>
                                <i class="bi bi-star" data-rating="3"></i>
                                <i class="bi bi-star" data-rating="4"></i>
                                <i class="bi bi-star" data-rating="5"></i>
                            </div>
                            <input type="hidden" name="rating" id="rating" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Comment</label>
                            <textarea name="comment" class="form-control" rows="4" required 
                                      placeholder="Share your experience (min 10 characters)"></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-primary">Submit Review</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>
        const reviewModal = new bootstrap.Modal(document.getElementById('reviewModal'));
        let selectedRating = 0;

        // Rating stars interaction
        document.querySelectorAll('#ratingInput i').forEach(star => {
            star.addEventListener('click', function() {
                selectedRating = parseInt(this.getAttribute('data-rating'));
                document.getElementById('rating').value = selectedRating;
                updateStars();
            });

            star.addEventListener('mouseenter', function() {
                const hoverRating = parseInt(this.getAttribute('data-rating'));
                document.querySelectorAll('#ratingInput i').forEach((s, index) => {
                    s.className = (index < hoverRating) ? 'bi bi-star-fill rating-stars' : 'bi bi-star';
                });
            });
        });

        document.getElementById('ratingInput').addEventListener('mouseleave', updateStars);

        function updateStars() {
            document.querySelectorAll('#ratingInput i').forEach((star, index) => {
                star.className = (index < selectedRating) ? 'bi bi-star-fill rating-stars' : 'bi bi-star';
            });
        }

        function openReviewModal(orderId, productName) {
            document.getElementById('review_order_id').value = orderId;
            document.getElementById('review_product_name').textContent = productName;
            selectedRating = 0;
            document.getElementById('rating').value = '';
            updateStars();
            reviewModal.show();
        }

        document.getElementById('reviewForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(this);

            fetch('/buyer/submit-review', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    Swal.fire('Success!', data.message, 'success').then(() => {
                        location.reload();
                    });
                } else {
                    Swal.fire('Error!', data.message || 'Failed to submit review', 'error');
                }
            })
            .catch(error => {
                Swal.fire('Error!', 'Something went wrong', 'error');
            });
        });
    </script>
</body>
</html>
