<?php
// Customer Orders Page - Fixed Version
// customer/orders.php
session_start();
require_once '../app/Core/init.php';
require_once '../app/Models/OrderRating.php';

// Authentication check
if (!isset($_SESSION['user_id']) || !isset($_SESSION['user_type']) || $_SESSION['user_type'] !== 'customer') {
    header('Location: ../index.php');
    exit();
}

// Page variables
$page_title = "Orders";
$active_menu = "orders";

// Initialize models
$customerModel = new Customer();
$orderModel = new Order();
$ratingModel = new OrderRating();
$penaltyModel = new PenaltySettings();

// Get penalty settings for JavaScript
$penalty_settings_json = $penaltyModel->getSettingsJSON();

// Get customer data using user_id from session
$customer = $customerModel->findByUserId($_SESSION['user_id']);
if (!$customer) {
    header('Location: ../index.php');
    exit();
}

$customer_id = $customer['id'];

// Handle order status updates (for demonstration purposes)
$message = '';
$messageType = '';

// Get filter parameters
$status_filter = $_GET['status'] ?? 'all';
$search = $_GET['search'] ?? '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 15;
$offset = ($page - 1) * $per_page;

// Build query
$where = ["o.customer_id = ?"];
$params = [$customer_id];

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

if (!empty($search)) {
    $where[] = "(o.order_number LIKE ? OR i.title LIKE ? OR v.business_name LIKE ?)";
    $search_term = "%{$search}%";
    $params[] = $search_term;
    $params[] = $search_term;
    $params[] = $search_term;
}

$where_clause = implode(' AND ', $where);


// Get total count
$count_sql = "SELECT COUNT(*) as total 
              FROM orders o
              JOIN items i ON o.item_id = i.id
              JOIN vendors v ON o.vendor_id = v.id
              WHERE {$where_clause}";
$count_result = $db->fetch($count_sql, $params);
$total_orders = $count_result['total'];
$total_pages = ceil($total_orders / $per_page);


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

// Get orders
$orders_sql = "SELECT o.*, 
               i.title as item_title, i.main_image as item_image,
               v.business_name as vendor_name,
               v.phone as vendor_phone
               FROM orders o
               JOIN items i ON o.item_id = i.id
               JOIN vendors v ON o.vendor_id = v.id
               WHERE {$where_clause}
               ORDER BY o.created_at DESC
               LIMIT ? OFFSET ?";


$params[] = $per_page;
$params[] = $offset;
$orders = $db->fetchAll($orders_sql, $params);

// Get stats
// Get order statistics
$order_stats_sql = "SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
    SUM(CASE WHEN status = 'confirmed' THEN 1 ELSE 0 END) as confirmed,
    SUM(CASE WHEN CURDATE() BETWEEN start_date AND end_date 
                AND status NOT IN ('cancelled', 'completed', 'returned', 'pending') 
        THEN 1 ELSE 0 END) as ongoing,
    SUM(CASE WHEN CURDATE() < start_date
        AND status NOT IN ('cancelled', 'completed', 'returned', 'pending')
        THEN 1 ELSE 0 END) as future,
    SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed,
    SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) as cancelled
    FROM orders WHERE customer_id = ?";
$order_stats = $db->fetch($order_stats_sql, [$customer_id]);


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

<style>
    .card-hover-bg:hover {
        background-color: #f8f9fa;
        transition: background-color 0.3s ease;
    }
    .listing-status {
        position: absolute;
        top: 10px;
        left: 10px;
        z-index: 10;
    }
    .order-actions .btn {
        margin-right: 5px;
        margin-bottom: 5px;
    }
</style>

<body class="fixed sidebar-mini">
    <div class="wrapper">
        <!-- Sidebar -->
        <nav class="sidebar">
            <div class="sidebar-header">
                <?php include '../templates/layouts/customer/navbar.php'; ?>
            </div>
        </nav>

        <!-- Page Content -->
        <div class="content-wrapper">
            <div class="main-content">
                <!-- Navbar -->
                <?php include '../templates/layouts/customer/header.php'; ?>

                <!-- Body Content -->
                <div class="body-content">
                    <div class="decoration blur-2"></div>
                    <div class="decoration blur-3"></div>
                    <div class="container-xxl">
                        <!-- Statistics Cards -->
                        <div class="row g-3 mb-4">
                            <div class="col-sm-4 col-md-4 col-lg-2 col-xl-2 d-flex">
                                <div class="card flex-column flex-fill overflow-auto p-4 position-relative shadow w-100 widget-card">
                                    <img src="assets/dist/img/corner.png" alt="" class="end-0 h-100 position-absolute top-0">
                                    <div class="fs-14 text-muted mb-1">Total Orders</div>
                                    <h3 class="mb-0"><?php echo $order_stats['total']; ?></h3>
                                </div>
                            </div>
                            <div class="col-sm-4 col-md-4 col-lg-2 col-xl-2 d-flex">
                                <div class="card flex-column flex-fill overflow-auto p-4 position-relative shadow w-100 widget-card">
                                    <img src="assets/dist/img/corner.png" alt="" class="end-0 h-100 position-absolute top-0">
                                    <div class="fs-14 text-muted mb-1">Confirmed Orders</div>
                                    <h3 class="mb-0"><?php echo $order_stats['confirmed']; ?></h3>
                                </div>
                            </div>
                            <div class="col-sm-4 col-md-4 col-lg-2 col-xl-2 d-flex">
                                <div class="card flex-column flex-fill overflow-auto p-4 position-relative shadow w-100 widget-card">
                                    <img src="assets/dist/img/corner.png" alt="" class="end-0 h-100 position-absolute top-0">
                                    <div class="fs-14 text-muted mb-1">Cancelled Orders</div>
                                    <h3 class="mb-0"><?php echo $order_stats['cancelled']; ?></h3>
                                </div>
                            </div>
                            <div class="col-sm-4 col-md-4 col-lg-2 col-xl-2 d-flex">
                                <div class="card flex-column flex-fill overflow-auto p-4 position-relative shadow w-100 widget-card">
                                    <img src="assets/dist/img/corner.png" alt="" class="end-0 h-100 position-absolute top-0">
                                    <div class="fs-14 text-muted mb-1">Completed Orders</div>
                                    <h3 class="mb-0"><?php echo $order_stats['completed']; ?></h3>
                                </div>
                            </div>
                            <div class="col-sm-4 col-md-4 col-lg-2 col-xl-2 d-flex">
                                <div class="card flex-column flex-fill overflow-auto p-4 position-relative shadow w-100 widget-card">
                                    <img src="assets/dist/img/corner.png" alt="" class="end-0 h-100 position-absolute top-0">
                                    <div class="fs-14 text-muted mb-1">Ongoing Orders</div>
                                    <h3 class="mb-0"><?php echo $order_stats['ongoing']; ?></h3>
                                </div>
                            </div>
                            <div class="col-sm-4 col-md-4 col-lg-2 col-xl-2 d-flex">
                                <div class="card flex-column flex-fill overflow-auto p-4 position-relative shadow w-100 widget-card">
                                    <img src="assets/dist/img/corner.png" alt="" class="end-0 h-100 position-absolute top-0">
                                    <div class="fs-14 text-muted mb-1">Future Orders</div>
                                    <h3 class="mb-0"><?php echo $order_stats['future']; ?></h3>
                                </div>
                            </div>
                        </div>

                        <!-- Section Header -->
                        <div class="align-items-end row g-4 mb-4" data-aos="fade-down">
                            <div class="col">
                                <div class="section-header">
                                    <div class="font-caveat fs-4 fw-bold fw-medium section-header__subtitle text-capitalize text-center text-primary text-xl-start">My Orders</div>
                                    <h2 class="fw-semibold mb-0 section-header__title text-capitalize text-center text-xl-start h3">Order History</h2>
                                    <div class="sub-title fs-16 text-center text-xl-start">Track and manage your rental orders. <span class="text-primary fw-semibold">View order status and details.</span></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 Status</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>
                                            <option value="cancelled" <?= $status_filter === 'cancelled' ? 'selected' : '' ?>>Cancelled</option>
                                        </select>
                                    </div>
                                    <div class="col-md-7">
                                        <label class="form-label">Search</label>
                                        <input type="text" name="search" class="form-control" 
                                            placeholder="Search by order #, item, vendor..." 
                                            value="<?= htmlspecialchars($search) ?>">
                                    </div>
                                    <div class="col-md-2">
                                        <label class="form-label">&nbsp;</label>
                                        <div class="d-flex gap-2">
                                            <button type="submit" class="btn btn-primary flex-fill">
                                                <i class="fas fa-search"></i> Search
                                            </button>
                                            <a href="orders.php" class="btn btn-secondary">
                                                <i class="fas fa-redo"></i>
                                            </a>
                                        </div>
                                    </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>
                                        <a href="../items.php" class="btn btn-primary">Browse Items</a>
                                    </div>
                                <?php else: ?>
                                    <div class="table-responsive">
                                        <table class="table table-hover mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Order #/ Item</th>
                                                    <th>Vendor</th>
                                                    <th>Period</th>
                                                    <th>Amount</th>
                                                    <th>Status</th>
                                                    <th style="min-width: 180px;">Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($orders as $order): ?>
                                                    <?php

                                                    // After getting orders, check which ones have been rated
                                                    $order['customer_has_rated'] = $ratingModel->hasRated($order['id'], 'customer');


                                                    $can_complete = in_array($order['status'], ['ongoing', 'confirmed']) 
                                                                && $order['rental_completed'] == 0 
                                                                && $order['customer_completion_request'] == 0;
                                                    
                                                    $can_cancel = in_array($order['status'], ['confirmed']) 
                                                            && $order['rental_completed'] == 0;
                                                    
                                                    $can_report = in_array($order['status'], ['confirmed', 'ongoing']) 
                                                            && $order['rental_completed'] == 0;
                                                    
                                                    $completion_requested = $order['customer_completion_request'] == 1;
                                                    ?>
                                                    <tr data-order-id="<?= $order['id'] ?>"
                                                        data-start-date="<?= $order['start_date'] ?>"
                                                        data-subtotal="<?= $order['subtotal'] ?>"
                                                        data-security-deposit="<?= $order['security_deposit'] ?>"
                                                        data-total-amount="<?= $order['total_amount'] ?>">
                                                        <td>
                                                            <strong><?= htmlspecialchars($order['order_number']) ?></strong>
                                                            <div class="d-flex align-items-center">
                                                                <img src="<?= upload('items/' . $order['item_image']) ?>" 
                                                                    style="width: 70px; object-fit: cover; border-radius: 5px;" 
                                                                    class="me-2">
                                                                <span><?= htmlspecialchars($order['item_title']) ?></span>
                                                            </div>
                                                            <?php if ($order['has_active_dispute'] == 1): ?>
                                                                <br><span class="badge bg-danger"><i class="fas fa-exclamation-triangle"></i> Issue</span>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td>
                                                            <?= htmlspecialchars($order['vendor_name']) ?><br>
                                                            <small class="text-muted"><?= htmlspecialchars($order['vendor_phone']) ?></small>
                                                        </td>
                                                        <td>
                                                            <small>
                                                                <?= date('M d', strtotime($order['start_date'])) ?> - 
                                                                <?= date('M d, Y', strtotime($order['end_date'])) ?><br>
                                                                <span class="text-muted"><?= $order['rental_days'] ?> days</span>
                                                            </small>
                                                        </td>
                                                        <td>
                                                            <strong>₦<?= number_format($order['total_amount'], 2) ?></strong><br>
                                                            <small class="text-muted">Deposit: ₦<?= number_format($order['security_deposit'], 2) ?></small>
                                                        </td>
                                                        <td>
                                                            <?php
                                                            // Get today's date in PHP
                                                            $today = date('Y-m-d');

                                                            // Then in your loop, compare using PHP
                                                            if($today >= $order['start_date'] && $today <= $order['end_date'] && !in_array($order['status'], ['cancelled', 'completed', 'returned', 'pending'])) {
                                                                $order['status'] = 'ongoing';
                                                            }
                                                            $status_colors = [
                                                                'confirmed' => 'info',
                                                                'ongoing' => 'warning',
                                                                'completed' => 'success',
                                                                'cancelled' => 'danger'
                                                            ];
                                                            $color = $status_colors[$order['status']] ?? 'secondary';
                                                            ?>
                                                            <span class="badge bg-<?= $color ?>"><?= ucfirst($order['status']) ?></span>
                                                        </td>
                                                        <td>
                                                            <div class="btn-group-vertical btn-group-sm w-100">
                                                                <a href="order-details.php?id=<?= $order['id'] ?>" 
                                                                class="btn btn-sm btn-info mb-1">
                                                                    <i class="fas fa-eye"></i> View Details
                                                                </a>

                                                                <?php
                                                                    // Completion button logic - NEW WORKFLOW
                                                                    $customer_requested = ($order['customer_completion_request'] ?? 0);
                                                                    $vendor_requested = ($order['vendor_completion_request'] ?? 0);
                                                                    $rental_completed = ($order['rental_completed'] ?? 0);
                                                                    $can_request_complete = in_array($order['status'], ['ongoing', 'confirmed']) 
                                                                                        && $rental_completed == 0;
                                                                    ?>

                                                                    <?php if ($can_request_complete): ?>
                                                                        <?php if ($customer_requested == 1): ?>
                                                                            <!-- Customer already requested -->
                                                                            <button class="btn btn-sm btn-secondary mb-1" disabled>
                                                                                <i class="fas fa-clock"></i> Awaiting Vendor Confirmation
                                                                            </button>
                                                                        <?php elseif ($vendor_requested == 1): ?>
                                                                            <!-- Vendor requested, customer can confirm -->
                                                                            <button class="btn btn-sm btn-success mb-1" 
                                                                                    onclick="confirmCompletion(<?= $order['id'] ?>, '<?= htmlspecialchars($order['order_number']) ?>')">
                                                                                <i class="fas fa-check-double"></i> Confirm Completion
                                                                            </button>
                                                                        <?php else: ?>
                                                                            <!-- No request yet, customer can request -->
                                                                            <button class="btn btn-sm btn-success mb-1" 
                                                                                    onclick="requestCompletion(<?= $order['id'] ?>, '<?= htmlspecialchars($order['order_number']) ?>')">
                                                                                <i class="fas fa-check-circle"></i> Request Completion
                                                                            </button>
                                                                        <?php endif; ?>
                                                                    <?php endif; ?>
                                                                                                                                
                                                                <?php /* if ($completion_requested): ?>
                                                                    <button class="btn btn-sm btn-secondary mb-1" disabled>
                                                                        <i class="fas fa-clock"></i> Pending Completion
                                                                    </button>
                                                                <?php endif; */ ?>
                                                                
                                                                <?php if ($can_report && $order['has_active_dispute'] == 0): ?>
                                                                    <button class="btn btn-sm btn-warning mb-1" 
                                                                            onclick="openReportModal(<?= $order['id'] ?>, '<?= htmlspecialchars($order['order_number']) ?>')">
                                                                        <i class="fas fa-exclamation-circle"></i> Report Issue
                                                                    </button>
                                                                <?php elseif ($can_report && $order['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 if ($can_cancel && $order['start_date'] > $today): ?>
                                                                    <button class="btn btn-sm btn-danger mb-1" 
                                                                            onclick="openCancelModal(<?= $order['id'] ?>, '<?= htmlspecialchars($order['order_number']) ?>')">
                                                                        <i class="fas fa-ban"></i> Cancel Order
                                                                    </button>
                                                                <?php endif; ?>
                                                            </div>
                                                            <?php if ($order['status'] === 'completed'): ?>
                                                            <?php if (!$order['customer_has_rated']): ?>
                                                                <button type="button" class="btn btn-sm btn-warning" 
                                                                        onclick="openRatingModal(<?= $order['id'] ?>)">
                                                                    <i class="fas fa-star"></i> Rate Order
                                                                </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>
                </div>
            </div>
        </div>
    </div>

    

<!-- 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-warning">
                <h5 class="modal-title">Report Issue</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <!-- <form id="reportIssueForm" enctype="multipart/form-data">
                <div class="modal-body">
                    <input type="hidden" id="issue_order_id" name="order_id">
                    <input type="hidden" name="raised_by_type" value="customer">
                    
                    <p class="mb-3">Order: <strong id="issue_order_number"></strong></p>
                    
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i>
                        Report any issues with the rental. Admin and vendor will be notified.
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Issue Type <span class="text-danger">*</span></label>
                        <select name="dispute_type" class="form-select" required>
                            <option value="">Select issue type</option>
                            <option value="item_not_as_described">Item Not as Described</option>
                            <option value="item_defective">Item Defective/Damaged</option>
                            <option value="missing_items">Missing Parts/Accessories</option>
                            <option value="poor_condition">Poor Item Condition</option>
                            <option value="vendor_unresponsive">Vendor Unresponsive</option>
                            <option value="overcharged">Overcharged/Billing Issue</option>
                            <option value="other">Other Issue</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Description <span class="text-danger">*</span></label>
                        <textarea name="description" class="form-control" rows="4" required 
                                  placeholder="Describe the issue in detail..."></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Requested Refund Amount (₦)</label>
                        <input type="number" name="amount_involved" class="form-control" 
                               min="0" step="0.01" placeholder="Optional">
                        <small class="text-muted">Leave blank if just reporting</small>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Evidence (Photos/Documents)</label>
                        <input type="file" name="evidence[]" class="form-control" 
                               multiple accept="image/*,.pdf">
                        <small class="text-muted">Upload photos showing the issue (Max 5 files)</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-warning">Submit Report</button>
                </div>
            </form> -->
        </div>
    </div>
</div>

<script>
// Request Completion
// function requestCompletion(orderId, orderNumber) {
//     if (confirm(`Confirm that rental for order ${orderNumber} is complete?\n\nThis will notify the vendor to finalize the order and release your security deposit.`)) {
//         const formData = new FormData();
//         formData.append('order_id', orderId);
        
//         fetch('../api/customer-complete-order.php', {
//             method: 'POST',
//             body: formData
//         })
//         .then(response => response.json())
//         .then(data => {
//             if (data.success) {
//                 alert(data.message);
//                 location.reload();
//             } else {
//                 alert('Error: ' + data.error);
//             }
//         })
//         .catch(error => {
//             console.error('Error:', error);
//             alert('Failed to send completion request');
//         });
//     }
// }
function requestCompletion(orderId, orderNumber) {
    if (confirm('Request completion for order ' + orderNumber + '?\n\nThe vendor will need to confirm before the order is completed.')) {
        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 => {
            alert(data.success ? '✓ ' + data.message : '✗ Error: ' + data.error);
            if (data.success) location.reload();
        });
    }
}

function confirmCompletion(orderId, orderNumber) {
    if (confirm('Confirm completion for order ' + orderNumber + '?\n\nThis will complete the order and release funds.')) {
        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 => {
            alert(data.success ? '✓ ' + data.message : '✗ Error: ' + data.error);
            if (data.success) location.reload();
        });
    }
}

// Open Report Issue Modal
// function openReportIssueModal(orderId, orderNumber) {
//     document.getElementById('issue_order_id').value = orderId;
//     document.getElementById('issue_order_number').textContent = orderNumber;
//     document.getElementById('reportIssueForm').reset();
//     document.getElementById('issue_order_id').value = orderId;
//     new bootstrap.Modal(document.getElementById('reportIssueModal')).show();
// }


// Cancel Order
function cancelOrder(orderId, orderNumber) {
    if (confirm(`Are you sure you want to cancel order ${orderNumber}?\n\nYour payment will be refunded.`)) {
        const formData = new FormData();
        formData.append('order_id', orderId);
        formData.append('cancelled_by', 'customer');
        
        fetch('../api/cancel-order.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert(data.message);
                location.reload();
            } else {
                alert('Error: ' + data.error);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Failed to cancel order');
        });
    }
}
</script>


<style>
/* Order Timeline Styles */
.order-timeline {
    position: relative;
    padding-left: 40px;
}

.timeline-item {
    position: relative;
    padding: 15px 0;
    opacity: 0.5;
}

.timeline-item.completed {
    opacity: 1;
}

.timeline-item i {
    position: absolute;
    left: -40px;
    font-size: 24px;
    color: #6c757d;
}

.timeline-item.completed i {
    color: #28a745;
}

.timeline-item:not(:last-child)::before {
    content: '';
    position: absolute;
    left: -29px;
    top: 35px;
    width: 2px;
    height: calc(100% - 10px);
    background: #dee2e6;
}

.timeline-item.completed:not(:last-child)::before {
    background: #28a745;
}
</style>


    <!-- Scripts -->
    <script src="assets/plugins/jQuery/jquery.min.js"></script>
    <script src="assets/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="assets/plugins/metisMenu/metisMenu.min.js"></script>
    <script src="assets/plugins/perfect-scrollbar/perfect-scrollbar.min.js"></script>
    <script src="assets/dist/js/app.min.js"></script>
    <!-- Toastr JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
    <!-- DataTables JS -->
    <script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.7/js/dataTables.bootstrap5.min.js"></script>

    <script>
        $(document).ready(function() {
            // Toastr notifications
            <?php if ($message): ?>
                toastr.<?php echo $messageType; ?>('<?php echo addslashes($message); ?>');
            <?php endif; ?>

            // Sidebar toggle
            $('#sidebarCollapse').on('click', function() {
                $('.wrapper').toggleClass('sidebar-collapsed');
            });

            // Initialize tooltips
            var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
            var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
                return new bootstrap.Tooltip(tooltipTriggerEl);
            });
        });

        function viewOrderDetails(orderId) {
            // In a real application, this would fetch order details via AJAX
            $('#orderDetailsContent').html(`
                <div class="text-center">
                    <div class="spinner-border" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-2">Loading order details...</p>
                </div>
            `);
            $('#orderDetailsModal').modal('show');
            
            // Simulate loading delay
            setTimeout(() => {
                $('#orderDetailsContent').html(`
                    <div class="row">
                        <div class="col-md-6">
                            <h6>Order Information</h6>
                            <p><strong>Order ID:</strong> #${orderId.toString().padStart(6, '0')}</p>
                            <p><strong>Status:</strong> <span class="badge bg-info">Confirmed</span></p>
                            <p><strong>Date:</strong> ${new Date().toLocaleDateString()}</p>
                            <p><strong>Total:</strong> ₦299.99</p>
                        </div>
                        <div class="col-md-6">
                            <h6>Item Details</h6>
                            <p><strong>Item Name:</strong> Premium Rental Item</p>
                            <p><strong>Duration:</strong> 3 days</p>
                            <p><strong>Location:</strong> Downtown Area</p>
                            <p><strong>Provider:</strong> John Doe</p>
                        </div>
                    </div>
                    <hr>
                    <h6>Order Timeline</h6>
                    <div class="timeline">
                        <div class="timeline-item">
                            <div class="timeline-marker bg-success"></div>
                            <div class="timeline-content">
                                <h6 class="timeline-title">Order Placed</h6>
                                <p class="timeline-description">Your order has been successfully placed.</p>
                                <small class="text-muted">2 hours ago</small>
                            </div>
                        </div>
                        <div class="timeline-item">
                            <div class="timeline-marker bg-info"></div>
                            <div class="timeline-content">
                                <h6 class="timeline-title">Order Confirmed</h6>
                                <p class="timeline-description">The service provider has confirmed your order.</p>
                                <small class="text-muted">1 hour ago</small>
                            </div>
                        </div>
                    </div>
                `);
            }, 1000);
        }

        function trackOrder(orderId) {
            // In a real application, this would show real-time tracking
            alert('Order tracking functionality would be implemented here for order #' + orderId.toString().padStart(6, '0'));
        }
    </script>


<!-- Report Issue Modal -->
<div class="modal fade" id="reportModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-warning">
                <h5 class="modal-title">Report Issue</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="reportForm" 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="customer">
                    
                    <p>Order: <strong id="report_order_number"></strong></p>
                    
                    <div class="mb-3">
                        <label class="form-label">Issue Type <span class="text-danger">*</span></label>
                        <select name="dispute_type" class="form-select" required>
                            <option value="">Select issue type</option>
                            <option value="item_not_as_described">Item Not as Described</option>
                            <option value="item_defective">Item Defective/Damaged</option>
                            <option value="missing_items">Missing Parts</option>
                            <option value="poor_condition">Poor Condition</option>
                            <option value="vendor_unresponsive">Vendor Unresponsive</option>
                            <option value="overcharged">Overcharged</option>
                            <option value="other">Other</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Description <span class="text-danger">*</span></label>
                        <textarea name="description" class="form-control" rows="4" required></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Refund Amount (₦)</label>
                        <input type="number" name="amount_involved" class="form-control" min="0" step="0.01">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Evidence (Photos)</label>
                        <input type="file" name="evidence[]" class="form-control" multiple accept="image/*,.pdf">
                    </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">Submit</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function requestCompletion(orderId, orderNumber) {
    if (confirm('Confirm order ' + orderNumber + ' is complete?\n\nThis will notify the vendor to finalize the order.')) {
        // Show loading
        const btn = event.target;
        const originalText = btn.innerHTML;
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Sending...';
        
        fetch('../api/customer-complete-order.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: 'order_id=' + orderId
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                // Show success notification
                alert('✓ ' + data.message + '\n\nThe vendor has been notified via email.');
                location.reload();
            } else {
                alert('✗ Error: ' + data.error);
                btn.disabled = false;
                btn.innerHTML = originalText;
            }
        })
        .catch(error => {
            alert('✗ Failed to send request. Please try again.');
            btn.disabled = false;
            btn.innerHTML = originalText;
        });
    }
}

function openReportModal(orderId, orderNumber) {
    document.getElementById('report_order_id').value = orderId;
    document.getElementById('report_order_number').textContent = orderNumber;
    new bootstrap.Modal(document.getElementById('reportModal')).show();
}


document.getElementById('reportForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    var formData = new FormData(this);
    var submitBtn = this.querySelector('button[type="submit"]');
    var originalText = submitBtn.innerHTML;
    
    // Disable button and show loading
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Submitting...';
    
    fetch('../api/raise-dispute.php', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => {
        if (data.success) {
            submitBtn.innerHTML = '<i class="fas fa-check"></i> Submitted!';
            alert('✓ Issue reported successfully!');
            
            // Close modal before reload
            var modal = bootstrap.Modal.getInstance(document.getElementById('reportModal'));
            if (modal) modal.hide();
            
            setTimeout(() => location.reload(), 500);
        } else {
            alert('✗ Error: ' + data.error);
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalText;
        }
    })
    .catch(error => {
        console.error('Submission error:', error);
        alert('✗ Failed to submit report. Please try again.\n\nError: ' + error.message);
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalText;
    });
});



</script>



<!-- REPLACE THE CANCEL ORDER MODAL IN customer/orders.php with this -->
<!-- Lines 876-936 approximately -->

<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="<?php echo Auth::userType(); ?>">
                
                <div class="modal-body">
                    <div class="alert alert-warning">
                        <i class="fas fa-info-circle"></i> 
                        <strong>Cancelling Order #<span id="cancel_order_number"></span></strong>
                    </div>
                    
                    <!-- PENALTY WARNING (dynamically filled by JavaScript) -->
                    <div id="penalty_warning_box" class="alert alert-danger" style="display:none;">
                        <h6 class="mb-2"><i class="fas fa-exclamation-circle"></i> Cancellation Penalty Applies</h6>
                        <p class="mb-1">
                            A <strong><span id="penalty_percentage_display">0</span>%</strong> penalty 
                            (<strong>₦<span id="penalty_amount_display">0</span></strong>) will be deducted from your rental amount.
                        </p>
                        <p class="mb-0">
                            <strong>You will be refunded: ₦<span id="refund_amount_display">0</span></strong>
                        </p>
                    </div>
                    
                    <div id="free_cancellation_box" class="alert alert-success" style="display:none;">
                        <i class="fas fa-check-circle"></i> 
                        <strong>Free Cancellation Period</strong><br>
                        You will receive a full refund with no penalty.
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label"><strong>Why are you cancelling this order?</strong> <span class="text-danger">*</span></label>
                        <select class="form-select" id="cancel_reason" name="reason" required>
                            <option value="">-- Select Reason --</option>
                            <option value="Changed my mind">Changed my mind</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="Duplicated Booking">Duplicated Booking</option>
                            <option value="Pricing error">Pricing error</option>
                            <option value="No longer needed">No longer needed</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" placeholder="Enter specific reason for cancellation"></textarea>
                    </div>
                    
                    <div class="alert alert-info mb-0">
                        <small>
                            <i class="fas fa-check-circle"></i> Refund will be credited to your wallet<br>
                            <i class="fas fa-envelope"></i> Email notifications will be sent
                        </small>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times"></i> Close
                    </button>
                    <button type="submit" class="btn btn-danger" id="cancel_submit_btn">
                        <i class="fas fa-ban"></i> Confirm Cancellation
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Store order data for penalty calculation
let currentOrderForCancel = null;

// Open cancel modal with penalty calculation
function openCancelModal(orderId, orderNumber) {
    // Find order in the table
    const orderCard = document.querySelector(`[data-order-id="${orderId}"]`);
    if (!orderCard) {
        alert('Order not found');
        return;
    }
    
    // Extract order data from data attributes
    const startDate = orderCard.dataset.startDate;
    const subtotal = parseFloat(orderCard.dataset.subtotal || 0);
    const securityDeposit = parseFloat(orderCard.dataset.securityDeposit || 0);
    const totalAmount = parseFloat(orderCard.dataset.totalAmount || 0);
    
    // Store order data
    currentOrderForCancel = {
        id: orderId,
        orderNumber: orderNumber,
        startDate: startDate,
        subtotal: subtotal,
        securityDeposit: securityDeposit,
        totalAmount: totalAmount
    };
    
    // Set modal values
    document.getElementById('cancel_order_id').value = orderId;
    document.getElementById('cancel_order_number').textContent = orderNumber;
    
    // Calculate penalty
    calculateAndShowPenalty(startDate, subtotal, securityDeposit);
    
    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('cancelOrderModal'));
    modal.show();
}

// Penalty settings from PHP
const penaltySettings = <?= $penalty_settings_json ?>;

// Calculate penalty based on DAYS until start
function calculateAndShowPenalty(startDateStr, rentalAmount, securityDeposit) {
    // Trim any whitespace
    startDateStr = startDateStr.trim();
    
    console.log('=== ORDERS.PHP DEBUG ===');
    console.log('Raw start date string:', startDateStr);
    
    // Parse dates properly to avoid timezone issues
    // Extract year, month, day from start date
    const startParts = startDateStr.split('-');
    console.log('Date parts:', startParts);
    
    const startYear = parseInt(startParts[0]);
    const startMonth = parseInt(startParts[1]) - 1; // Month is 0-indexed in JavaScript
    const startDay = parseInt(startParts[2]);
    
    console.log('Parsed - Year:', startYear, 'Month:', startMonth, 'Day:', startDay);
    
    // Create dates at midnight local time
    const now = new Date();
    now.setHours(0, 0, 0, 0);
    
    const start = new Date(startYear, startMonth, startDay, 0, 0, 0, 0);
    
    // Calculate difference in days
    const timeDiff = start - now;
    const daysUntil = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
    
    console.log('Today:', now.toDateString(), '(' + now.getTime() + ')');
    console.log('Start:', start.toDateString(), '(' + start.getTime() + ')');
    console.log('Time diff (ms):', timeDiff);
    console.log('Days until start:', daysUntil);
    
    let penaltyPercentage = 0;
    
    // Determine penalty based on days (from admin settings)
    if (daysUntil >= 7) {
        penaltyPercentage = penaltySettings.penalty_7plus_days;
    } else if (daysUntil == 6) {
        penaltyPercentage = penaltySettings.penalty_6_days;
    } else if (daysUntil == 5) {
        penaltyPercentage = penaltySettings.penalty_5_days;
    } else if (daysUntil == 4) {
        penaltyPercentage = penaltySettings.penalty_4_days;
    } else if (daysUntil == 3) {
        penaltyPercentage = penaltySettings.penalty_3_days;
    } else if (daysUntil == 2) {
        penaltyPercentage = penaltySettings.penalty_2_days;
    } else if (daysUntil == 1) {
        penaltyPercentage = penaltySettings.penalty_1_day;
    } else {
        // Same day or past (0 or negative days)
        penaltyPercentage = penaltySettings.penalty_same_day;
    }
    
    console.log('Penalty percentage:', penaltyPercentage + '%');
    console.log('========================');
    
    // Calculate amounts
    const penaltyAmount = (rentalAmount * penaltyPercentage) / 100;
    const refundAmount = (rentalAmount - penaltyAmount) + securityDeposit;
    
    // Show/hide warning boxes
    if (penaltyPercentage > 0) {
        document.getElementById('penalty_warning_box').style.display = 'block';
        document.getElementById('free_cancellation_box').style.display = 'none';
        document.getElementById('penalty_percentage_display').textContent = penaltyPercentage.toFixed(1);
        document.getElementById('penalty_amount_display').textContent = penaltyAmount.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
        document.getElementById('refund_amount_display').textContent = refundAmount.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    } else {
        document.getElementById('penalty_warning_box').style.display = 'none';
        document.getElementById('free_cancellation_box').style.display = 'block';
    }
}

// Show/hide other reason field
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;
        document.getElementById('cancel_other_reason').value = '';
    }
});

// Handle cancel form submission
document.getElementById('cancelOrderForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const orderId = document.getElementById('cancel_order_id').value;
    let reason = document.getElementById('cancel_reason').value;
    
    if (reason === 'Other') {
        const otherReason = document.getElementById('cancel_other_reason').value.trim();
        if (otherReason) {
            reason = 'Other: ' + otherReason;
        }
    }
    
    if (!reason) {
        alert('Please select a cancellation reason');
        return;
    }
    
    const cancelledBy = document.getElementById('cancel_cancelled_by').value;
    const submitBtn = document.getElementById('cancel_submit_btn');
    
    // Disable button
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
    
    // Create form data
    const formData = new FormData();
    formData.append('order_id', orderId);
    formData.append('cancelled_by', cancelledBy);
    formData.append('reason', reason);
    
    // Submit cancellation
    fetch('../api/cancel-order.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(data.message || 'Order cancelled successfully');
            location.reload();
        } else {
            alert('Error: ' + (data.error || 'Failed to cancel order'));
            submitBtn.disabled = false;
            submitBtn.innerHTML = '<i class="fas fa-ban"></i> Confirm Cancellation';
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('An error occurred. Please try again.');
        submitBtn.disabled = false;
        submitBtn.innerHTML = '<i class="fas fa-ban"></i> Confirm Cancellation';
    });
});
</script>


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

<!-- Rating Modal -->
<div class="modal fade" id="ratingModal" 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 Your Order</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4">
                <form id="ratingForm">
                    <input type="hidden" id="rating_order_id" name="order_id">
                    
                    <!-- Item Rating -->
                    <div class="mb-4">
                        <label class="form-label fw-bold">Rate the Item</label>
                        <div class="star-rating mb-2" data-rating-target="item_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="item_rating" id="item_rating" required>
                        <textarea name="item_review" class="form-control mt-2" rows="2" 
                                  placeholder="Tell us about your experience with this item (optional, max 150 characters)" 
                                  maxlength="150"></textarea>
                        <small class="text-muted">
                            <span id="item_review_count">0</span>/150 characters
                        </small>
                    </div>
                    
                    <!-- Vendor Rating -->
                    <div class="mb-4">
                        <label class="form-label fw-bold">Rate the Vendor</label>
                        <div class="star-rating mb-2" data-rating-target="vendor_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="vendor_rating" id="vendor_rating" required>
                        <textarea name="vendor_review" class="form-control mt-2" rows="2" 
                                  placeholder="How was your experience with the vendor? (optional, max 150 characters)" 
                                  maxlength="150"></textarea>
                        <small class="text-muted">
                            <span id="vendor_review_count">0</span>/150 characters
                        </small>
                    </div>
                    
                    <div id="rating_error" class="alert alert-danger d-none"></div>
                    
                    <div class="d-grid gap-2">
                        <button type="submit" class="btn btn-primary" id="submitRatingBtn">
                            <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 counters
document.querySelector('[name="item_review"]').addEventListener('input', function() {
    document.getElementById('item_review_count').textContent = this.value.length;
});

document.querySelector('[name="vendor_review"]').addEventListener('input', function() {
    document.getElementById('vendor_review_count').textContent = this.value.length;
});

// Open modal function
function openRatingModal(orderId) {
    document.getElementById('rating_order_id').value = orderId;
    document.getElementById('ratingForm').reset();
    document.querySelectorAll('.star-rating i').forEach(star => {
        star.classList.remove('fas');
        star.classList.add('far');
    });
    document.getElementById('item_review_count').textContent = '0';
    document.getElementById('vendor_review_count').textContent = '0';
    document.getElementById('rating_error').classList.add('d-none');
    
    const modal = new bootstrap.Modal(document.getElementById('ratingModal'));
    modal.show();
}

// Form submission
document.getElementById('ratingForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const itemRating = document.getElementById('item_rating').value;
    const vendorRating = document.getElementById('vendor_rating').value;
    const errorDiv = document.getElementById('rating_error');
    const submitBtn = document.getElementById('submitRatingBtn');
    
    // Validation
    if (!itemRating || !vendorRating) {
        errorDiv.textContent = 'Please rate both the item and the vendor';
        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('ratingModal')).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>


<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 vendor 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>

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