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

/**
 * Order Editing Page - Force Item Detection
 */
$afdp_order_id = isset( $_GET['order_id'] ) ? intval( $_GET['order_id'] ) : 0;

if ( ! $afdp_order_id ) {
	echo '<div class="notice notice-error"><p>' . esc_html__( 'Invalid Order Resource.', 'food-delivery-pickup-soluition' ) . '</p></div>';
	return;
}

// 1. GET CURRENCY
$afdp_currency_opt   = get_option( 'afdp_currency', 'USD' );
$afdp_symbols        = array(
	'USD' => '$',
	'GBP' => '£',
	'EUR' => '€',
	'INR' => '₹',
	'BDT' => '৳',
	'AUD' => 'A$',
);
$afdp_currency_label = isset( $afdp_symbols[ $afdp_currency_opt ] ) ? $afdp_symbols[ $afdp_currency_opt ] : '£';

/**
 * 2. UPDATE LOGIC
 */
if ( isset( $_POST['fd_update_order'] ) ) {
	check_admin_referer( 'fd_update_order_action', 'fd_update_order_nonce' );

	update_post_meta( $afdp_order_id, 'afdp_customer_name', sanitize_text_field( $_POST['customer_name'] ) );
	update_post_meta( $afdp_order_id, 'afdp_customer_phone', sanitize_text_field( $_POST['customer_phone'] ) );
	update_post_meta( $afdp_order_id, 'afdp_customer_address', sanitize_textarea_field( $_POST['customer_address'] ) );
	update_post_meta( $afdp_order_id, 'afdp_order_notes', sanitize_textarea_field( $_POST['notes'] ) );
	update_post_meta( $afdp_order_id, 'afdp_order_status', sanitize_text_field( $_POST['order_status'] ) );

	$afdp_updated_items = array();
	if ( isset( $_POST['items_name'] ) && is_array( $_POST['items_name'] ) ) {
		foreach ( $_POST['items_name'] as $afdp_index => $afdp_name ) {
			if ( ! empty( $afdp_name ) ) {
				$afdp_updated_items[] = array(
					'name'  => sanitize_text_field( $afdp_name ),
					'qty'   => intval( $_POST['items_qty'][ $afdp_index ] ),
					'price' => floatval( $_POST['items_price'][ $afdp_index ] ),
				);
			}
		}
	}
	update_post_meta( $afdp_order_id, 'afdp_order_items', $afdp_updated_items );
	update_post_meta( $afdp_order_id, 'afdp_total_price', floatval( $_POST['total_price'] ) );

	echo '<div class="updated notice is-dismissible" style="border-left-color: #e53935;"><p><strong>' . esc_html__( 'Order Updated Successfully.', 'food-delivery-pickup-soluition' ) . '</strong></p></div>';
}

/**
 * 3. FORCE DATA RETRIEVAL (The Fix)
 */
$afdp_cust_name    = get_post_meta( $afdp_order_id, 'afdp_customer_name', true );
$afdp_cust_phone   = get_post_meta( $afdp_order_id, 'afdp_customer_phone', true );
$afdp_cust_address = get_post_meta( $afdp_order_id, 'afdp_customer_address', true );
$afdp_notes        = get_post_meta( $afdp_order_id, 'afdp_order_notes', true );
$afdp_status       = get_post_meta( $afdp_order_id, 'afdp_order_status', true ) ?: 'pending';
$afdp_total_price  = get_post_meta( $afdp_order_id, 'afdp_total_price', true ) ?: 0;

// Try to fetch the items from any possible location
$afdp_raw_items = get_post_meta( $afdp_order_id, 'afdp_order_items', true );

// IF EMPTY, try the specific key used by your checkout session
if ( empty( $afdp_raw_items ) ) {
	$afdp_raw_items = get_post_meta( $afdp_order_id, 'afdp_cart_items', true );
}

// Ensure it is an array (Handle objects or strings)
if ( is_string( $afdp_raw_items ) ) {
	$afdp_raw_items = maybe_unserialize( $afdp_raw_items );
}
if ( is_object( $afdp_raw_items ) ) {
	$afdp_raw_items = (array) $afdp_raw_items;
}

$afdp_items_list = is_array( $afdp_raw_items ) ? $afdp_raw_items : array();
?>

<style>
	:root { --fd-primary: #e53935; --fd-border: #ccd0d4; --fd-text: #1d2327; --fd-muted: #64748b; }
	.afdp-edit-wrapper { margin-top: 10px; max-width: 1100px; font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Oxygen-Sans,Ubuntu,Cantarell,"Helvetica Neue",sans-serif; }
	.afdp-grid { display: grid; grid-template-columns: 1fr 320px; gap: 24px; }
	.afdp-card { background: #fff; border: 1px solid var(--fd-border); border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); margin-bottom: 24px; }
	.afdp-card-header { padding: 18px 24px; border-bottom: 1px solid #f0f0f1; display: flex; align-items: center; gap: 10px; }
	.afdp-card-header h2 { margin: 0; font-size: 16px; font-weight: 700; }
	.afdp-card-body { padding: 24px; }
	.form-group { margin-bottom: 20px; }
	.form-label { display: block; font-size: 11px; font-weight: 700; text-transform: uppercase; color: var(--fd-muted); margin-bottom: 8px; }
	.fd-input { width: 100%; border: 1px solid var(--fd-border); border-radius: 8px; padding: 10px; }
	.fd-edit-table { width: 100%; border-collapse: collapse; }
	.fd-edit-table th { text-align: left; font-size: 11px; color: var(--fd-muted); padding: 10px; border-bottom: 2px solid #f0f0f1; }
	.fd-edit-table td { padding: 10px; border-bottom: 1px solid #f0f0f1; }
	.btn-save-fd { background: var(--fd-primary); color: #fff; width: 100%; padding: 12px; border-radius: 8px; border: none; font-weight: 700; cursor: pointer; }
	.btn-add-row { background: #f1f5f9; border: 1px dashed #cbd5e1; color: #475569; padding: 8px; width: 100%; border-radius: 6px; margin-top: 10px; cursor: pointer; font-weight: 600; }
</style>

<div class="wrap afdp-edit-wrapper">
	<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
		<h1 style="font-weight: 800; margin: 0;">Edit Order #<?php echo esc_html( $afdp_order_id ); ?></h1>
		<a href="?page=awesome_food_delivery&tab=orders" style="text-decoration: none; color: var(--fd-muted);">← Back</a>
	</div>

	<form method="post">
		<?php wp_nonce_field( 'fd_update_order_action', 'fd_update_order_nonce' ); ?>

		<div class="afdp-grid">
			<div class="afdp-main">
				<div class="afdp-card">
					<div class="afdp-card-header"><h2>Customer Information</h2></div>
					<div class="afdp-card-body">
						<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
							<div class="form-group">
								<label class="form-label">Full Name</label>
								<input type="text" name="customer_name" value="<?php echo esc_attr( $afdp_cust_name ); ?>" class="fd-input">
							</div>
							<div class="form-group">
								<label class="form-label">Phone</label>
								<input type="text" name="customer_phone" value="<?php echo esc_attr( $afdp_cust_phone ); ?>" class="fd-input">
							</div>
						</div>
						<div class="form-group">
							<label class="form-label">Address</label>
							<textarea name="customer_address" class="fd-input" rows="2"><?php echo esc_textarea( $afdp_cust_address ); ?></textarea>
						</div>
					</div>
				</div>

				<div class="afdp-card">
					<div class="afdp-card-header"><h2>Order Line Items</h2></div>
					<div class="afdp-card-body">
						<table class="fd-edit-table" id="items-container">
							<thead>
								<tr>
									<th>Product</th>
									<th width="80">Qty</th>
									<th width="120">Price</th>
									<th width="40"></th>
								</tr>
							</thead>
							<tbody>
								<?php 
								if ( ! empty( $afdp_items_list ) ) : 
									foreach ( $afdp_items_list as $afdp_item_row ) : 
										$afdp_item_obj   = (array) $afdp_item_row;
										$afdp_row_name   = $afdp_item_obj['name'] ?? $afdp_item_obj['item_name'] ?? $afdp_item_obj['title'] ?? 'Menu Item';
										$afdp_row_qty    = $afdp_item_obj['qty'] ?? $afdp_item_obj['item_qty'] ?? $afdp_item_obj['quantity'] ?? 1;
										$afdp_row_price  = $afdp_item_obj['price'] ?? $afdp_item_obj['item_price'] ?? $afdp_item_obj['amount'] ?? 0;
								?>
									<tr>
										<td><input type="text" name="items_name[]" value="<?php echo esc_attr( $afdp_row_name ); ?>" class="fd-input"></td>
										<td><input type="number" name="items_qty[]" value="<?php echo esc_attr( $afdp_row_qty ); ?>" class="fd-input"></td>
										<td><input type="number" step="0.01" name="items_price[]" value="<?php echo esc_attr( $afdp_row_price ); ?>" class="fd-input"></td>
										<td><button type="button" onclick="this.closest('tr').remove()" style="border:none; background:none; color:red; cursor:pointer;">&times;</button></td>
									</tr>
								<?php endforeach; else : ?>
									<tr id="no-items-row"><td colspan="4" style="text-align:center; padding:20px; color:var(--fd-muted);">No items found. Add one below.</td></tr>
								<?php endif; ?>
							</tbody>
						</table>
						<button type="button" class="btn-add-row" onclick="addRow()">+ Add New Item</button>

						<div style="text-align: right; margin-top: 30px; border-top: 2px solid #f8f9fa; padding-top: 20px;">
							<span class="form-label">Total Amount (<?php echo esc_attr( $afdp_currency_label ); ?>)</span>
							<input type="number" step="0.01" name="total_price" value="<?php echo esc_attr( $afdp_total_price ); ?>" style="font-size: 32px; font-weight: 800; text-align: right; border: none; color: var(--fd-primary); width: 200px;">
						</div>
					</div>
				</div>
			</div>

			<div class="afdp-sidebar">
				<div class="afdp-card">
					<div class="afdp-card-header"><h2>Status</h2></div>
					<div class="afdp-card-body">
						<select name="order_status" class="fd-input" style="margin-bottom: 15px;">
							<option value="pending" <?php selected( $afdp_status, 'pending' ); ?>>Pending</option>
							<option value="processing" <?php selected( $afdp_status, 'processing' ); ?>>Processing</option>
							<option value="completed" <?php selected( $afdp_status, 'completed' ); ?>>Completed</option>
						</select>
						<button type="submit" name="fd_update_order" class="btn-save-fd">Save Changes</button>
					</div>
				</div>
				<div class="afdp-card">
					<div class="afdp-card-header"><h2>Instructions</h2></div>
					<div class="afdp-card-body">
						<textarea name="notes" class="fd-input" rows="5" placeholder="Kitchen notes..."><?php echo esc_textarea( $afdp_notes ); ?></textarea>
					</div>
				</div>
			</div>
		</div>
	</form>
</div>

<script>
function addRow() {
	const row = `<tr>
		<td><input type="text" name="items_name[]" class="fd-input" placeholder="Item name"></td>
		<td><input type="number" name="items_qty[]" value="1" class="fd-input"></td>
		<td><input type="number" step="0.01" name="items_price[]" value="0.00" class="fd-input"></td>
		<td><button type="button" onclick="this.closest('tr').remove()" style="border:none; background:none; color:red; cursor:pointer;">&times;</button></td>
	</tr>`;
	document.getElementById('no-items-row')?.remove();
	document.querySelector('#items-container tbody').insertAdjacentHTML('beforeend', row);
}
</script>