<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Handle Order Deletion
 */
if ( isset( $_GET['action'] ) && 'delete' === $_GET['action'] && isset( $_GET['order_id'] ) ) {
	if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( $_GET['_wpnonce'] ), 'delete_order_' . intval( $_GET['order_id'] ) ) ) {
		wp_die( esc_html__( 'Security check failed.', 'food-delivery-pickup-soluition' ) );
	}
	if ( ! current_user_can( 'delete_posts' ) ) {
		wp_die( esc_html__( 'You do not have permission to delete this.', 'food-delivery-pickup-soluition' ) );
	}
	$afdp_delete_id = intval( $_GET['order_id'] );
	// Adjusted to check for your specific post type
	if ( get_post_type( $afdp_delete_id ) === 'afdp_food_order' ) {
		wp_delete_post( $afdp_delete_id, true );
		echo '<div class="notice notice-success is-dismissible" style="border-left-color: var(--fd-primary);"><p>' . esc_html__( 'Order deleted successfully.', 'food-delivery-pickup-soluition' ) . '</p></div>';
	}
}

/**
 * Fetch Orders
 */
$afdp_orders = get_posts(
	array(
		'post_type'   => 'afdp_food_order',
		'numberposts' => 500,
		'post_status' => 'publish',
		'orderby'     => 'date',
		'order'       => 'DESC',
	)
);

$afdp_wp_date_format = get_option( 'date_format' );
$afdp_wp_time_format = get_option( 'time_format' );
?>

<style>
	:root { 
		--fd-primary: #e53935; 
		--fd-primary-hover: #c62828;
		--fd-border: #ccd0d4; 
		--fd-text: #1d2327;
		--fd-muted: #64748b;
	}

	.afdp-dashboard { margin-top: 10px; }
	
	/* Table Wrapper Card */
	#fd-orders-table-container { background: #fff; border: 1px solid var(--fd-border); border-radius: 12px; overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.05); }
	#fd-orders-table { border: none !important; width: 100% !important; margin: 0 !important; border-collapse: collapse; }
	#fd-orders-table thead th { background: #f8f9fa; padding: 16px; font-weight: 700; color: var(--fd-muted); border-bottom: 2px solid #f0f0f1; text-transform: uppercase; font-size: 11px; text-align: left; }
	#fd-orders-table td { padding: 14px 16px; vertical-align: middle; border-bottom: 1px solid #f0f0f1; }
	
	/* Order Badges */
	.fd-badge { display: inline-block; padding: 4px 10px; border-radius: 6px; font-size: 11px; font-weight: 700; border: 1px solid transparent; text-transform: uppercase; }
	.status-pending { background: #fffbeb; color: #92400e; border: 1px solid #fef3c7; animation: fd-pulse 2s infinite; }
	.status-completed { background: #f0fdf4; color: #166534; border: 1px solid #bbf7d0; }
	.status-cancelled { background: #fef2f2; color: #991b1b; border: 1px solid #fecaca; }

	@keyframes fd-pulse { 0% { opacity: 1; } 50% { opacity: 0.7; } 100% { opacity: 1; } }
	
	/* Button System */
	.btn-fd { 
		display: inline-flex; align-items: center; gap: 6px; padding: 6px 12px; 
		border-radius: 6px; font-size: 12px; font-weight: 600; text-decoration: none; 
		transition: 0.2s; cursor: pointer; border: 1px solid transparent;
	}
	.btn-fd svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 2.5; }

	.btn-view-fd { color: #475569; border-color: #cbd5e1; background: #fff; }
	.btn-view-fd:hover { background: #f1f5f9; color: #1e293b; }

	.btn-edit-fd { color: var(--fd-primary); border-color: var(--fd-primary); background: transparent; }
	.btn-edit-fd:hover { background: var(--fd-primary); color: #fff; }

	.btn-kitchen-fd { color: #2563eb; border-color: #bfdbfe; background: #eff6ff; }
	.btn-kitchen-fd:hover { background: #2563eb; color: #fff; border-color: #2563eb; }

	.btn-delete-fd { color: #fff; background: var(--fd-primary); border-color: var(--fd-primary); }
	.btn-delete-fd:hover { background: var(--fd-primary-hover); }

	/* DataTable Search Style */
	.dataTables_wrapper .dataTables_filter { float: left; margin-bottom: 20px; }
	.dataTables_wrapper .dataTables_filter input { border: 1px solid var(--fd-border); border-radius: 8px; padding: 10px 15px; width: 320px; background: #fff; }
</style>

<div class="wrap afdp-dashboard">
	<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px;">
		<h1 style="font-weight: 800; font-size: 24px;">Order Management</h1>
		<div style="color: var(--fd-muted); font-size: 13px; font-weight: 600;">
			Total Orders: <?php echo count( $afdp_orders ); ?>
		</div>
	</div>

	<div id="fd-orders-table-container">
		<table id="fd-orders-table">
			<thead>
				<tr>
					<th width="140">Order ID</th>
					<th>Customer Details</th>
					<th width="130">Status</th>
					<th width="420" style="text-align: right;">Actions</th>
				</tr>
			</thead>
			<tbody>
				<?php if ( ! empty( $afdp_orders ) ) : ?>
					<?php foreach ( $afdp_orders as $afdp_post ) :
						$afdp_order_id   = $afdp_post->ID;
						$afdp_display_id = get_the_title( $afdp_order_id );

						// ALIGNMENT LOGIC: Get linked user from Dashboard Meta
						$afdp_user_id  = get_post_meta( $afdp_order_id, 'afdp_customer_id', true );
						$afdp_userdata = $afdp_user_id ? get_userdata( $afdp_user_id ) : false;

						if ( $afdp_userdata ) {
							$afdp_customer = $afdp_userdata->display_name;
							$afdp_sub_text = $afdp_userdata->user_email;
						} else {
							$afdp_customer = get_post_meta( $afdp_order_id, 'afdp_customer_name', true ) ?: 'Guest Order';
							$afdp_sub_text = get_post_meta( $afdp_order_id, 'afdp_customer_phone', true ) ?: 'No contact info';
						}

						$afdp_status      = get_post_meta( $afdp_order_id, 'afdp_order_status', true ) ?: 'pending';
						$afdp_status_slug = strtolower( $afdp_status );
						
						$afdp_base_url           = admin_url( 'admin.php?page=awesome_food_delivery&tab=orders&order_id=' . $afdp_order_id );
						$afdp_view_url           = $afdp_base_url . '&action=view';
						$afdp_edit_url           = $afdp_base_url . '&action=edit';
						$afdp_print_customer_url = $afdp_base_url . '&action=print&type=customer';
						$afdp_print_kitchen_url  = $afdp_base_url . '&action=print&type=kitchen';
						$afdp_delete_url         = wp_nonce_url( $afdp_base_url . '&action=delete', 'delete_order_' . $afdp_order_id );
					?>
						<tr>
							<td>
								<div style="font-family: monospace; font-weight: 800; color: var(--fd-text); font-size: 14px;">
									#<?php echo esc_html( $afdp_order_id ); ?>
								</div>
								<div style="font-size:10px; color:var(--fd-muted);"><?php echo esc_html( $afdp_display_id ); ?></div>
							</td>
							<td>
								<div style="font-weight: 700; font-size: 15px; color: var(--fd-text);"><?php echo esc_html( $afdp_customer ); ?></div>
								<div style="color: var(--fd-muted); font-size: 11px; margin-top: 2px;">
									<?php echo esc_html( $afdp_sub_text ); ?> • <?php echo esc_html( get_the_date( $afdp_wp_date_format, $afdp_order_id ) ); ?>
								</div>
							</td>
							<td>
								<span class="fd-badge status-<?php echo esc_attr( $afdp_status_slug ); ?>">
									<?php echo esc_html( $afdp_status_slug ); ?>
								</span>
							</td>
							<td>
								<div style="display: flex; gap: 6px; justify-content: flex-end;">
									<a class="btn-fd btn-view-fd" href="<?php echo esc_url( $afdp_view_url ); ?>">
										<svg viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>
										View
									</a>
									<a class="btn-fd btn-edit-fd" href="<?php echo esc_url( $afdp_edit_url ); ?>">
										<svg viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4L18.5 2.5z"></path></svg>
										Edit
									</a>
									<a class="btn-fd btn-view-fd" href="<?php echo esc_url( $afdp_print_customer_url ); ?>" target="_blank">
										<svg viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 6 2 18 2 18 9"></polyline><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"></path><rect x="6" y="14" width="12" height="8"></rect></svg>
										Receipt
									</a>
									<a class="btn-fd btn-kitchen-fd" href="<?php echo esc_url( $afdp_print_kitchen_url ); ?>" target="_blank">
										<svg viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round"><path d="M6 2L3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4Z"></path><line x1="3" y1="6" x2="21" y2="6"></line><path d="M16 10a4 4 0 0 1-8 0"></path></svg>
										Kitchen
									</a>
									<a class="btn-fd btn-delete-fd" onclick="return confirm('Delete this order permanently?')" href="<?php echo esc_url( $afdp_delete_url ); ?>">
										<svg viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path></svg>
									</a>
								</div>
							</td>
						</tr>
					<?php endforeach; ?>
				<?php endif; ?>
			</tbody>
		</table>
	</div>
</div>

<script>
jQuery(document).ready(function($){
	if ($.fn.DataTable) {
		$('#fd-orders-table').DataTable({
			"pageLength": 15,
			"order": [[0, "desc"]], 
			"dom": '<"top"f>rt<"bottom"ip><"clear">',
			"language": {
				"search": "",
				"searchPlaceholder": "Search orders (ID, Name, Date)..."
			},
			"columnDefs": [ 
				{ "orderable": false, "targets": [3] }
			]
		});
	}
});
</script>