<?php
// Vendor Portal - Order Details
require_once('../includes/vendor-security.php');

include_once('../../includes/config.php');
include_once('../../includes/settings.php');

$vendorId = $_SESSION['vendor_id'];
$orderId = intval($_GET['id']);

// Get order details - verify vendor ownership
$orderQuery = mysqli_query($con, "SELECT o.*, o.gps_address, o.delivery_method, o.delivery_fee, 
                                  p.productName, p.productImage1, p.productCompany, p.vendor_id, p.productPrice, p.is_abroad,
                                  u.email, ud.name, ud.contactno, 
                                  ud.billingAddress, ud.billingCity, ud.billingState, ud.billingPincode,
                                  ud.shippingAddress, ud.shippingCity, ud.shippingState, ud.shippingPincode,
                                  ps.station_name, ps.address as ps_address, c.city_name as ps_city, s.state_name as ps_state,
                                  ds.state_name as d_state_name, dc.city_name as d_city_name
                                  FROM orders o 
                                  JOIN products p ON o.productId = p.id 
                                  JOIN users u ON o.userId = u.id 
                                  LEFT JOIN user_details ud ON ud.user_id = u.id 
                                  LEFT JOIN pickup_stations ps ON o.pickup_station_id = ps.id
                                  LEFT JOIN cities c ON ps.city_id = c.id
                                  LEFT JOIN states s on ps.state_id = s.id
                                  LEFT JOIN states ds on o.delivery_state = ds.id
                                  LEFT JOIN cities dc on o.delivery_city = dc.id
                                  WHERE o.id='$orderId' AND p.vendor_id='$vendorId'
                                  LIMIT 1");

if (mysqli_num_rows($orderQuery) == 0) {
	echo "<script>alert('Order not found or unauthorized access!'); window.location.href='all-orders.php';</script>";
	exit;
}

$order = mysqli_fetch_array($orderQuery);

// Get tracking history
$trackingQuery = mysqli_query($con, "SELECT * FROM ordertrackhistory WHERE orderId='$orderId' ORDER BY id DESC");
?>

<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="utf-8" />
	<title>Order #<?php echo $orderId; ?> - Vendor Portal</title>
	<link href="../../__admin__/css/styles.css" rel="stylesheet" />
	<link href="../../__admin__/css/admin-professional.css" rel="stylesheet" />
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
	<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/js/all.min.js"></script>
</head>

<body class="sb-nav-fixed">
	<?php include_once('../includes/header.php'); ?>

	<div id="layoutSidenav">
		<?php include_once('../includes/sidebar.php'); ?>

		<div id="layoutSidenav_content">
			<main>
				<div class="container-fluid px-4">
					<!-- Page Header -->
					<div class="page-header mt-4">
						<div>
							<h1><i class="fas fa-file-invoice me-2"></i> Order Details</h1>
							<p>Order #<?php echo $orderId; ?></p>
						</div>
						<a href="all-orders.php" class="btn btn-outline-primary">
							<i class="fas fa-arrow-left me-2"></i>Back to Orders
						</a>
					</div>

										<div class="row">
						<!-- Customer & Order Overview -->
						<div class="col-lg-8">
							<div class="card mb-4">
								<div class="card-header">
									<i class="fas fa-info-circle me-1"></i> Order Information
								</div>
								<div class="card-body">
									<div class="row">
										<div class="col-md-6">
											<div class="detail-label">Customer Name</div>
											<div class="detail-value"><?php echo htmlentities($order['name']); ?></div>

											<div class="detail-label mt-3">Order Date</div>
											<div class="detail-value"><?php echo date('F d, Y - h:i A', strtotime($order['orderDate'])); ?></div>

											<div class="detail-label mt-3">Delivery Method</div>
											<div class="detail-value">
												<?php
												$delivery_method = $order['delivery_method'] ?? 'pickup';
												if ($delivery_method == 'door') {
													echo '<span class="badge bg-success"><i class="fas fa-shipping-fast"></i> Door Delivery</span>';
												} else {
													echo '<span class="badge bg-info"><i class="fas fa-store"></i> Pickup Station</span>';
												}
												?>
											</div>
										</div>
										<div class="col-md-6">
											<div class="detail-label">Order Status</div>
											<div class="detail-value">
												<?php
												$status = $order['orderStatus'] ?: 'Pending';
												$statusClass = 'warning';
												if ($status == 'Delivered')
													$statusClass = 'success';
												elseif ($status == 'Dispatched' || $status == 'In Transit')
													$statusClass = 'info';
												elseif ($status == 'Cancelled')
													$statusClass = 'danger';
												?>
												<span class="badge bg-<?php echo $statusClass; ?>"><?php echo $status; ?></span>
											</div>

											<div class="detail-label mt-3">Payment Method</div>
											<div class="detail-value"><?php echo htmlentities($order['paymentMethod'] ?: 'Cash on Delivery'); ?></div>
										</div>
									</div>
								</div>
							</div>

							<!-- Product Details -->
							<div class="card mb-4">
								<div class="card-header">
									<i class="fas fa-box me-1"></i> Product Details
								</div>
								<div class="card-body">
									<div class="table-responsive">
										<table class="table table-bordered">
											<thead class="table-light">
												<tr>
													<th>Image</th>
													<th>Product Name</th>
													<th>Price</th>
													<th>Quantity</th>
													<th>Total</th>
												</tr>
											</thead>
											<tbody>
												<tr>
													<td>
														<?php if ($order['productImage1']): ?>
																<img src="../../__admin__/productimages/<?php echo $order['productId']; ?>/<?php echo $order['productImage1']; ?>"
																	style="width: 60px; height: 60px; object-fit: cover; border-radius: 4px;">
														<?php else: ?>
																<div style="width: 60px; height: 60px; background: #f0f0f0; border-radius: 4px;"></div>
														<?php endif; ?>
													</td>
													<td>
														<strong><?php echo htmlentities($order['productName']); ?></strong><br>
														<small class="text-muted">Brand: <?php echo htmlentities($order['productCompany'] ?: 'N/A'); ?></small>
														<?php if ($order['is_abroad'] == 1): ?>
																<br><span class="badge bg-warning text-dark"><i class="fas fa-globe"></i> Abroad</span>
														<?php endif; ?>
													</td>
													<td>GHS <?php echo number_format($order['productPrice'], 2); ?></td>
													<td><?php echo $order['quantity']; ?></td>
													<td><strong class="text-primary">GHS <?php echo number_format($order['productPrice'] * $order['quantity'], 2); ?></strong></td>
												</tr>
											</tbody>
										</table>
									</div>
								</div>
							</div>
						</div>

						<!-- Sidebar -->
						<div class="col-lg-4">
							<!-- Status History -->
							<div class="card">
								<div class="card-header">
									<h5 class="mb-0"><i class="fas fa-history me-2"></i>Status History</h5>
								</div>
								<div class="card-body">
									<?php if (mysqli_num_rows($trackingQuery) > 0): ?>
											<div class="tracking-timeline">
												<?php while ($track = mysqli_fetch_array($trackingQuery)): ?>
														<div class="timeline-item mb-3">
															<strong><?php echo htmlentities($track['status']); ?></strong>
															<br><small class="text-muted">
																<?php echo date('M d, Y h:i A', strtotime($track['postingDate'])); ?>
															</small>
															<?php if (!empty($track['remark'])): ?>
																	<p class="mb-0 mt-1 small"><?php echo htmlentities($track['remark']); ?></p>
															<?php endif; ?>
														</div>
												<?php endwhile; ?>
											</div>
									<?php else: ?>
											<p class="text-muted mb-0">No tracking history available</p>
									<?php endif; ?>
								</div>
							</div>
						</div>
					</div>
				</div>
			</main>
		</div>
	</div>

	<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>

</html>