<?php
/**
 * SIMPLIFIED ORDER DETAILS - WORKING VERSION
 * This version uses basic queries and fallbacks to ensure it works
 */

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

// Require vendor authentication
Auth::requireVendor();

$page_title = "Order Details";
$active_menu = "orders";

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

if (!$order_id) {
    flash('error', 'Invalid order ID', 'danger');
    redirect('orders.php');
}

// Initialize models
$db = Database::getInstance();
$vendor = new Vendor();

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

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

// SIMPLIFIED QUERY APPROACH - Build data step by step
$order = null;

// Step 1: Get basic order data
$order_basic = $db->fetch("SELECT * FROM orders WHERE id = ?", [$order_id]);

if (!$order_basic) {
    flash('error', 'Order not found', 'danger');
    redirect('orders.php');
}

// Step 2: Check vendor permissions
$vendor_has_access = ($order_basic['vendor_id'] == $vendor_data['id']);

if (!$vendor_has_access) {
    // Check if the item belongs to this vendor (alternative permission check)
    $item_check = $db->fetch("SELECT vendor_id FROM items WHERE id = ?", [$order_basic['item_id']]);
    if (!$item_check || $item_check['vendor_id'] != $vendor_data['id']) {
        flash('error', 'You do not have permission to view this order', 'danger');
        redirect('orders.php');
    }
}

// Step 3: Get item data
$item_data = $db->fetch("SELECT * FROM items WHERE id = ?", [$order_basic['item_id']]);

// Step 4: Get vendor data (from orders table's vendor_id)
$order_vendor = $db->fetch("SELECT * FROM vendors WHERE id = ?", [$order_basic['vendor_id']]);

// Step 5: Get customer data
$customer_data = $db->fetch("SELECT * FROM customers WHERE id = ?", [$order_basic['customer_id']]);

// Step 6: Get category data
$category_data = null;
if ($item_data && !empty($item_data['category_id'])) {
    $category_data = $db->fetch("SELECT name FROM categories WHERE id = ?", [$item_data['category_id']]);
}

// Step 7: Combine all data into $order array
$order = array_merge($order_basic, [
    'item_title' => $item_data['title'] ?? 'N/A',
    'price_per_day' => $item_data['price_per_day'] ?? 0,
    'security_deposit' => $item_data['security_deposit'] ?? 0,
    'item_image' => $item_data['main_image'] ?? null,
    'item_vendor_id' => $item_data['vendor_id'] ?? null,
    'customer_name' => $customer_data ? ($customer_data['first_name'] . ' ' . $customer_data['last_name']) : 'N/A',
    'customer_phone' => $customer_data['phone'] ?? null,
    'customer_email' => $customer_data['email'] ?? null,
    'customer_avatar' => $customer_data['profile_picture'] ?? null,
    'vendor_name' => $order_vendor['business_name'] ?? 'N/A',
    'vendor_phone' => $order_vendor['phone'] ?? null,
    'category_name' => $category_data['name'] ?? 'N/A'
]);

// Helper function to safely get array values
function safeGet($array, $key, $default = null) {
    return isset($array[$key]) && $array[$key] !== null ? $array[$key] : $default;
}

// Helper function to safely escape output
function safeEscape($value) {
    return htmlspecialchars($value ?? '', ENT_QUOTES, 'UTF-8');
}

// Calculate duration with null checks
$rental_days = 0;
if (!empty($order['start_date']) && $order['start_date'] !== '0000-00-00' && 
    !empty($order['end_date']) && $order['end_date'] !== '0000-00-00') {
    try {
        $start_date = new DateTime($order['start_date']);
        $end_date = new DateTime($order['end_date']);
        $duration = $start_date->diff($end_date);
        $rental_days = $duration->days;
        $rental_days = max(1, $rental_days);
    } catch (Exception $e) {
        error_log("Date calculation error for order {$order_id}: " . $e->getMessage());
        $rental_days = $order['rental_days'] ?? 1;
    }
} else {
    $rental_days = $order['rental_days'] ?? 1;
}

// Get order timeline/history - with fallback
$timeline = [];
try {
    // First try to get from order_history table if it exists
    $timeline_sql = "SELECT * FROM order_history WHERE order_id = ? ORDER BY created_at ASC";
    $timeline = $db->fetchAll($timeline_sql, [$order_id]);
    
    if (empty($timeline)) {
        // If no history records, create basic timeline from order data
        $timeline = [
            [
                'status' => $order['status'] ?? 'pending',
                'notes' => 'Order created',
                'created_at' => $order['created_at'] ?? date('Y-m-d H:i:s')
            ]
        ];
    }
} catch (Exception $e) {
    // If order_history table doesn't exist, use basic timeline
    error_log("Timeline query failed for order {$order_id}: " . $e->getMessage());
    $timeline = [
        [
            'status' => $order['status'] ?? 'pending',
            'notes' => 'Order created',
            'created_at' => $order['created_at'] ?? date('Y-m-d H:i:s')
        ]
    ];
}

// Handle order actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!Security::validateToken($_POST['csrf_token'] ?? '')) {
        flash('error', 'Invalid security token', 'danger');
        redirect('order-details.php?id=' . $order_id);
    }
    
    $action = $_POST['action'] ?? '';
    
    switch ($action) {
        case 'update_status':
            $new_status = $_POST['status'] ?? '';
            $valid_statuses = ['pending', 'confirmed', 'ongoing', 'completed', 'cancelled'];
            
            if (in_array($new_status, $valid_statuses)) {
                try {
                    $update_sql = "UPDATE orders SET status = ?, updated_at = NOW() WHERE id = ?";
                    $result = $db->execute($update_sql, [$new_status, $order_id]);
                    
                    if ($result) {
                        // Try to add to order history if table exists
                        try {
                            $history_sql = "INSERT INTO order_history (order_id, status, notes, created_by) VALUES (?, ?, ?, ?)";
                            $notes = "Status changed to " . ucfirst($new_status) . " by vendor";
                            $db->execute($history_sql, [$order_id, $new_status, $notes, 'vendor:' . $vendor_data['id']]);
                        } catch (Exception $e) {
                            error_log("Failed to add order history: " . $e->getMessage());
                        }
                        
                        flash('success', 'Order status updated successfully!', 'success');
                    } else {
                        flash('error', 'Failed to update order status', 'danger');
                    }
                } catch (Exception $e) {
                    flash('error', 'Error updating order status: ' . $e->getMessage(), 'danger');
                }
            }
            break;
            
        case 'send_message':
            $message = trim($_POST['message'] ?? '');
            if (!empty($message)) {
                flash('info', 'Message feature coming soon!', 'info');
            }
            break;
    }
    
    redirect('order-details.php?id=' . $order_id);
}

// Handle flash messages
$flash_message = flash('message');

include '../templates/layouts/vendor/header.php';
?>

<div class="main-content">
    <div class="page-header">
        <div class="header-left">
            <h1><i class="fas fa-shopping-cart"></i> Order Details</h1>
            <p class="text-muted">Manage and track customer orders</p>
        </div>
        <div class="header-right">
            <a href="orders.php" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Back to Orders
            </a>
        </div>
    </div>

    <!-- Flash Messages -->
    <?php if ($flash_message): ?>
        <div class="alert alert-<?= safeEscape($flash_message['type']) ?>">
            <?= Security::escapeOutput($flash_message['message']) ?>
        </div>
    <?php endif; ?>
    
    
    <div class="row">
        <div class="col-lg-8">
            <!-- Order Information -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-info-circle"></i> Order Information</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><strong>Order Number</strong></label>
                            <div class="fw-bold text-primary"><?= safeEscape(safeGet($order, 'order_number', 'N/A')) ?></div>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><strong>Status</strong></label>
                            <div>
                                <?= format_status_badge(safeGet($order, 'status', 'pending')) ?>
                            </div>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><strong>Total Amount</strong></label>
                            <div class="fw-bold text-success"><?= format_money(safeGet($order, 'total_amount', 0)) ?></div>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><strong>Rental Period</strong></label>
                            <div>
                                <?= format_date(safeGet($order, 'start_date'), 'M d, Y') ?> - 
                                <?= format_date(safeGet($order, 'end_date'), 'M d, Y') ?>
                                <?php if ($rental_days > 0): ?>
                                    <br>
                                    <small class="text-muted">(<?= $rental_days ?> days)</small>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><strong>Price per Day</strong></label>
                            <div><?= format_money(safeGet($order, 'price_per_day', 0)) ?></div>
                        </div>
                        
                        <?php if (safeGet($order, 'security_deposit', 0) > 0): ?>
                            <div class="col-md-6 mb-3">
                                <label class="form-label"><strong>Security Deposit</strong></label>
                                <div><?= format_money(safeGet($order, 'security_deposit', 0)) ?></div>
                            </div>
                        <?php endif; ?>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><strong>Subtotal</strong></label>
                            <div><?= format_money(safeGet($order, 'subtotal', 0)) ?></div>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><strong>Platform Fee</strong></label>
                            <div><?= format_money(safeGet($order, 'platform_fee', 0)) ?></div>
                        </div>
                        
                        <div class="col-12 mb-3">
                            <label class="form-label"><strong>Item</strong></label>
                            <div class="d-flex align-items-center">
                                <?php if (!empty(safeGet($order, 'item_image'))): ?>
                                    <img src="<?= upload('items/' . safeGet($order, 'item_image')) ?>" 
                                         alt="<?= safeEscape(safeGet($order, 'item_title', 'Item')) ?>"
                                         class="rounded me-3"
                                         style="width: 60px; height: 60px; object-fit: cover;">
                                <?php endif; ?>
                                <div>
                                    <strong><?= safeEscape(safeGet($order, 'item_title', 'N/A')) ?></strong>
                                    <?php if (!empty(safeGet($order, 'category_name')) && safeGet($order, 'category_name') !== 'N/A'): ?>
                                        <br>
                                        <small class="text-muted"><?= safeEscape(safeGet($order, 'category_name')) ?></small>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        
                        <?php if (!empty(safeGet($order, 'delivery_address'))): ?>
                            <div class="col-12 mb-3">
                                <label class="form-label"><strong>Delivery Address</strong></label>
                                <div class="border rounded p-3 bg-light">
                                    <?= nl2br(Security::escapeOutput(safeGet($order, 'delivery_address'))) ?>
                                    <?php if (!empty(safeGet($order, 'delivery_city')) || !empty(safeGet($order, 'delivery_state'))): ?>
                                        <br>
                                        <small class="text-muted">
                                            <?= safeEscape(safeGet($order, 'delivery_city')) ?><?= !empty(safeGet($order, 'delivery_city')) && !empty(safeGet($order, 'delivery_state')) ? ', ' : '' ?>
                                            <?= safeEscape(safeGet($order, 'delivery_state')) ?>
                                        </small>
                                    <?php endif; ?>
                                    <?php if (!empty(safeGet($order, 'delivery_phone'))): ?>
                                        <br>
                                        <small class="text-muted">Phone: <?= safeEscape(safeGet($order, 'delivery_phone')) ?></small>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endif; ?>
                        
                        <?php if (!empty(safeGet($order, 'special_instructions'))): ?>
                            <div class="col-12 mb-3">
                                <label class="form-label"><strong>Special Instructions</strong></label>
                                <div class="border rounded p-3 bg-light">
                                    <?= nl2br(Security::escapeOutput(safeGet($order, 'special_instructions'))) ?>
                                </div>
                            </div>
                        <?php endif; ?>
                        
                        <?php if (!empty(safeGet($order, 'notes'))): ?>
                            <div class="col-12">
                                <label class="form-label"><strong>Customer Notes</strong></label>
                                <div class="border rounded p-3 bg-light">
                                    <?= nl2br(Security::escapeOutput(safeGet($order, 'notes'))) ?>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Order Timeline -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-history"></i> Order Timeline</h5>
                </div>
                <div class="card-body">
                    <?php if (empty($timeline)): ?>
                        <p class="text-muted text-center">No timeline data available</p>
                    <?php else: ?>
                        <div class="timeline">
                            <?php foreach ($timeline as $event): ?>
                                <div class="timeline-item mb-3">
                                    <div class="d-flex">
                                        <div class="timeline-badge me-3">
                                            <i class="fas fa-circle text-primary"></i>
                                        </div>
                                        <div class="flex-grow-1">
                                            <div class="d-flex justify-content-between">
                                                <strong class="text-capitalize"><?= safeEscape(safeGet($event, 'status', 'unknown')) ?></strong>
                                                <small class="text-muted"><?= format_date(safeGet($event, 'created_at'), 'M d, Y h:i A') ?></small>
                                            </div>
                                            <?php if (!empty(safeGet($event, 'notes'))): ?>
                                                <p class="mb-1 text-muted"><?= safeEscape(safeGet($event, 'notes')) ?></p>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </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; ?>


            
        </div>
        
        <div class="col-lg-4">
            <!-- Customer Information -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-user"></i> Customer Information</h5>
                </div>
                <div class="card-body">
                    <div class="text-center mb-3">
                        <?php if (!empty(safeGet($order, 'customer_avatar'))): ?>
                            <img src="<?= upload(safeGet($order, 'customer_avatar')) ?>" 
                                 alt="<?= safeEscape(safeGet($order, 'customer_name', 'Customer')) ?>"
                                 class="rounded-circle mb-3"
                                 style="width: 80px; height: 80px; object-fit: cover;">
                        <?php else: ?>
                            <div class="rounded-circle bg-primary text-white d-inline-flex align-items-center justify-content-center mb-3" 
                                 style="width: 80px; height: 80px; font-size: 24px;">
                                <?= strtoupper(substr(safeGet($order, 'customer_name', 'CU'), 0, 2)) ?>
                            </div>
                        <?php endif; ?>
                        <h6><?= safeEscape(safeGet($order, 'customer_name', 'N/A')) ?></h6>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label"><strong>Email</strong></label>
                        <div><?= safeEscape(safeGet($order, 'customer_email', 'N/A')) ?></div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label"><strong>Phone</strong></label>
                        <div><?= !empty(safeGet($order, 'customer_phone')) ? format_phone(safeGet($order, 'customer_phone')) : 'N/A' ?></div>
                    </div>
                    
                    <!-- Message Customer Button -->
                    <button class="btn btn-outline-primary w-100" data-bs-toggle="modal" data-bs-target="#messageModal">
                        <i class="fas fa-envelope"></i> Message Customer
                    </button>
                </div>
            </div>

            <!-- Quick Actions -->
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-cog"></i> Quick Actions</h5>
                </div>
                <div class="card-body">
                    <form method="POST" class="mb-3">
                        <input type="hidden" name="csrf_token" value="<?= Security::generateToken() ?>">
                        <input type="hidden" name="action" value="update_status">
                        
                        <label class="form-label"><strong>Update Status</strong></label>
                        <select name="status" class="form-control mb-2" onchange="this.form.submit()">
                            <option value="pending" <?= safeGet($order, 'status') === 'pending' ? 'selected' : '' ?>>Pending</option>
                            <option value="confirmed" <?= safeGet($order, 'status') === 'confirmed' ? 'selected' : '' ?>>Confirmed</option>
                            <option value="ongoing" <?= safeGet($order, 'status') === 'ongoing' ? 'selected' : '' ?>>Ongoing</option>
                            <option value="completed" <?= safeGet($order, 'status') === 'completed' ? 'selected' : '' ?>>Completed</option>
                            <option value="cancelled" <?= safeGet($order, 'status') === 'cancelled' ? 'selected' : '' ?>>Cancelled</option>
                        </select>
                        <small class="text-muted">Select to update status immediately</small>
                    </form>
                    
                    <hr>
                    
                    <div class="d-grid gap-2">
                        <a href="item-details.php?id=<?= safeGet($order, 'item_id') ?>" class="btn btn-outline-info">
                            <i class="fas fa-box"></i> View Item
                        </a>
                        
                        <?php if (safeGet($order, 'status') === 'completed'): ?>
                            <button class="btn btn-outline-success" onclick="issueRefund(<?= $order_id ?>)">
                                <i class="fas fa-money-bill-wave"></i> Process Refund
                            </button>
                        <?php endif; ?>
                        
                        <?php if (in_array(safeGet($order, 'status'), ['pending', 'confirmed'])): ?>
                            <button type="button" class="btn btn-outline-danger" 
                                    onclick="showCancelModal(<?= $order_id ?>)">
                                <i class="fas fa-times"></i> Cancel Order
                            </button>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Order Dates -->
            <div class="card mt-4">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-calendar"></i> Important Dates</h5>
                </div>
                <div class="card-body">
                    <div class="mb-2">
                        <small class="text-muted">Order Created</small>
                        <div><?= format_date(safeGet($order, 'created_at'), 'M d, Y h:i A') ?></div>
                    </div>
                    
                    <?php if (!empty(safeGet($order, 'confirmed_at'))): ?>
                        <div class="mb-2">
                            <small class="text-muted">Confirmed At</small>
                            <div><?= format_date(safeGet($order, 'confirmed_at'), 'M d, Y h:i A') ?></div>
                        </div>
                    <?php endif; ?>
                    
                    <?php if (!empty(safeGet($order, 'started_at'))): ?>
                        <div class="mb-2">
                            <small class="text-muted">Rental Started</small>
                            <div><?= format_date(safeGet($order, 'started_at'), 'M d, Y h:i A') ?></div>
                        </div>
                    <?php endif; ?>
                    
                    <?php if (!empty(safeGet($order, 'completed_at'))): ?>
                        <div class="mb-2">
                            <small class="text-muted">Completed At</small>
                            <div><?= format_date(safeGet($order, 'completed_at'), 'M d, Y h:i A') ?></div>
                        </div>
                    <?php endif; ?>
                    
                    <?php if (!empty(safeGet($order, 'cancelled_at'))): ?>
                        <div class="mb-2">
                            <small class="text-muted">Cancelled At</small>
                            <div><?= format_date(safeGet($order, 'cancelled_at'), 'M d, Y h:i A') ?></div>
                        </div>
                    <?php endif; ?>
                    
                    <?php if (!empty(safeGet($order, 'updated_at'))): ?>
                        <div>
                            <small class="text-muted">Last Updated</small>
                            <div><?= format_date(safeGet($order, 'updated_at'), 'M d, Y h:i A') ?></div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Message Modal -->
<div class="modal fade" id="messageModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Message Customer</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="csrf_token" value="<?= Security::generateToken() ?>">
                <input type="hidden" name="action" value="send_message">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Message</label>
                        <textarea name="message" class="form-control" rows="4" 
                                  placeholder="Type your message to the customer..." required></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Send Message</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Cancel Order Modal -->
<div class="modal fade" id="cancelModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Cancel Order</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="cancelForm" method="GET" action="order-cancel.php">
                <input type="hidden" name="id" id="cancelOrderId">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Cancellation Reason</label>
                        <select name="reason" class="form-control" required>
                            <option value="">Select a reason</option>
                            <option value="Item not available">Item not available</option>
                            <option value="Schedule conflict">Schedule conflict</option>
                            <option value="Customer request">Customer request</option>
                            <option value="Pricing issue">Pricing issue</option>
                            <option value="Other">Other reason</option>
                        </select>
                    </div>
                    <div class="mb-3" id="otherReasonContainer" style="display: none;">
                        <label class="form-label">Specify Reason</label>
                        <input type="text" name="reason_other" class="form-control" placeholder="Enter cancellation reason">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-danger">Cancel Order</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function showCancelModal(orderId) {
    document.getElementById('cancelOrderId').value = orderId;
    var cancelModal = new bootstrap.Modal(document.getElementById('cancelModal'));
    cancelModal.show();
}

function issueRefund(orderId) {
    if (confirm('Are you sure you want to process a refund for this order?')) {
        alert('Refund processing feature coming soon!');
    }
}

// Handle "Other" reason selection
document.querySelector('select[name="reason"]').addEventListener('change', function() {
    const otherContainer = document.getElementById('otherReasonContainer');
    if (this.value === 'Other') {
        otherContainer.style.display = 'block';
    } else {
        otherContainer.style.display = 'none';
    }
});

// Handle form submission for "Other" reason
document.getElementById('cancelForm').addEventListener('submit', function(e) {
    const reasonSelect = document.querySelector('select[name="reason"]');
    const otherInput = document.querySelector('input[name="reason_other"]');
    
    if (reasonSelect.value === 'Other' && otherInput.value.trim() === '') {
        e.preventDefault();
        alert('Please specify the cancellation reason');
        return;
    }
    
    // If "Other" is selected, use the custom reason
    if (reasonSelect.value === 'Other') {
        // Remove the select and add the custom reason as URL parameter
        this.action += '?id=' + document.getElementById('cancelOrderId').value + 
                      '&reason=' + encodeURIComponent(otherInput.value.trim());
    }
});

// Auto-hide success messages
setTimeout(function() {
    const alerts = document.querySelectorAll('.alert-success');
    alerts.forEach(alert => {
        alert.style.transition = 'opacity 0.5s';
        alert.style.opacity = '0';
        setTimeout(() => alert.remove(), 500);
    });
}, 3000);
</script>

<style>
.timeline-badge {
    width: 20px;
    display: flex;
    justify-content: center;
}

.timeline-item {
    position: relative;
}

.timeline-item:not(:last-child):after {
    content: '';
    position: absolute;
    left: 10px;
    top: 25px;
    bottom: -15px;
    width: 2px;
    background: #e9ecef;
}
</style>


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

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

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

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

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

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

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

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