<?php
/**
 * ============================================================================
 * buyer/order-details.php
 * Detailed Order View - Complete order information with tracking
 * ============================================================================
 */

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/BuyerSystem.php';

if (!isLoggedIn()) {
    header('Location: ' . APP_URL . '/auth/login.php');
    exit();
}

if (getUserType() !== 'buyer') {
    header('Location: ' . APP_URL . '/dashboard/');
    exit();
}

use App\Database;
$database = Database::getInstance();
$db = $database->getConnection();
$currentUserId = getUserId();
$buyerSystem = new BuyerSystem($database, $currentUserId);

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

if (!$orderId) {
    header('Location: ' . APP_URL . '/buyer/orders.php');
    exit();
}

// Get order details
$sql = "SELECT o.*, p.product_name, p.category, p.images, p.unit,
               seller.full_name as seller_name, seller.phone_number as seller_phone,
               seller.email as seller_email,
               d.district_name as seller_district, s.subcounty_name as seller_subcounty
        FROM orders o
        INNER JOIN products p ON o.product_id = p.id
        INNER JOIN users seller ON o.seller_id = seller.id
        LEFT JOIN districts d ON seller.district_id = d.id
        LEFT JOIN subcounties s ON seller.subcounty_id = s.id
        WHERE o.id = ? AND o.buyer_id = ?";

$stmt = $db->prepare($sql);
$stmt->execute([$orderId, $currentUserId]);
$order = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$order) {
    $_SESSION['flash_message'] = 'Order not found';
    $_SESSION['flash_type'] = 'error';
    header('Location: ' . APP_URL . '/buyer/orders.php');
    exit();
}

// Get order timeline
$timeline = getOrderTimeline($order);

$pageTitle = 'Order Details - ' . $order['order_number'];
$breadcrumbs = [
    ['title' => 'Orders', 'url' => APP_URL . '/buyer/orders.php'],
    ['title' => 'Order Details', 'url' => '']
];

require_once __DIR__ . '/includes/base.php';
require_once __DIR__ . '/includes/helpers.php';
renderBuyerHeader($pageTitle, $breadcrumbs);
?>

<style>
    .order-details-card {
        background: white;
        border-radius: 12px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        margin-bottom: 1.5rem;
    }
    
    .order-header {
        background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
        color: white;
        padding: 2rem;
        border-radius: 12px 12px 0 0;
    }
    
    .timeline-container {
        position: relative;
        padding: 2rem 0;
    }
    
    .timeline-item {
        position: relative;
        padding-left: 3rem;
        padding-bottom: 2rem;
    }
    
    .timeline-item:last-child {
        padding-bottom: 0;
    }
    
    .timeline-item::before {
        content: '';
        position: absolute;
        left: 1rem;
        top: 0;
        bottom: -2rem;
        width: 2px;
        background: #e5e7eb;
    }
    
    .timeline-item:last-child::before {
        display: none;
    }
    
    .timeline-icon {
        position: absolute;
        left: 0;
        top: 0;
        width: 2.5rem;
        height: 2.5rem;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.2rem;
        z-index: 1;
    }
    
    .timeline-icon.completed {
        background: #10b981;
        color: white;
    }
    
    .timeline-icon.pending {
        background: #e5e7eb;
        color: #6b7280;
    }
    
    .product-image-large {
        width: 100%;
        max-width: 400px;
        height: 300px;
        object-fit: cover;
        border-radius: 12px;
    }
    
    .info-row {
        padding: 1rem;
        border-bottom: 1px solid #e5e7eb;
    }
    
    .info-row:last-child {
        border-bottom: none;
    }
    
    .info-label {
        font-weight: 600;
        color: #6b7280;
        margin-bottom: 0.25rem;
        font-size: 0.875rem;
    }
    
    .info-value {
        color: #1f2937;
        font-size: 1rem;
    }
</style>

<!-- Order Header -->
<div class="order-details-card">
    <div class="order-header">
        <div class="row align-items-center">
            <div class="col-md-8">
                <h3 class="mb-2">
                    <i class="bi bi-receipt me-2"></i>
                    <?php echo htmlspecialchars($order['order_number']); ?>
                </h3>
                <p class="mb-0 opacity-90">
                    <i class="bi bi-calendar me-2"></i>
                    Placed on <?php echo date('F j, Y', strtotime($order['created_at'])); ?>
                    <span class="ms-3">
                        <i class="bi bi-clock me-1"></i>
                        <?php echo date('h:i A', strtotime($order['created_at'])); ?>
                    </span>
                </p>
            </div>
            <div class="col-md-4 text-md-end mt-3 mt-md-0">
                <div class="mb-2">
                    <?php echo getOrderStatusBadge($order['status']); ?>
                    <?php echo getPaymentStatusBadge($order['payment_status']); ?>
                </div>
                <h4 class="mb-0"><?php echo formatCurrency($order['total_amount']); ?></h4>
                <small class="opacity-75">Total Amount</small>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- Left Column -->
    <div class="col-lg-8">
        <!-- Product Details -->
        <div class="order-details-card">
            <div class="card-body p-4">
                <h5 class="mb-4"><i class="bi bi-box me-2"></i>Product Details</h5>
                
                <div class="row">
                    <div class="col-md-5">
                        <?php
                        $productImage = getProductImage($order['images']);
                        ?>
                        <img src="<?php echo $productImage; ?>" 
                             class="product-image-large" 
                             alt="<?php echo htmlspecialchars($order['product_name']); ?>">
                    </div>
                    
                    <div class="col-md-7">
                        <h4 class="mb-3"><?php echo htmlspecialchars($order['product_name']); ?></h4>
                        
                        <div class="mb-3">
                            <span class="badge bg-primary">
                                <i class="<?php echo getCategoryIcon($order['category']); ?> me-1"></i>
                                <?php echo ucfirst(str_replace('_', ' ', $order['category'])); ?>
                            </span>
                        </div>
                        
                        <div class="info-row">
                            <div class="info-label">Quantity Ordered</div>
                            <div class="info-value">
                                <strong><?php echo number_format($order['quantity'], 2); ?></strong> 
                                <?php echo htmlspecialchars($order['unit']); ?>
                            </div>
                        </div>
                        
                        <div class="info-row">
                            <div class="info-label">Price per Unit</div>
                            <div class="info-value text-success">
                                <strong><?php echo formatCurrency($order['unit_price']); ?></strong>
                            </div>
                        </div>
                        
                        <div class="info-row">
                            <div class="info-label">Total Amount</div>
                            <div class="info-value">
                                <h5 class="mb-0 text-success">
                                    <?php echo formatCurrency($order['total_amount']); ?>
                                </h5>
                            </div>
                        </div>
                        
                        <?php if (!empty($order['notes'])): ?>
                        <div class="info-row">
                            <div class="info-label">Order Notes</div>
                            <div class="info-value">
                                <?php echo nl2br(htmlspecialchars($order['notes'])); ?>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Delivery Information -->
        <?php if (!empty($order['delivery_address'])): ?>
        <div class="order-details-card">
            <div class="card-body p-4">
                <h5 class="mb-3"><i class="bi bi-truck me-2"></i>Delivery Information</h5>
                
                <div class="info-row">
                    <div class="info-label">Delivery Address</div>
                    <div class="info-value">
                        <?php echo nl2br(htmlspecialchars($order['delivery_address'])); ?>
                    </div>
                </div>
                
                <?php if ($order['status'] === 'processing'): ?>
                <div class="info-row">
                    <div class="info-label">Estimated Delivery</div>
                    <div class="info-value text-primary">
                        <i class="bi bi-clock me-1"></i>
                        <?php echo getEstimatedDelivery($order['created_at']); ?>
                    </div>
                </div>
                <?php endif; ?>
                
                <?php if ($order['status'] === 'completed'): ?>
                <div class="info-row">
                    <div class="info-label">Delivered On</div>
                    <div class="info-value text-success">
                        <i class="bi bi-check-circle-fill me-1"></i>
                        <?php echo date('F j, Y', strtotime($order['updated_at'])); ?>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- Payment Information -->
        <div class="order-details-card">
            <div class="card-body p-4">
                <h5 class="mb-3"><i class="bi bi-wallet2 me-2"></i>Payment Information</h5>
                
                <div class="info-row">
                    <div class="info-label">Payment Status</div>
                    <div class="info-value">
                        <?php echo getPaymentStatusBadge($order['payment_status']); ?>
                    </div>
                </div>
                
                <?php if (!empty($order['payment_method'])): ?>
                <div class="info-row">
                    <div class="info-label">Payment Method</div>
                    <div class="info-value">
                        <i class="<?php echo getPaymentMethodIcon($order['payment_method']); ?> me-1"></i>
                        <?php echo ucfirst(str_replace('_', ' ', $order['payment_method'])); ?>
                    </div>
                </div>
                <?php endif; ?>
                
                <div class="info-row">
                    <div class="info-label">Order Total</div>
                    <div class="info-value">
                        <h5 class="mb-0 text-success">
                            <?php echo formatCurrency($order['total_amount']); ?>
                        </h5>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Right Column -->
    <div class="col-lg-4">
        <!-- Seller Information -->
        <div class="order-details-card">
            <div class="card-body p-4">
                <h5 class="mb-3"><i class="bi bi-person me-2"></i>Seller Information</h5>
                
                <div class="info-row">
                    <div class="info-label">Seller Name</div>
                    <div class="info-value">
                        <strong><?php echo htmlspecialchars($order['seller_name']); ?></strong>
                    </div>
                </div>
                
                <div class="info-row">
                    <div class="info-label">Phone Number</div>
                    <div class="info-value">
                        <i class="bi bi-phone me-1"></i>
                        <?php echo htmlspecialchars($order['seller_phone']); ?>
                    </div>
                </div>
                
                <?php if (!empty($order['seller_email'])): ?>
                <div class="info-row">
                    <div class="info-label">Email</div>
                    <div class="info-value">
                        <i class="bi bi-envelope me-1"></i>
                        <?php echo htmlspecialchars($order['seller_email']); ?>
                    </div>
                </div>
                <?php endif; ?>
                
                <div class="info-row">
                    <div class="info-label">Location</div>
                    <div class="info-value">
                        <i class="bi bi-geo-alt me-1"></i>
                        <?php 
                        $location = [];
                        if (!empty($order['seller_subcounty'])) $location[] = $order['seller_subcounty'];
                        if (!empty($order['seller_district'])) $location[] = $order['seller_district'];
                        echo htmlspecialchars(implode(', ', $location) ?: 'Not specified');
                        ?>
                    </div>
                </div>
                
                <div class="mt-3">
                    <a href="<?php echo APP_URL; ?>/chat/?user=<?php echo $order['seller_id']; ?>" class="btn btn-primary w-100">
                        <i class="bi bi-chat-dots me-2"></i>Contact Seller
                    </a>
                </div>
            </div>
        </div>
        
        <!-- Order Timeline -->
        <div class="order-details-card">
            <div class="card-body p-4">
                <h5 class="mb-4"><i class="bi bi-clock-history me-2"></i>Order Timeline</h5>
                
                <div class="timeline-container">
                    <?php foreach ($timeline as $event): ?>
                    <div class="timeline-item">
                        <div class="timeline-icon <?php echo $event['completed'] ? 'completed' : 'pending'; ?>">
                            <i class="bi <?php echo $event['icon']; ?>"></i>
                        </div>
                        <div>
                            <strong><?php echo $event['status']; ?></strong>
                            <?php if ($event['date']): ?>
                            <div class="text-muted small">
                                <?php echo date('M j, Y - h:i A', strtotime($event['date'])); ?>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        
        <!-- Actions -->
        <div class="order-details-card">
            <div class="card-body p-4">
                <h5 class="mb-3"><i class="bi bi-gear me-2"></i>Actions</h5>
                
                <div class="d-grid gap-2">
                    <a href="<?php echo APP_URL; ?>/buyer/invoice.php?order=<?php echo $order['id']; ?>" 
                       class="btn btn-outline-primary" target="_blank">
                        <i class="bi bi-file-earmark-pdf me-2"></i>Download Invoice
                    </a>
                    
                    <?php if (canCancelOrder($order)): ?>
                    <button type="button" class="btn btn-outline-danger" 
                            onclick="cancelOrder(<?php echo $order['id']; ?>, '<?php echo htmlspecialchars($order['order_number']); ?>')">
                        <i class="bi bi-x-circle me-2"></i>Cancel Order
                    </button>
                    <?php endif; ?>
                    
                    <?php if (canReviewOrder($order)): ?>
                    <a href="<?php echo APP_URL; ?>/buyer/review-order.php?id=<?php echo $order['id']; ?>" 
                       class="btn btn-outline-warning">
                        <i class="bi bi-star me-2"></i>Leave Review
                    </a>
                    <?php endif; ?>
                    
                    <?php if ($order['status'] === 'completed'): ?>
                    <a href="<?php echo APP_URL; ?>/buyer/reorder.php?id=<?php echo $order['id']; ?>" 
                       class="btn btn-success">
                        <i class="bi bi-arrow-repeat me-2"></i>Reorder
                    </a>
                    <?php endif; ?>
                    
                    <a href="<?php echo APP_URL; ?>/buyer/orders.php" class="btn btn-outline-secondary">
                        <i class="bi bi-arrow-left me-2"></i>Back to Orders
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Cancel Order Form -->
<form id="cancelOrderForm" method="POST" action="<?php echo APP_URL; ?>/buyer/orders.php" style="display: none;">
    <input type="hidden" name="action" value="cancel_order">
    <input type="hidden" name="order_id" id="cancelOrderId">
</form>

<script>
function cancelOrder(orderId, orderNumber) {
    Swal.fire({
        title: 'Cancel Order?',
        html: `Are you sure you want to cancel order <strong>${orderNumber}</strong>?<br><small class="text-muted">This action cannot be undone.</small>`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#ef4444',
        cancelButtonColor: '#6b7280',
        confirmButtonText: 'Yes, Cancel Order',
        cancelButtonText: 'No, Keep It'
    }).then((result) => {
        if (result.isConfirmed) {
            document.getElementById('cancelOrderId').value = orderId;
            document.getElementById('cancelOrderForm').submit();
        }
    });
}
</script>

<?php
renderBuyerFooter();
?>