<?php
// Customer Order Details Page
// customer/order-details.php
session_start();
require_once '../app/Core/init.php';
require_once '../app/Models/OrderRating.php';
require_once '../app/Models/PenaltySettings.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 = "Order Details";
$active_menu = "orders";

// Get order ID
$order_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$order_id) {
    header('Location: orders.php');
    exit();
}

// Initialize models
$customerModel = new Customer();
$penaltyModel = new PenaltySettings();

$customer = $customerModel->findByUserId($_SESSION['user_id']);

if (!$customer) {
    header('Location: ../index.php');
    exit();
}

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

$db = Database::getInstance();

// Get order details
$order = $db->fetch("
    SELECT o.*, i.title as item_title, i.main_image as item_image, i.description as item_description,
    v.business_name as vendor_name, v.phone as vendor_phone, v.address as vendor_address,
    vu.email as vendor_email
    FROM orders o
    JOIN items i ON o.item_id = i.id
    JOIN vendors v ON o.vendor_id = v.id
    JOIN users vu ON v.user_id = vu.id
    WHERE o.id = ? AND o.customer_id = ?
", [$order_id, $customer['id']]);

if (!$order) {
    header('Location: orders.php');
    exit();
}

// Get payment breakdown if exists
$breakdown = $db->fetch("
    SELECT * FROM order_payment_breakdown 
    WHERE order_id = ? AND type = 'security_deposit'
    LIMIT 1
", [$order_id]);

// Get cancellation details if exists
$cancel_info = null;
if (!empty($order['cancel_detail'])) {
    $cancel_info = json_decode($order['cancel_detail'], true);
}

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

<style>
    .order-detail-card {
        border-radius: 10px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }
    .info-label {
        font-weight: 600;
        color: #6c757d;
        font-size: 14px;
    }
    .info-value {
        font-size: 16px;
        color: #212529;
    }
    .timeline {
        list-style: none;
        padding-left: 0;
        position: relative;
    }
    .timeline-item {
        padding-left: 35px;
        position: relative;
        padding-bottom: 25px;
    }
    .timeline-item:last-child {
        padding-bottom: 0;
    }
    .timeline-item i {
        position: absolute;
        left: 0;
        top: 2px;
        font-size: 18px;
    }
    .timeline-item::before {
        content: '';
        position: absolute;
        left: 8px;
        top: 25px;
        bottom: -10px;
        width: 2px;
        background: #dee2e6;
    }
    .timeline-item:last-child::before {
        display: none;
    }
    .action-card {
        border-left: 4px solid #007bff;
    }
</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">
                        
                        <!-- Back Button & Page Header -->
                        <div class="row mb-4">
                            <div class="col-12">
                                <a href="orders.php" class="btn btn-outline-primary mb-3">
                                    <i class="fas fa-arrow-left"></i> Back to Orders
                                </a>
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <h2 class="mb-1">Order #<?= htmlspecialchars($order['order_number']) ?></h2>
                                        <p class="text-muted mb-0">
                                            <i class="far fa-calendar"></i> 
                                            Placed on <?= date('M d, Y h:i A', strtotime($order['created_at'])) ?>
                                        </p>
                                    </div>
                                    <div>
                                        <?php
                                        $status_colors = [
                                            'pending' => 'warning',
                                            'confirmed' => 'info',
                                            'ongoing' => 'primary',
                                            'completed' => 'success',
                                            'cancelled' => 'danger'
                                        ];
                                        $color = $status_colors[$order['status']] ?? 'secondary';
                                        ?>
                                        <span class="badge bg-<?= $color ?> fs-5 px-4 py-2">
                                            <?= ucfirst($order['status']) ?>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row g-4">
                            <!-- Left Column -->
                            <div class="col-lg-8">
                                <!-- Item Details Card -->
                                <div class="card order-detail-card mb-4">
                                    <div class="card-header bg-white">
                                        <h5 class="mb-0"><i class="fas fa-box text-primary"></i> Item Details</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-4 mb-3 mb-md-0">
                                                <img src="<?= upload('items/' . $order['item_image']) ?>" 
                                                     class="img-fluid rounded" 
                                                     style="width: 100%; height: 200px; object-fit: cover;"
                                                     alt="<?= htmlspecialchars($order['item_title']) ?>">
                                            </div>
                                            <div class="col-md-8">
                                                <h4 class="mb-3"><?= htmlspecialchars($order['item_title']) ?></h4>
                                                <p class="text-muted"><?= nl2br(htmlspecialchars($order['item_description'])) ?></p>
                                                
                                                <div class="row mt-4">
                                                    <div class="col-6">
                                                        <div class="info-label">Rental Period</div>
                                                        <div class="info-value">
                                                            <strong><?= date('M d, Y', strtotime($order['start_date'])) ?></strong><br>
                                                            <small class="text-muted">to</small><br>
                                                            <strong><?= date('M d, Y', strtotime($order['end_date'])) ?></strong>
                                                        </div>
                                                    </div>
                                                    <div class="col-6">
                                                        <div class="info-label">Duration</div>
                                                        <div class="info-value mb-3">
                                                            <strong><?= $order['rental_days'] ?> days</strong>
                                                        </div>
                                                        
                                                        <div class="info-label">Quantity</div>
                                                        <div class="info-value">
                                                            <strong><?= $order['quantity'] ?></strong>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Vendor Details Card -->
                                <div class="card order-detail-card mb-4">
                                    <div class="card-header bg-white">
                                        <h5 class="mb-0"><i class="fas fa-store text-primary"></i> Vendor Details</h5>
                                    </div>
                                    <div class="card-body">
                                        <h5><?= htmlspecialchars($order['vendor_name']) ?></h5>
                                        <div class="row mt-3">
                                            <div class="col-md-6">
                                                <p class="mb-2">
                                                    <i class="fas fa-phone text-primary"></i> 
                                                    <a href="tel:<?= htmlspecialchars($order['vendor_phone']) ?>">
                                                        <?= htmlspecialchars($order['vendor_phone']) ?>
                                                    </a>
                                                </p>
                                                <p class="mb-2">
                                                    <i class="fas fa-envelope text-primary"></i> 
                                                    <a href="mailto:<?= htmlspecialchars($order['vendor_email']) ?>">
                                                        <?= htmlspecialchars($order['vendor_email']) ?>
                                                    </a>
                                                </p>
                                            </div>
                                            <div class="col-md-6">
                                                <?php if (!empty($order['vendor_address'])): ?>
                                                    <p class="mb-0">
                                                        <i class="fas fa-map-marker-alt text-primary"></i> 
                                                        <?= htmlspecialchars($order['vendor_address']) ?>
                                                    </p>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- ================================================================
                                    RATINGS DISPLAY COMPONENT
                                    ================================================================
                                    Add this section to ALL order-details.php pages (customer, vendor, admin)
                                    Place it after the order information section
                                    ================================================================ -->

                                <?php
                                // Get ratings for this order
                                $ratingModel = new OrderRating();
                                $ratings = $ratingModel->getByOrder($order['id']);
                                $customerRating = $ratingModel->getCustomerRating($order['id']);
                                $vendorRating = $ratingModel->getVendorRating($order['id']);

                                // Function to display stars
                                function displayRatingStars($rating) {
                                    $html = '';
                                    for ($i = 1; $i <= 5; $i++) {
                                        if ($i <= $rating) {
                                            $html .= '<i class="fas fa-star text-warning"></i>';
                                        } else {
                                            $html .= '<i class="far fa-star text-muted"></i>';
                                        }
                                    }
                                    return $html;
                                }
                                ?>

                                <?php if (!empty($ratings)): ?>
                                <!-- Ratings Section -->
                                <div class="card mb-4">
                                    <div class="card-header bg-white">
                                        <h5 class="mb-0">
                                            <i class="fas fa-star text-warning me-2"></i>Ratings & Reviews
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <?php if ($customerRating): ?>
                                        <!-- Customer's Rating -->
                                        <div class="mb-4 pb-4 border-bottom">
                                            <div class="d-flex align-items-start">
                                                <div class="flex-shrink-0">
                                                    <div class="rounded-circle bg-primary text-white d-flex align-items-center justify-content-center" 
                                                        style="width: 50px; height: 50px;">
                                                        <i class="fas fa-user"></i>
                                                    </div>
                                                </div>
                                                <div class="flex-grow-1 ms-3">
                                                    <h6 class="mb-1">Customer Rating</h6>
                                                    <small class="text-muted">
                                                        <?= date('M d, Y - h:i A', strtotime($customerRating['created_at'])) ?>
                                                    </small>
                                                    
                                                    <!-- Item Rating -->
                                                    <div class="mt-3">
                                                        <strong>Item Rating:</strong>
                                                        <div class="d-inline-block ms-2">
                                                            <?= displayRatingStars($customerRating['item_rating']) ?>
                                                            <span class="ms-2 text-muted">(<?= $customerRating['item_rating'] ?>/5)</span>
                                                        </div>
                                                        <?php if (!empty($customerRating['item_review'])): ?>
                                                        <p class="mt-2 mb-0 text-muted">
                                                            <i class="fas fa-quote-left me-1"></i>
                                                            <?= htmlspecialchars($customerRating['item_review']) ?>
                                                            <i class="fas fa-quote-right ms-1"></i>
                                                        </p>
                                                        <?php endif; ?>
                                                    </div>
                                                    
                                                    <!-- Vendor Rating -->
                                                    <div class="mt-3">
                                                        <strong>Vendor Rating:</strong>
                                                        <div class="d-inline-block ms-2">
                                                            <?= displayRatingStars($customerRating['vendor_rating']) ?>
                                                            <span class="ms-2 text-muted">(<?= $customerRating['vendor_rating'] ?>/5)</span>
                                                        </div>
                                                        <?php if (!empty($customerRating['vendor_review'])): ?>
                                                        <p class="mt-2 mb-0 text-muted">
                                                            <i class="fas fa-quote-left me-1"></i>
                                                            <?= htmlspecialchars($customerRating['vendor_review']) ?>
                                                            <i class="fas fa-quote-right ms-1"></i>
                                                        </p>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <?php if ($vendorRating): ?>
                                        <!-- Vendor's Rating -->
                                        <div class="mb-0">
                                            <div class="d-flex align-items-start">
                                                <div class="flex-shrink-0">
                                                    <div class="rounded-circle bg-success text-white d-flex align-items-center justify-content-center" 
                                                        style="width: 50px; height: 50px;">
                                                        <i class="fas fa-store"></i>
                                                    </div>
                                                </div>
                                                <div class="flex-grow-1 ms-3">
                                                    <h6 class="mb-1">Vendor Rating</h6>
                                                    <small class="text-muted">
                                                        <?= date('M d, Y - h:i A', strtotime($vendorRating['created_at'])) ?>
                                                    </small>
                                                    
                                                    <!-- Customer Rating -->
                                                    <div class="mt-3">
                                                        <strong>Customer Rating:</strong>
                                                        <div class="d-inline-block ms-2">
                                                            <?= displayRatingStars($vendorRating['customer_rating']) ?>
                                                            <span class="ms-2 text-muted">(<?= $vendorRating['customer_rating'] ?>/5)</span>
                                                        </div>
                                                        <?php if (!empty($vendorRating['customer_review'])): ?>
                                                        <p class="mt-2 mb-0 text-muted">
                                                            <i class="fas fa-quote-left me-1"></i>
                                                            <?= htmlspecialchars($vendorRating['customer_review']) ?>
                                                            <i class="fas fa-quote-right ms-1"></i>
                                                        </p>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <?php if (!$customerRating && !$vendorRating): ?>
                                        <div class="text-center text-muted py-3">
                                            <i class="fas fa-star-half-alt fa-2x mb-2"></i>
                                            <p class="mb-0">No ratings yet for this order</p>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <?php endif; ?>

                                <?php if ($order['status'] === 'completed'): ?>
                                    <?php if (Auth::userType() === 'customer' && !$customerRating): ?>
                                    <!-- Customer: Show Rate Order Button -->
                                    <div class="card mb-4">
                                        <div class="card-body text-center py-4">
                                            <i class="fas fa-star fa-2x text-warning mb-3"></i>
                                            <h6 class="mb-3">How was your experience?</h6>
                                            <button type="button" class="btn btn-primary" onclick="openRatingModal(<?= $order['id'] ?>)">
                                                <i class="fas fa-star me-2"></i>Rate This Order
                                            </button>
                                        </div>
                                    </div>
                                    <?php elseif (Auth::userType() === 'vendor' && !$vendorRating): ?>
                                    <!-- Vendor: Show Rate Customer Button -->
                                    <div class="card mb-4">
                                        <div class="card-body text-center py-4">
                                            <i class="fas fa-star fa-2x text-warning mb-3"></i>
                                            <h6 class="mb-3">Rate your customer</h6>
                                            <button type="button" class="btn btn-primary" onclick="openVendorRatingModal(<?= $order['id'] ?>)">
                                                <i class="fas fa-star me-2"></i>Rate Customer
                                            </button>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                <?php endif; ?>

                                <!-- Cancellation Details (if cancelled) -->
                                <?php if ($cancel_info): ?>
                                    <div class="card order-detail-card border-danger mb-4">
                                        <div class="card-header bg-danger text-white">
                                            <h5 class="mb-0"><i class="fas fa-ban"></i> Cancellation Details</h5>
                                        </div>
                                        <div class="card-body">
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <div class="info-label">Cancelled By</div>
                                                    <div class="info-value">
                                                        <strong><?= htmlspecialchars($cancel_info['cancelled_by_name']) ?></strong>
                                                        <span class="badge bg-secondary ms-2"><?= ucfirst($cancel_info['cancelled_by']) ?></span>
                                                    </div>
                                                </div>
                                                <div class="col-md-6 mb-3">
                                                    <div class="info-label">Cancelled On</div>
                                                    <div class="info-value">
                                                        <strong><?= date('M d, Y h:i A', strtotime($cancel_info['cancelled_at'])) ?></strong>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="info-label">Reason</div>
                                            <div class="info-value">
                                                <strong><?= htmlspecialchars($cancel_info['reason']) ?></strong>
                                            </div>
                                        </div>
                                    </div>
                                <?php endif; ?>
                            </div>

                            <!-- Right Column -->
                            <div class="col-lg-4">
                                <!-- Payment Summary Card -->
                                <div class="card order-detail-card mb-4">
                                    <div class="card-header bg-white">
                                        <h5 class="mb-0"><i class="fas fa-file-invoice-dollar text-primary"></i> Payment Summary</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between mb-3">
                                            <span class="info-label">Rental Amount</span>
                                            <strong class="info-value">₦<?= number_format($order['subtotal'], 2) ?></strong>
                                        </div>
                                        <div class="d-flex justify-content-between mb-3">
                                            <span class="info-label">Security Deposit</span>
                                            <strong class="info-value">₦<?= number_format($order['security_deposit'], 2) ?></strong>
                                        </div>
                                        <hr>
                                        <div class="d-flex justify-content-between mb-3">
                                            <strong>Total Amount</strong>
                                            <h4 class="mb-0 text-primary">₦<?= number_format($order['total_amount'], 2) ?></h4>
                                        </div>
                                        
                                        <hr>
                                        
                                        <div class="d-flex justify-content-between mb-2">
                                            <span class="info-label">Payment Status</span>
                                            <?php
                                            $payment_colors = ['paid' => 'success', 'pending' => 'warning', 'failed' => 'danger'];
                                            $p_color = $payment_colors[$order['payment_status']] ?? 'secondary';
                                            ?>
                                            <span class="badge bg-<?= $p_color ?>"><?= ucfirst($order['payment_status']) ?></span>
                                        </div>
                                        
                                        <?php if ($breakdown): ?>
                                            <div class="d-flex justify-content-between">
                                                <span class="info-label">Breakdown Status</span>
                                                <?php
                                                $breakdown_colors = ['onhold' => 'warning', 'released' => 'success', 'refunded' => 'info'];
                                                $b_color = $breakdown_colors[$breakdown['status']] ?? 'secondary';
                                                ?>
                                                <span class="badge bg-<?= $b_color ?>"><?= ucfirst($breakdown['status']) ?></span>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>

                                <!-- Order Timeline Card -->
                                <div class="card order-detail-card mb-4">
                                    <div class="card-header bg-white">
                                        <h5 class="mb-0"><i class="fas fa-clock text-primary"></i> Order Timeline</h5>
                                    </div>
                                    <div class="card-body">
                                        <ul class="timeline">
                                            <li class="timeline-item">
                                                <i class="fas fa-check-circle text-success"></i>
                                                <div>
                                                    <strong>Order Placed</strong>
                                                    <small class="text-muted d-block">
                                                        <?= date('M d, Y h:i A', strtotime($order['created_at'])) ?>
                                                    </small>
                                                </div>
                                            </li>
                                            
                                            <?php if ($order['status'] === 'confirmed' || $order['status'] === 'ongoing' || $order['status'] === 'completed'): ?>
                                                <li class="timeline-item">
                                                    <i class="fas fa-check-circle text-success"></i>
                                                    <div>
                                                        <strong>Payment Confirmed</strong>
                                                        <small class="text-muted d-block">
                                                            <?= date('M d, Y h:i A', strtotime($order['created_at'])) ?>
                                                        </small>
                                                    </div>
                                                </li>
                                            <?php endif; ?>
                                            
                                            <?php if ($order['status'] === 'ongoing' || $order['status'] === 'completed'): ?>
                                                <li class="timeline-item">
                                                    <i class="fas fa-check-circle text-success"></i>
                                                    <div>
                                                        <strong>Rental Started</strong>
                                                        <small class="text-muted d-block">
                                                            <?= date('M d, Y', strtotime($order['start_date'])) ?>
                                                        </small>
                                                    </div>
                                                </li>
                                            <?php endif; ?>
                                            
                                            <?php if ($order['status'] === 'completed'): ?>
                                                <li class="timeline-item">
                                                    <i class="fas fa-check-circle text-success"></i>
                                                    <div>
                                                        <strong>Rental Completed</strong>
                                                        <small class="text-muted d-block">
                                                            <?= !empty($order['completed_at']) ? date('M d, Y h:i A', strtotime($order['completed_at'])) : 'N/A' ?>
                                                        </small>
                                                    </div>
                                                </li>
                                            <?php endif; ?>
                                            
                                            <?php if ($order['status'] === 'cancelled'): ?>
                                                <li class="timeline-item">
                                                    <i class="fas fa-times-circle text-danger"></i>
                                                    <div>
                                                        <strong>Order Cancelled</strong>
                                                        <small class="text-muted d-block">
                                                            <?= !empty($order['cancelled_at']) ? date('M d, Y h:i A', strtotime($order['cancelled_at'])) : 'N/A' ?>
                                                        </small>
                                                    </div>
                                                </li>
                                            <?php endif; ?>
                                        </ul>
                                    </div>
                                </div>

                                <!-- Actions Card -->
                                <?php if ($order['status'] !== 'cancelled' && $order['status'] !== 'completed'): ?>
                                    <div class="card order-detail-card action-card">
                                        <div class="card-header bg-primary text-white">
                                            <h5 class="mb-0"><i class="fas fa-tasks"></i> Actions</h5>
                                        </div>
                                        <div class="card-body">
                                            <?php if (in_array($order['status'], ['ongoing', 'confirmed']) && $order['customer_completion_request'] == 0): ?>
                                                <button class="btn btn-success w-100 mb-2" 
                                                        onclick="requestCompletion(<?= $order['id'] ?>, '<?= htmlspecialchars($order['order_number']) ?>')">
                                                    <i class="fas fa-check-circle"></i> Request Completion
                                                </button>
                                            <?php endif; ?>
                                            
                                            <?php if ($order['customer_completion_request'] == 1): ?>
                                                <button class="btn btn-secondary w-100 mb-2" disabled>
                                                    <i class="fas fa-clock"></i> Awaiting Vendor Confirmation
                                                </button>
                                            <?php endif; ?>
                                            
                                            <?php if (in_array($order['status'], ['confirmed', 'ongoing'])): ?>
                                                <button class="btn btn-warning w-100 mb-2" 
                                                        onclick="openReportIssueModal(<?= $order['id'] ?>, '<?= htmlspecialchars($order['order_number']) ?>')">
                                                    <i class="fas fa-exclamation-circle"></i> Report Issue
                                                </button>
                                            <?php endif; ?>
                                            
                                            <?php if (!in_array($order['status'], ['completed', 'cancelled'])): ?>
                                                <button class="btn btn-danger w-100" 
                                                        onclick="openCancelModal(<?= $order['id'] ?>, '<?= htmlspecialchars($order['order_number']) ?>')">
                                                    <i class="fas fa-ban"></i> Cancel Order
                                                </button>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>

<!-- Request Completion Modal -->
<div class="modal fade" id="completionModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title">
                    <i class="fas fa-check-circle"></i> Request Completion
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form id="completionForm">
                <input type="hidden" id="completion_order_id" value="<?= $order_id ?>">
                <div class="modal-body">
                    <div class="alert alert-info">
                        <strong>Order #<?= htmlspecialchars($order['order_number']) ?></strong>
                    </div>
                    
                    <p>Have you returned the item to the vendor?</p>
                    
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" id="confirm_return" required>
                        <label class="form-check-label" for="confirm_return">
                            I confirm I have returned the item in good condition
                        </label>
                    </div>
                    
                    <div class="alert alert-warning">
                        <small><i class="fas fa-info-circle"></i> The vendor will verify and complete the order. Your security deposit will be refunded after verification.</small>
                    </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-success">Request Completion</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Report Issue Modal -->
<div class="modal fade" id="reportIssueModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-warning">
                <h5 class="modal-title">
                    <i class="fas fa-exclamation-triangle"></i> Report Issue
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="reportIssueForm">
                <input type="hidden" name="order_id" value="<?= $order_id ?>">
                <input type="hidden" name="reported_by" value="customer">
                
                <div class="modal-body">
                    <div class="alert alert-info">
                        <strong>Order #<?= htmlspecialchars($order['order_number']) ?></strong>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Issue Type</label>
                        <select class="form-select" name="issue_type" required>
                            <option value="">Select issue type</option>
                            <option value="item_damage">Item Not as Described</option>
                            <option value="late_delivery">Late Delivery</option>
                            <option value="missing_items">Missing Items/Accessories</option>
                            <option value="quality_issue">Quality Issue</option>
                            <option value="vendor_issue">Vendor Communication Issue</option>
                            <option value="other">Other</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Description</label>
                        <textarea class="form-control" name="issue_description" rows="4" required 
                                  placeholder="Please describe the issue in detail..."></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-warning">Submit Report</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Cancel Order Modal with Penalty Calculation -->
<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" value="<?= $order_id ?>">
                <input type="hidden" id="cancel_cancelled_by" value="customer">
                <input type="hidden" id="cancel_start_date" value="<?= $order['start_date'] ?>">
                <input type="hidden" id="cancel_subtotal" value="<?= $order['subtotal'] ?>">
                <input type="hidden" id="cancel_security_deposit" value="<?= $order['security_deposit'] ?>">
                
                <div class="modal-body">
                    <div class="alert alert-warning">
                        <i class="fas fa-info-circle"></i> 
                        <strong>Cancelling Order #<?= htmlspecialchars($order['order_number']) ?></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>

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

<script>
// Request Completion
function requestCompletion(orderId, orderNumber) {
    var modal = new bootstrap.Modal(document.getElementById('completionModal'));
    modal.show();
}

document.getElementById('completionForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    var orderId = document.getElementById('completion_order_id').value;
    var confirmed = document.getElementById('confirm_return').checked;
    var submitBtn = this.querySelector('button[type="submit"]');
    
    if (!confirmed) {
        alert('Please confirm that you have returned the item');
        return;
    }
    
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
    
    fetch('../api/request-completion.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'order_id=' + orderId
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            submitBtn.innerHTML = '<i class="fas fa-check"></i> Requested!';
            alert('✓ Completion request sent to vendor!\n\nYou will be notified once the vendor verifies and completes the order.');
            location.reload();
        } else {
            alert('✗ Error: ' + data.error);
            submitBtn.disabled = false;
            submitBtn.innerHTML = 'Request Completion';
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('✗ Failed to send request. Please try again.');
        submitBtn.disabled = false;
        submitBtn.innerHTML = 'Request Completion';
    });
});

// Report Issue
function openReportIssueModal(orderId, orderNumber) {
    var modal = new bootstrap.Modal(document.getElementById('reportIssueModal'));
    modal.show();
}

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

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

// Calculate penalty on page load
window.addEventListener('DOMContentLoaded', function() {
    calculatePenalty();
});

// Calculate penalty based on DAYS until start
function calculatePenalty() {
    const startDateStr = document.getElementById('cancel_start_date').value;
    const rentalAmount = parseFloat(document.getElementById('cancel_subtotal').value);
    const securityDeposit = parseFloat(document.getElementById('cancel_security_deposit').value);
    
    // Parse date
    const parts = startDateStr.split('-');
    const year = parseInt(parts[0]);
    const month = parseInt(parts[1]) - 1;
    const day = parseInt(parts[2]);
    
    const now = new Date();
    now.setHours(0, 0, 0, 0);
    
    const start = new Date(year, month, day, 0, 0, 0, 0);
    
    const timeDiff = start - now;
    const daysUntil = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
    
    let penaltyPercentage = 0;
    
    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 {
        penaltyPercentage = penaltySettings.penalty_same_day;
    }
    
    const penaltyAmount = (rentalAmount * penaltyPercentage) / 100;
    const refundAmount = (rentalAmount - penaltyAmount) + securityDeposit;
    
    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';
    }
}

// Cancel Order
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 = '';
    }
});

function openCancelModal(orderId, orderNumber) {
    document.getElementById('cancelOrderForm').reset();
    document.getElementById('cancel_other_reason_div').style.display = 'none';
    
    // Recalculate penalty
    calculatePenalty();
    
    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;
    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');
    
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
    
    const formData = new FormData();
    formData.append('order_id', orderId);
    formData.append('cancelled_by', cancelledBy);
    formData.append('reason', reason);
    
    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>

</body>
</html>