<?php
// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
	session_start();
}

// Enable error reporting for development
error_reporting(E_ALL);
ini_set('display_errors', 0); // Don't display errors on page
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/php_errors.log');

require_once('../includes/admin-security.php');
include_once('includes/config.php');

// Access Check
if (!has_permission('manage_orders')) {
	echo "<script>alert('Access Denied. Redirecting to Dashboard...'); window.location.href='dashboard.php';</script>";
	exit();
}

// Handle Update Order
if (isset($_POST['update_order'])) {
	$order_id = intval($_POST['order_id']);
	$status = $_POST['status'];
	$remark = $_POST['remark'];
	$query = mysqli_query($con, "insert into ordertrackhistory(orderId,status,remark)
values('$order_id','$status','$remark')");
	$sql = mysqli_query($con, "update orders set orderStatus='$status' where id='$order_id'");
	echo "
<script>alert('Order updated successfully');</script>";
}

$orderid = intval($_GET['orderid'] ? $_GET['orderid'] : $_GET['oid']);
?>
<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="utf-8" />
	<meta http-equiv="X-UA-Compatible" content="IE=edge" />
	<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
	<title>Awesome Mall | Order Details</title>
	<link href="https://cdn.jsdelivr.net/npm/simple-datatables@latest/dist/style.css" rel="stylesheet" />
	<link href="css/styles.css" rel="stylesheet" />
	<link href="css/admin-professional.css" rel="stylesheet" />
	<style>
		.detail-label {
			font-weight: 600;
			color: #6c757d;
			font-size: 0.85rem;
			text-transform: uppercase;
			margin-bottom: 0.25rem;
		}

		.detail-value {
			font-size: 1rem;
			color: #212529;
			margin-bottom: 1rem;
		}

		.product-img-thumb {
			width: 80px;
			height: 80px;
			object-fit: cover;
			border: 1px solid #dee2e6;
			border-radius: 4px;
		}
	</style>
	<script src="js/all.min.js" crossorigin="anonymous"></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 Follow Up</h1>
							<p>Order #<?php echo $orderid; ?> Details</p>
						</div>
						<a href="all-orders.php" class="btn btn-outline-secondary btn-sm"><i
								class="fas fa-arrow-left me-1"></i> Back to List</a>
					</div>

					<?php
					$query = mysqli_query($con, "select orders.id as oid,orders.gps_address,orders.delivery_method,orders.delivery_fee,user_details.name as username,users.email as useremail,user_details.contactno as usercontact,user_details.shippingAddress as shippingaddress,user_details.shippingCity as shippingcity,user_details.shippingState as shippingstate,user_details.shippingPincode as shippingpincode,products.productName as productname,products.shippingCharge as shippingcharge,orders.quantity as quantity,orders.orderDate as orderdate,products.productPrice as productprice,user_details.billingAddress,user_details.billingState,user_details.billingCity,user_details.billingPincode,products.id as pid,productImage1,shippingcharge,
					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 
					join users on orders.userId=users.id 
					left join user_details on user_details.user_id=users.id 
					join products on products.id=orders.productId 
					left join pickup_stations ps on orders.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 orders.delivery_state = ds.id
					left join cities dc on orders.delivery_city = dc.id
					where orders.id='$orderid'");
					$row = mysqli_fetch_array($query);
					if ($row) {
						?>

						<div class="row">
							<!-- Customer & Order Overview -->
							<div class="col-lg-8">
								<div class="card mb-4">
									<div class="card-header">
										<i class="fas fa-user me-1"></i> Customer & Order Info
									</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($row['username']); ?>
												</div>

												<div class="detail-label">Contact Info</div>
												<div class="detail-value">
													<?php echo htmlentities($row['useremail']); ?><br>
													<?php echo htmlentities($row['usercontact']); ?>
												</div>

												<div class="detail-label">Order Date</div>
												<div class="detail-value"><?php echo htmlentities($row['orderdate']); ?>
												</div>

												<div class="detail-label mt-3">Delivery Method</div>
												<div class="detail-value">
													<?php
													$delivery_method = $row['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 class="detail-label mt-3">Delivery Fee</div>
												<div class="detail-value">
													<strong class="text-primary">GHS
														<?php echo number_format($row['delivery_fee'] ?? 0, 2); ?></strong>
												</div>
											</div>
											<div class="col-md-6">
												<?php if (!empty($row['station_name'])) { ?>
													<div class="detail-label text-primary">Pickup Station</div>
													<div class="detail-value border-start border-primary ps-2">
														<strong><?php echo htmlentities($row['station_name']); ?></strong><br>
														<?php echo htmlentities($row['ps_address']); ?><br>
														<?php echo htmlentities($row['ps_city'] . ", " . $row['ps_state']); ?>
													</div>
												<?php } else { ?>
													<div class="detail-label">Shipping Address</div>
													<div class="detail-value">
														<?php echo htmlentities($row['shippingaddress']); ?><br>
														<?php if (!empty($row['d_state_name'])) {
															echo htmlentities($row['d_city_name'] . ", " . $row['d_state_name']);
														} else {
															echo htmlentities($row['shippingcity'] . ", " . $row['shippingstate'] . " - " . $row['shippingpincode']);
														} ?>

														<?php if (!empty($row['gps_address'])) { ?>
															<div class="mt-2 pt-2 border-top">
																<small class="text-primary fw-bold uppercase">GPS
																	Address:</small><br>
																<span
																	class="badge bg-primary"><?php echo htmlentities($row['gps_address']); ?></span>
															</div>
														<?php } ?>
													</div>
												<?php } ?>

												<div class="detail-label">Billing Address</div>
												<div class="detail-value">
													<?php echo htmlentities($row['billingAddress']); ?><br>
													<?php echo htmlentities($row['billingCity'] . ", " . $row['billingState'] . " - " . $row['billingPincode']); ?>
												</div>
											</div>
										</div>
									</div>
								</div>

								<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>Qty</th>
														<th>Shipping</th>
														<th class="text-end">Total</th>
													</tr>
												</thead>
												<tbody>
													<tr>
														<td>
															<img src="productimages/<?php echo htmlentities($row['pid'] . "/" . $row['productImage1']); ?>"
																class="product-img-thumb" alt="Product">
														</td>
														<td class="align-middle">
															<?php echo htmlentities($row['productname']); ?>
														</td>
														<td class="align-middle">
															$<?php echo htmlentities($row['productprice']); ?></td>
														<td class="align-middle">
															<?php echo htmlentities($row['quantity']); ?>
														</td>
														<td class="align-middle">
															$<?php echo htmlentities($row['shippingcharge']); ?></td>
														<td class="align-middle text-end fw-bold">
															$<?php echo htmlentities($row['quantity'] * $row['productprice'] + $row['shippingcharge']); ?>
														</td>
													</tr>
												</tbody>
											</table>
										</div>
									</div>
								</div>
							</div>

							<!-- Status & Tracking -->
							<div class="col-lg-4">
								<!-- Update Status Form -->
								<div class="card mb-4 border-primary">
									<div class="card-header bg-primary text-white">
										<i class="fas fa-edit me-1"></i> Update Status
									</div>
									<div class="card-body">
										<?php if ($row['currentStatus'] == 'Delivered' || $row['currentStatus'] == 'Cancelled') { ?>
											<div class="alert alert-warning mb-0">
												<i class="fas fa-lock me-2"></i> Order is
												<strong><?php echo htmlentities($row['currentStatus']); ?></strong>. No further
												updates allowed.
											</div>
										<?php } else { ?>
											<form method="post">
												<input type="hidden" name="order_id" value="<?php echo $orderid; ?>">
												<div class="mb-3">
													<label class="form-label detail-label">New Status</label>
													<select name="status" class="form-select" required>
														<option value="">Select Status</option>
														<option value="Packed">Packed</option>
														<option value="Dispatched">Dispatched</option>
														<option value="In Transit">In Transit</option>
														<option value="Out For Delivery">Out For Delivery</option>
														<option value="Delivered">Delivered</option>
														<option value="Cancelled">Cancelled</option>
													</select>
												</div>
												<div class="mb-3">
													<label class="form-label detail-label">Remark</label>
													<textarea name="remark" class="form-control" rows="4" required
														placeholder="Enter tracking info or comments..."></textarea>
												</div>
												<button type="submit" name="update_order" class="btn btn-primary w-100">Update
													Order</button>
											</form>
										<?php } ?>
									</div>
								</div>

								<!-- Order History -->
								<div class="card mb-4">
									<div class="card-header">
										<i class="fas fa-history me-1"></i> Tracking History
									</div>
									<div class="table-responsive">
										<table class="table table-striped table-sm mb-0">
											<thead>
												<tr>
													<th>Date</th>
													<th>Status</th>
													<th>Remark</th>
												</tr>
											</thead>
											<tbody>
												<?php
												$ret = mysqli_query($con, "SELECT * FROM ordertrackhistory WHERE orderId='$orderid' ORDER BY postingDate DESC");
												while ($hrow = mysqli_fetch_array($ret)) {
													?>
													<tr>
														<td><small><?php echo htmlentities($hrow['postingDate']); ?></small>
														</td>
														<td><span
																class="badge bg-secondary"><?php echo htmlentities($hrow['status']); ?></span>
														</td>
														<td><small><?php echo htmlentities($hrow['remark']); ?></small></td>
													</tr>
												<?php } ?>
												<?php if (mysqli_num_rows($ret) == 0) { ?>
													<tr>
														<td colspan="3" class="text-center text-muted">No history available</td>
													</tr>
												<?php } ?>
											</tbody>
										</table>
									</div>
								</div>
							</div>
						</div>

					<?php } else { ?>
						<div class="alert alert-danger">
							Order not found.
						</div>
					<?php } ?>
				</div>
			</main>
			<?php include_once('includes/footer.php'); ?>
		</div>
	</div>
	<script src="js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
	<script src="js/scripts.js"></script>
</body>

</html>
?>