<?php
/**
 * VENDOR ORDERS PAGE - COMPLETE WORKING VERSION
 * File: vendor/orders.php
 */

require_once '../app/Core/init.php';
require_once '../app/Models/OrderRating.php';

Auth::requireVendor();

$vendor = new Vendor();
$order = new Order();
$ratingModel = new OrderRating();

$vendor_id = Auth::id();
$vendor_data = $vendor->getByUserId($vendor_id);

if (!$vendor_data) {
    flash('error', 'Please complete your profile first.', 'danger');
    redirect('vendor/profile.php');
}

$status_filter = $_GET['status'] ?? 'all';
$search = $_GET['search'] ?? '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 15;

$where_conditions = ["o.vendor_id = ?"];
$params = [$vendor_data['id']];

if ($status_filter !== 'all') {
    $where_conditions[] = "o.status = ?";
    $params[] = $status_filter;
}

if (!empty($search)) {
    $where_conditions[] = "(o.order_number LIKE ? OR i.title LIKE ? OR CONCAT(c.first_name, ' ', c.last_name) LIKE ?)";
    $search_term = "%$search%";
    $params[] = $search_term;
    $params[] = $search_term;
    $params[] = $search_term;
}

$where_clause = 'WHERE ' . implode(' AND ', $where_conditions);

$db = Database::getInstance();

$today = date('Y-m-d');

// Count total
$count_sql = "SELECT COUNT(*) as total FROM orders o
              JOIN items i ON o.item_id = i.id
              JOIN customers c ON o.customer_id = c.id
              $where_clause";
$count_result = $db->fetch($count_sql, $params);
$total_orders = $count_result['total'];
$total_pages = ceil($total_orders / $per_page);

// Get orders
$offset = ($page - 1) * $per_page;
$sql = "SELECT o.*, 
        i.title as item_title, i.main_image as item_image,
        CONCAT(c.first_name, ' ', c.last_name) as customer_name,
        c.phone as customer_phone,
        u.email as customer_email
        FROM orders o
        JOIN items i ON o.item_id = i.id
        JOIN customers c ON o.customer_id = c.id
        JOIN users u ON c.user_id = u.id
        $where_clause
        ORDER BY o.created_at DESC
        LIMIT $per_page OFFSET $offset";

$orders = $db->fetchAll($sql, $params);


// Stats
$stats_sql = "SELECT 
              COUNT(*) as total,
              SUM(CASE WHEN o.status = 'pending' THEN 1 ELSE 0 END) as pending,
              SUM(CASE WHEN o.status = 'confirmed' THEN 1 ELSE 0 END) as confirmed,
              SUM(CASE WHEN o.status = 'ongoing' THEN 1 ELSE 0 END) as ongoing,
              SUM(CASE WHEN o.status = 'completed' THEN 1 ELSE 0 END) as completed
              FROM orders o WHERE o.vendor_id = ?";
$stats = $db->fetch($stats_sql, [$vendor_data['id']]);

// Ensure stats has default values
if (!$stats || !isset($stats['total'])) {
    $stats = [
        'total' => 0,
        'pending' => 0,
        'confirmed' => 0,
        'ongoing' => 0,
        'completed' => 0
    ];
}

$page_title = 'My Orders - ' . APP_NAME;
include '../templates/layouts/vendor/header.php';
?>

<div class="main-content">
    <div class="page-header">
        <h1><i class="fas fa-shopping-bag"></i> My Orders</h1>
        <p class="text-muted">Manage your rental bookings</p>
    </div>

    <!-- Stats -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="stat-card">
                <div class="stat-icon bg-primary"><i class="fas fa-shopping-bag"></i></div>
                <div class="stat-details">
                    <h3><?= number_format($stats['total'] ?? 0) ?></h3>
                    <p>Total Orders</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card">
                <div class="stat-icon bg-warning"><i class="fas fa-clock"></i></div>
                <div class="stat-details">
                    <h3><?= number_format($stats['pending'] ?? 0) ?></h3>
                    <p>Pending</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card">
                <div class="stat-icon bg-info"><i class="fas fa-check"></i></div>
                <div class="stat-details">
                    <h3><?= number_format($stats['confirmed'] ?? 0) ?></h3>
                    <p>Confirmed</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card">
                <div class="stat-icon bg-success"><i class="fas fa-check-double"></i></div>
                <div class="stat-details">
                    <h3><?= number_format($stats['completed'] ?? 0) ?></h3>
                    <p>Completed</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="card mb-4">
        <div class="card-body">
            <form method="GET" class="row g-3">
                <div class="col-md-3">
                    <label class="form-label">Status</label>
                    <select name="status" class="form-select" onchange="this.form.submit()">
                        <option value="all" <?= $status_filter === 'all' ? 'selected' : '' ?>>All</option>
                        <option value="pending" <?= $status_filter === 'pending' ? 'selected' : '' ?>>Pending</option>
                        <option value="confirmed" <?= $status_filter === 'confirmed' ? 'selected' : '' ?>>Confirmed</option>
                        <option value="ongoing" <?= $status_filter === 'ongoing' ? 'selected' : '' ?>>Ongoing</option>
                        <option value="completed" <?= $status_filter === 'completed' ? 'selected' : '' ?>>Completed</option>
                    </select>
                </div>
                <div class="col-md-7">
                    <label class="form-label">Search</label>
                    <input type="text" name="search" class="form-control" placeholder="Order #, item, customer..." value="<?= esc($search) ?>">
                </div>
                <div class="col-md-2">
                    <label class="form-label">&nbsp;</label>
                    <button type="submit" class="btn btn-primary w-100"><i class="fas fa-search"></i> Search</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Orders Table -->
    <div class="card">
        <div class="card-header">
            <h5 class="mb-0">Orders List <span class="badge bg-secondary"><?= number_format($total_orders) ?></span></h5>
        </div>
        <div class="card-body p-0">
            <?php if (empty($orders)): ?>
                <div class="text-center py-5">
                    <i class="fas fa-shopping-bag fa-3x text-muted mb-3"></i>
                    <p class="text-muted">No orders found</p>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead>
                            <tr>
                                <th>Order #/ Item</th>
                                <th>Customer</th>
                                <th>Period</th>
                                <th>Amount</th>
                                <th>Status</th>
                                <th>Payment</th>
                                <th>Date</th>
                                <th class="text-end">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($orders as $order_data): $order_data['vendor_has_rated'] = $ratingModel->hasRated($order_data['id'], 'vendor'); ?>
                                <tr>
                                    <td>
                                        <strong><?= esc($order_data['order_number']) ?></strong> <br>
                                            <?php if (!empty($order_data['item_image'])): ?>
                                                <img src="<?= upload('items/' . $order_data['item_image']) ?>" 
                                                     alt="" class="rounded me-2" style="width: 80px; height: 80px; object-fit: cover;"><br>
                                            <?php endif; ?>
                                            <span><?= esc($order_data['item_title']) ?></span>
                                            <?php if ($order_data['has_active_dispute'] == 1): ?>
                                                <br><span class="badge bg-danger"><i class="fas fa-exclamation-triangle"></i> Issue</span>
                                            <?php endif; ?>
                                    </td>
                                    <td>
                                        <?= esc($order_data['customer_name']) ?><br>
                                        <small class="text-muted"><?= esc($order_data['customer_phone']) ?></small>
                                    </td>
                                    <td>
                                        <small>
                                            <?= date('M j', strtotime($order_data['start_date'])) ?> - 
                                            <?= date('M j, Y', strtotime($order_data['end_date'])) ?><br>
                                            <span class="badge bg-secondary"><?= $order_data['rental_days'] ?> days</span>
                                        </small>
                                    </td>
                                    <td><strong>₦<?= number_format($order_data['subtotal'], 2) ?></strong></td>
                                    <td>
                                        <?php
                                        $status_badges = [
                                            'pending' => 'warning',
                                            'confirmed' => 'info',
                                            'ongoing' => 'primary',
                                            'completed' => 'success',
                                            'cancelled' => 'danger'
                                        ];
                                        $badge_class = $status_badges[$order_data['status']] ?? 'secondary';
                                        ?>
                                        <span class="badge bg-<?= $badge_class ?>"><?= ucfirst($order_data['status']) ?></span>
                                    </td>
                                    <td>
                                        <?php
                                        $payment_badges = [
                                            'pending' => 'warning',
                                            'paid' => 'success',
                                            'refunded' => 'secondary'
                                        ];
                                        $payment_badge = $payment_badges[$order_data['payment_status']] ?? 'secondary';
                                        ?>
                                        <span class="badge bg-<?= $payment_badge ?>"><?= ucfirst($order_data['payment_status']) ?></span>
                                    </td>
                                    <td><small><?= date('M j, Y', strtotime($order_data['created_at'])) ?></small></td>
                                    <td class="text-end">
                                        <div class="btn-group-vertical btn-group-sm">
                                            <a href="order-details.php?id=<?= $order_data['id'] ?>" class="btn btn-info btn-sm mb-1">
                                                <i class="fas fa-eye"></i> View
                                            </a>

                                            <?php
                                            // Cancel button
                                            $can_cancel = !in_array($order_data['status'], ['cancelled', 'completed']) 
                                                       && $order_data['rental_completed'] == 0;
                                            ?>
                                            
                                            <?php
                                            // COMPLETION BUTTON LOGIC - REMOVED DATE RESTRICTION
                                            $customer_requested = ($order_data['customer_completion_request'] ?? 0);
                                            $vendor_requested = ($order_data['vendor_completion_request'] ?? 0);
                                            $rental_completed = ($order_data['rental_completed'] ?? 0);
                                            // Vendor can request completion for ongoing or confirmed orders
                                            $can_request_complete = in_array($order_data['status'], ['ongoing', 'confirmed']) 
                                                                  && $rental_completed == 0;
                                            ?>

                                            <?php if ($can_request_complete): ?>
                                                <?php if ($vendor_requested == 1): ?>
                                                    <!-- Vendor already requested -->
                                                    <button class="btn btn-sm btn-secondary mb-1" disabled>
                                                        <i class="fas fa-clock"></i> Awaiting Customer
                                                    </button>
                                                <?php elseif ($customer_requested == 1): ?>
                                                    <!-- Customer requested, vendor can confirm -->
                                                    <button class="btn btn-sm btn-success mb-1" 
                                                            onclick="confirmCompletion(<?= $order_data['id'] ?>, '<?= esc($order_data['order_number']) ?>')">
                                                        <i class="fas fa-check-double"></i> Confirm Complete
                                                        <span class="badge bg-light text-dark">!</span>
                                                    </button>
                                                <?php else: ?>
                                                    <!-- No request yet, vendor can request -->
                                                    <button class="btn btn-sm btn-success mb-1" 
                                                            onclick="requestCompletion(<?= $order_data['id'] ?>, '<?= esc($order_data['order_number']) ?>')">
                                                        <i class="fas fa-check-circle"></i> Request Complete
                                                    </button>
                                                <?php endif; ?>
                                                <?php
                                                // Report Issue button - Vendor can report issues on ongoing/confirmed/completed orders
                                                $can_report_issue = in_array($order_data['status'], ['ongoing', 'confirmed', 'completed']) 
                                                                    && $order_data['payment_status'] === 'paid';
                                                ?>

                                                <?php if ($can_report_issue && $order_data['has_active_dispute'] == 0): ?>
                                                    <button class="btn btn-sm btn-danger mb-1" 
                                                            onclick="openReportIssueModal(<?= $order_data['id'] ?>, '<?= esc($order_data['order_number']) ?>', '<?= esc($order_data['item_title']) ?>')">
                                                        <i class="fas fa-exclamation-triangle"></i> Report Issue
                                                    </button>
                                                <?php elseif ($can_report_issue && $order_data['has_active_dispute'] == 1): ?>
                                                    <a class="btn btn-sm btn-secondary mb-1" href="disputes.php">
                                                        <i class="fas fa-exclamation-triangle"></i> Respond to reported Issue
                                                    </a>
                                                <?php endif; ?>
                                            <?php endif; ?>

                                            <?php if ($can_cancel && $order_data['start_date'] > $today): ?>
                                                <button class="btn btn-sm btn-danger mb-1" 
                                                        onclick="openCancelModal(<?= $order_data['id'] ?>, '<?= esc($order_data['order_number']) ?>')">
                                                    <i class="fas fa-ban"></i> Cancel Order
                                                </button>
                                            <?php endif; ?>

                                        </div><br>
                                        <?php if ($order_data['status'] === 'completed'): ?>
                                            <?php if (!$order_data['vendor_has_rated']): ?>
                                                <button type="button" class="btn btn-sm btn-warning" 
                                                        onclick="openVendorRatingModal(<?= $order_data['id'] ?>)">
                                                    <i class="fas fa-star"></i> Rate Customer
                                                </button>
                                            <?php else: ?>
                                                <span class="badge bg-success">
                                                    <i class="fas fa-check"></i> Rated
                                                </span>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                <?php if ($total_pages > 1): ?>
                    <div class="card-footer">
                        <nav>
                            <ul class="pagination justify-content-center mb-0">
                                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                    <li class="page-item <?= $i === $page ? 'active' : '' ?>">
                                        <a class="page-link" href="?page=<?= $i ?>&status=<?= $status_filter ?>&search=<?= urlencode($search) ?>"><?= $i ?></a>
                                    </li>
                                <?php endfor; ?>
                            </ul>
                        </nav>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Cancel Order Modal -->
<div class="modal fade" id="cancelOrderModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">
                    <i class="fas fa-exclamation-triangle"></i> Cancel Order
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form id="cancelOrderForm">
                <input type="hidden" id="cancel_order_id">
                <input type="hidden" id="cancel_cancelled_by" value="vendor">
                
                <div class="modal-body">
                    <div class="alert alert-warning">
                        <i class="fas fa-info-circle"></i> 
                        <strong>Order #<span id="cancel_order_number"></span></strong> will be cancelled and customer will receive full refund.
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label"><strong>Why are you cancelling?</strong> <span class="text-danger">*</span></label>
                        <select class="form-select" id="cancel_reason" name="reason" required>
                            <option value="">-- Select Reason --</option>
                            <option value="Customer request">Customer requested cancellation</option>
                            <option value="Item not available">Item not available</option>
                            <option value="Payment issue">Payment issue</option>
                            <option value="Date conflict">Date conflict</option>
                            <option value="Pricing error">Pricing error</option>
                            <option value="Customer no-show">Customer no-show</option>
                            <option value="Item damaged">Item damaged/not ready</option>
                            <option value="Other">Other (specify below)</option>
                        </select>
                    </div>
                    
                    <div class="mb-3" id="cancel_other_reason_div" style="display:none;">
                        <label class="form-label">Please specify:</label>
                        <textarea class="form-control" id="cancel_other_reason" rows="2"></textarea>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-danger" id="cancel_submit_btn">
                        <i class="fas fa-ban"></i> Cancel Order
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php include '../templates/layouts/vendor/footer.php'; ?>

<script>
// Cancel modal
document.getElementById('cancel_reason').addEventListener('change', function() {
    const otherDiv = document.getElementById('cancel_other_reason_div');
    if (this.value === 'Other') {
        otherDiv.style.display = 'block';
        document.getElementById('cancel_other_reason').required = true;
    } else {
        otherDiv.style.display = 'none';
        document.getElementById('cancel_other_reason').required = false;
    }
});

function openCancelModal(orderId, orderNumber) {
    document.getElementById('cancel_order_id').value = orderId;
    document.getElementById('cancel_order_number').textContent = orderNumber;
    document.getElementById('cancelOrderForm').reset();
    document.getElementById('cancel_other_reason_div').style.display = 'none';
    var cancelModal = new bootstrap.Modal(document.getElementById('cancelOrderModal'));
    cancelModal.show();
}

document.getElementById('cancelOrderForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const orderId = document.getElementById('cancel_order_id').value;
    const reason = document.getElementById('cancel_reason').value;
    const otherReason = document.getElementById('cancel_other_reason').value;
    const submitBtn = document.getElementById('cancel_submit_btn');
    
    if (!reason) {
        alert('Please select a cancellation reason');
        return;
    }
    
    if (reason === 'Other' && !otherReason.trim()) {
        alert('Please specify the cancellation reason');
        return;
    }
    
    if (!confirm('Cancel this order? Customer will receive full refund.')) {
        return;
    }
    
    const finalReason = reason === 'Other' ? otherReason : reason;
    
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Cancelling...';
    
    fetch('../api/cancel-order.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: new URLSearchParams({
            'order_id': orderId,
            'cancelled_by': 'vendor',
            'reason': finalReason
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('✓ Order cancelled!\n\n' + data.message);
            bootstrap.Modal.getInstance(document.getElementById('cancelOrderModal')).hide();
            location.reload();
        } else {
            alert('✗ Error: ' + data.error);
            submitBtn.disabled = false;
            submitBtn.innerHTML = '<i class="fas fa-ban"></i> Cancel Order';
        }
    })
    .catch(error => {
        alert('✗ Failed: ' + error.message);
        submitBtn.disabled = false;
        submitBtn.innerHTML = '<i class="fas fa-ban"></i> Cancel Order';
    });
});


function requestCompletion(orderId, orderNumber) {
    if (confirm('Request completion for order ' + orderNumber + '?\n\nThe customer will need to confirm before funds are released.')) {
        // Get the button that was clicked
        const btn = event.target.closest('button');
        const originalHTML = btn.innerHTML;
        
        // Disable button and show loading
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Requesting...';
        
        fetch('../api/complete-rental.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: 'order_id=' + orderId + '&action=request'
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                alert('✓ ' + data.message);
                location.reload();
            } else {
                alert('✗ Error: ' + data.error);
                // Re-enable button on error
                btn.disabled = false;
                btn.innerHTML = originalHTML;
            }
        })
        .catch(error => {
            alert('✗ Failed to send request. Please try again.');
            // Re-enable button on error
            btn.disabled = false;
            btn.innerHTML = originalHTML;
        });
    }
}

function confirmCompletion(orderId, orderNumber) {
    if (confirm('Confirm completion for order ' + orderNumber + '?\n\nThis will complete the order and release funds!')) {
        // Get the button that was clicked
        const btn = event.target.closest('button');
        const originalHTML = btn.innerHTML;
        
        // Disable button and show loading
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Confirming...';
        
        fetch('../api/complete-rental.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: 'order_id=' + orderId + '&action=confirm'
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                alert('✓ ' + data.message);
                location.reload();
            } else {
                alert('✗ Error: ' + data.error);
                // Re-enable button on error
                btn.disabled = false;
                btn.innerHTML = originalHTML;
            }
        })
        .catch(error => {
            alert('✗ Failed to complete order. Please try again.');
            // Re-enable button on error
            btn.disabled = false;
            btn.innerHTML = originalHTML;
        });
    }
}
</script>


<!-- ================================================================
     VENDOR RATING MODAL
     ================================================================
     Add this modal BEFORE the closing </body> tag in vendor/orders.php
     ================================================================ -->

<!-- Vendor Rating Modal -->
<div class="modal fade" id="vendorRatingModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header border-0">
                <h5 class="modal-title">Rate Customer</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4">
                <form id="vendorRatingForm">
                    <input type="hidden" id="vendor_rating_order_id" name="order_id">
                    
                    <!-- Customer Rating -->
                    <div class="mb-4">
                        <label class="form-label fw-bold">Rate the Customer</label>
                        <p class="text-muted small">How was your experience with this customer?</p>
                        <div class="star-rating mb-2" data-rating-target="customer_rating">
                            <i class="far fa-star" data-rating="1"></i>
                            <i class="far fa-star" data-rating="2"></i>
                            <i class="far fa-star" data-rating="3"></i>
                            <i class="far fa-star" data-rating="4"></i>
                            <i class="far fa-star" data-rating="5"></i>
                        </div>
                        <input type="hidden" name="customer_rating" id="customer_rating" required>
                        <textarea name="customer_review" class="form-control mt-3" rows="3" 
                                  placeholder="Share your experience with this customer (optional, max 150 characters)" 
                                  maxlength="150"></textarea>
                        <small class="text-muted">
                            <span id="customer_review_count">0</span>/150 characters
                        </small>
                    </div>
                    
                    <div id="vendor_rating_error" class="alert alert-danger d-none"></div>
                    
                    <div class="d-grid gap-2">
                        <button type="submit" class="btn btn-primary" id="submitVendorRatingBtn">
                            <i class="fas fa-star me-2"></i>Submit Rating
                        </button>
                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<style>
.star-rating {
    font-size: 2rem;
    cursor: pointer;
}
.star-rating i {
    color: #ddd;
    transition: color 0.2s;
}
.star-rating i:hover,
.star-rating i.hover {
    color: #ffc107;
}
.star-rating i.fas {
    color: #ffc107;
}
</style>

<script>
// Star Rating Functionality
document.querySelectorAll('.star-rating').forEach(container => {
    const stars = container.querySelectorAll('i');
    const targetInput = container.dataset.ratingTarget;
    
    stars.forEach((star, index) => {
        // Click handler
        star.addEventListener('click', () => {
            const rating = parseInt(star.dataset.rating);
            document.getElementById(targetInput).value = rating;
            
            // Update stars
            stars.forEach((s, i) => {
                if (i < rating) {
                    s.classList.remove('far');
                    s.classList.add('fas');
                } else {
                    s.classList.remove('fas');
                    s.classList.add('far');
                }
            });
        });
        
        // Hover effect
        star.addEventListener('mouseenter', () => {
            stars.forEach((s, i) => {
                if (i <= index) {
                    s.classList.add('hover');
                } else {
                    s.classList.remove('hover');
                }
            });
        });
        
        container.addEventListener('mouseleave', () => {
            stars.forEach(s => s.classList.remove('hover'));
        });
    });
});

// Character counter
document.querySelector('[name="customer_review"]').addEventListener('input', function() {
    document.getElementById('customer_review_count').textContent = this.value.length;
});

// Open modal function
function openVendorRatingModal(orderId) {
    document.getElementById('vendor_rating_order_id').value = orderId;
    document.getElementById('vendorRatingForm').reset();
    document.querySelectorAll('.star-rating i').forEach(star => {
        star.classList.remove('fas');
        star.classList.add('far');
    });
    document.getElementById('customer_review_count').textContent = '0';
    document.getElementById('vendor_rating_error').classList.add('d-none');
    
    const modal = new bootstrap.Modal(document.getElementById('vendorRatingModal'));
    modal.show();
}

// Form submission
document.getElementById('vendorRatingForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const customerRating = document.getElementById('customer_rating').value;
    const errorDiv = document.getElementById('vendor_rating_error');
    const submitBtn = document.getElementById('submitVendorRatingBtn');
    
    // Validation
    if (!customerRating) {
        errorDiv.textContent = 'Please rate the customer';
        errorDiv.classList.remove('d-none');
        return;
    }
    
    // Disable button
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Submitting...';
    
    // Submit via AJAX
    const formData = new FormData(this);
    
    fetch('../ajax/submit-rating.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            bootstrap.Modal.getInstance(document.getElementById('vendorRatingModal')).hide();
            alert(data.message);
            location.reload();
        } else {
            errorDiv.textContent = data.message;
            errorDiv.classList.remove('d-none');
            submitBtn.disabled = false;
            submitBtn.innerHTML = '<i class="fas fa-star me-2"></i>Submit Rating';
        }
    })
    .catch(error => {
        console.error('Error:', error);
        errorDiv.textContent = 'An error occurred. Please try again.';
        errorDiv.classList.remove('d-none');
        submitBtn.disabled = false;
        submitBtn.innerHTML = '<i class="fas fa-star me-2"></i>Submit Rating';
    });
});
</script>


<!-- Report Issue Modal -->
<div class="modal fade" id="reportIssueModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">
                    <i class="fas fa-exclamation-triangle"></i> Report Issue
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form id="reportIssueForm" enctype="multipart/form-data">
                <div class="modal-body">
                    <input type="hidden" id="report_order_id" name="order_id">
                    <input type="hidden" name="raised_by_type" value="vendor">
                    
                    <div class="alert alert-info">
                        <strong>Order:</strong> <span id="report_order_number"></span><br>
                        <strong>Item:</strong> <span id="report_item_title"></span>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-bold">Issue Type <span class="text-danger">*</span></label>
                        <select name="dispute_type" class="form-select" required>
                            <option value="">Select issue type</option>
                            <option value="damage">Customer Damaged Item</option>
                            <option value="non_return">Customer Didn't Return Item</option>
                            <option value="late_return">Late Return</option>
                            <option value="payment_issue">Payment Issue</option>
                            <option value="misuse">Item Misuse</option>
                            <option value="other">Other Issue</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-bold">Description <span class="text-danger">*</span></label>
                        <textarea name="description" class="form-control" rows="5" 
                                  placeholder="Describe the issue in detail..." required></textarea>
                        <small class="text-muted">Be specific about what happened, when, and any relevant details.</small>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-bold">Amount Involved (Optional)</label>
                        <div class="input-group">
                            <span class="input-group-text">₦</span>
                            <input type="number" name="amount_involved" class="form-control" 
                                   placeholder="0.00" step="0.01" min="0">
                        </div>
                        <small class="text-muted">If this issue involves additional costs or refunds.</small>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-bold">Evidence (Optional)</label>
                        <input type="file" name="evidence[]" class="form-control" multiple 
                               accept="image/*,.pdf">
                        <small class="text-muted">Upload photos or documents (max 5 files, 10MB each)</small>
                    </div>

                    <div class="alert alert-warning">
                        <i class="fas fa-info-circle"></i> 
                        <strong>Note:</strong> The customer and admin will be notified immediately. 
                        This issue will be reviewed and addressed within 24-48 hours.
                    </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-danger" id="submitReportBtn">
                        <i class="fas fa-paper-plane"></i> Submit Report
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>


<script>
// Open Report Issue Modal
function openReportIssueModal(orderId, orderNumber, itemTitle) {
    document.getElementById('report_order_id').value = orderId;
    document.getElementById('report_order_number').textContent = orderNumber;
    document.getElementById('report_item_title').textContent = itemTitle;
    
    // Reset form
    document.getElementById('reportIssueForm').reset();
    document.getElementById('report_order_id').value = orderId;
    
    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('reportIssueModal'));
    modal.show();
}

// Handle Report Issue Form Submission
document.getElementById('reportIssueForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const submitBtn = document.getElementById('submitReportBtn');
    const originalText = submitBtn.innerHTML;
    
    // Validate
    const disputeType = this.querySelector('[name="dispute_type"]').value;
    const description = this.querySelector('[name="description"]').value;
    
    if (!disputeType || !description.trim()) {
        alert('Please fill in all required fields');
        return;
    }
    
    // Disable button
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Submitting...';
    
    // Prepare form data
    const formData = new FormData(this);
    
    // Submit via AJAX
    fetch('../api/raise-dispute.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('✓ Issue reported successfully!\n\nDispute Number: ' + data.dispute_number + '\n\nThe customer and admin have been notified.');
            
            // Close modal
            bootstrap.Modal.getInstance(document.getElementById('reportIssueModal')).hide();
            
            // Reload page to show updated status
            setTimeout(() => location.reload(), 1000);
        } else {
            alert('✗ Error: ' + (data.error || 'Failed to submit report'));
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalText;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('✗ An error occurred. Please try again.');
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalText;
    });
});
</script>



<script>
document.getElementById('reportIssueForm')?.addEventListener('submit', function(e) {
    e.preventDefault();
    
    const submitBtn = document.getElementById('submitReportBtn');
    const originalText = submitBtn.innerHTML;
    
    // Validate
    const disputeType = this.querySelector('[name="dispute_type"]').value;
    const description = this.querySelector('[name="description"]').value.trim();
    
    if (!disputeType) {
        alert('Please select an issue type');
        return;
    }
    
    if (!description) {
        alert('Please describe the issue');
        return;
    }
    
    // Show loading state
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
    
    // Prepare form data
    const formData = new FormData(this);
    
    // Submit via AJAX
    fetch('../api/raise-dispute.php', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        // Check if response is JSON
        const contentType = response.headers.get('content-type');
        if (!contentType || !contentType.includes('application/json')) {
            throw new Error('Server returned non-JSON response');
        }
        return response.json();
    })
    .then(data => {
        // Re-enable button first
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalText;
        
        if (data.success) {
            alert('✓ Issue reported successfully!\n\nDispute Number: ' + data.dispute_number + '\n\nThe customer and admin have been notified.');
            
            // Close modal
            const modalElement = document.getElementById('reportIssueModal');
            const modalInstance = bootstrap.Modal.getInstance(modalElement);
            if (modalInstance) {
                modalInstance.hide();
            }
            
            // Reset form
            this.reset();
            
            // Reload page after short delay
            setTimeout(() => {
                window.location.reload();
            }, 1500);
        } else {
            alert('✗ Error: ' + (data.error || 'Failed to submit report. Please try again.'));
        }
    })
    .catch(error => {
        console.error('Error:', error);
        
        // Re-enable button
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalText;
        
        alert('✗ An error occurred while submitting. Please check your connection and try again.');
    });
});
</script>