<?php
/**
 * Recipe builder edit view.
 *
 * @package RestaurantCosting
 * @var object|null          $recipe
 * @var array<int, object> la $lines
 * @var array<int, object> la $labor
 * @var array<string, mixed> $totals
 * @var int                  $recipe_id
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

$recipe_id    = $recipe_id ?? ( $recipe->id ?? 0 );
$portions     = $recipe->portions ?? 1;
$scale        = $recipe->scale_factor ?? 1;
$menu_price   = $recipe->menu_price ?? '';
$labor_rate   = $recipe->labor_rate ?? 25;
$method       = $recipe->method ?? '';
$name         = $recipe->name ?? '';
$is_scaled    = (float) $scale !== 1.0;
$image_url    = $recipe->image_url ?? '';
$print_image  = (int) ( $recipe->print_image ?? 0 );
$is_active   = (int) ( $recipe->is_active ?? 1 );
$menu_type_id = (int) ( $recipe->menu_type_id ?? 0 );
?>
<div class="wrap rc-recipe-builder">
	<h1><?php echo esc_html( $recipe_id ? __( 'Restaurant Costing - Edit Recipe', 'restaurant-costing' ) : __( 'Restaurant Costing - New Recipe', 'restaurant-costing' ) ); ?></h1>
	<div class="rc-version">v<?php echo esc_html( RC_VERSION ); ?></div>

	<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
		<?php wp_nonce_field( 'rc_save_recipe' ); ?>
		<input type="hidden" name="action" value="rc_save_recipe" />
		<input type="hidden" name="recipe_id" value="<?php echo (int) $recipe_id; ?>" />

		<div id="rc-recipe-save-error" class="rc-save-error"></div>

		<div class="rc-grid">
			<div>
				<div class="rc-panel">
					<table class="form-table">
						<tr>
							<th><label for="rc-recipe-name"><?php esc_html_e( 'Recipe name', 'restaurant-costing' ); ?></label></th>
							<td>
								<input type="text" class="regular-text" id="rc-recipe-name" name="name" value="<?php echo esc_attr( (string) $name ); ?>" required />
								<label class="rc-ml-12">
									<input type="checkbox" name="is_ingredient" value="1" <?php checked( $is_ingredient ); ?> />
									<?php esc_html_e( 'Add as ingredient', 'restaurant-costing' ); ?>
								</label>
							</td>
						</tr>
						<tr>
							<th><label for="rc-portions"><?php esc_html_e( 'Recipe Makes (Portions)', 'restaurant-costing' ); ?></label></th>
							<td>
								<input type="number" step="0.1" min="0.1" id="rc-portions" name="portions" value="<?php echo esc_attr( rc_fmt_num( $portions ) ); ?>" class="small-text" />
								<span class="rc-inline-block rc-border-dark rc-p-4-10 rc-ml-12 rc-v-align-middle">
									<label for="rc-scale-factor"><?php esc_html_e( 'Scale Recipe', 'restaurant-costing' ); ?></label>
									<input type="number" step="0.0001" min="0.0001" id="rc-scale-factor" name="scale_factor" value="<?php echo esc_attr( rc_fmt_num( $scale ) ); ?>" class="small-text rc-w-80" />
									<label class="rc-ml-8">
										<input type="checkbox" id="rc-print-scaled" />
										<?php esc_html_e( 'Print Scaled Recipe', 'restaurant-costing' ); ?>
									</label>
								</span>
							</td>
						</tr>
					</table>
				</div>

				<div class="rc-panel rc-mt-16">
					<table class="form-table">
						<tr>
							<th><label for="rc-menu-type"><?php esc_html_e( 'Menu Type', 'restaurant-costing' ); ?></label></th>
							<td>
								<select id="rc-menu-type" name="menu_type_id">
									<?php echo RC_Menu_Type_Repository::options_html( $menu_type_id ?: null ); ?>
								</select>
							</td>
						</tr>
					</table>
				</div>

				<p class="submit rc-mt-16">
					<button type="submit" class="button button-primary"><?php esc_html_e( 'Save recipe', 'restaurant-costing' ); ?></button>
					<?php if ( $recipe_id ) : ?>
						<a class="button" href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=rc_copy_recipe&id=' . (int) $recipe_id ), 'rc_copy_recipe_' . (int) $recipe_id ) ); ?>"><?php esc_html_e( 'Copy to New Recipe', 'restaurant-costing' ); ?></a>
						<a class="button" href="#" id="rc-print-btn-top"><?php esc_html_e( 'Print', 'restaurant-costing' ); ?></a>
					<?php endif; ?>
					<a class="button" href="<?php echo esc_url( admin_url( 'admin.php?page=restaurant-costing-recipes' ) ); ?>"><?php esc_html_e( 'Cancel', 'restaurant-costing' ); ?></a>
					<?php if ( $recipe_id ) : ?>
						<span class="rc-ml-auto"></span>
						<a class="button rc-confirm-delete-recipe" href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=rc_delete_recipe&id=' . (int) $recipe_id ), 'rc_delete_recipe_' . (int) $recipe_id ) ); ?>"><?php esc_html_e( 'Delete', 'restaurant-costing' ); ?></a>
						<a class="button<?php echo $is_active ? ' rc-btn-danger' : ''; ?> rc-confirm-toggle-recipe" href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=rc_toggle_recipe_status&id=' . (int) $recipe_id ), 'rc_toggle_recipe_' . (int) $recipe_id ) ); ?>"><?php echo $is_active ? esc_html__( 'Set Inactive', 'restaurant-costing' ) : esc_html__( 'Reactivate', 'restaurant-costing' ); ?></a>
					<?php endif; ?>
				</p>

				<div class="rc-panel rc-mt-16">
					<h2><?php esc_html_e( 'Ingredients', 'restaurant-costing' ); ?></h2>
					<table class="wp-list-table widefat striped rc-lines">
						<thead>
							<tr>
								<th class="col-drag"></th>
								<th><?php esc_html_e( 'Ingredient', 'restaurant-costing' ); ?></th>
								<th class="col-qty"><?php esc_html_e( 'Qty', 'restaurant-costing' ); ?></th>
								<th class="col-unit"><?php esc_html_e( 'Unit', 'restaurant-costing' ); ?></th>
								<th class="col-density"><?php esc_html_e( 'Density g/ml', 'restaurant-costing' ); ?></th>
								<th class="col-imperial"><?php esc_html_e( 'Imperial', 'restaurant-costing' ); ?></th>
								<th class="col-cost"><?php esc_html_e( 'Cost', 'restaurant-costing' ); ?></th>
								<th></th>
							</tr>
						</thead>
						<tbody>
							<?php
							$line_rows = ! empty( $lines ) ? $lines : array( (object) array() );
							foreach ( $line_rows as $idx => $line ) :
								?>
								<tr class="rc-line-row">
									<td class="col-drag"><span class="rc-drag-handle dashicons dashicons-menu" title="<?php esc_attr_e( 'Drag to reorder', 'restaurant-costing' ); ?>"></span></td>
									<td class="rc-ingredient-cell">
										<input type="hidden" class="rc-ingredient-id" name="lines[<?php echo (int) $idx; ?>][ingredient_id]" value="<?php echo esc_attr( (string) ( $line->ingredient_id ?? '' ) ); ?>" />
										<input type="text" class="rc-ingredient-input regular-text" name="lines[<?php echo (int) $idx; ?>][ingredient_name]" value="<?php echo esc_attr( (string) ( $line->ingredient_name ?? '' ) ); ?>" autocomplete="off" />
										<button type="button" class="button-link rc-open-ingredient-modal" title="<?php esc_attr_e( 'Add new ingredient', 'restaurant-costing' ); ?>">+</button>
									</td>
									<td><input type="number" step="0.01" min="0" name="lines[<?php echo (int) $idx; ?>][quantity]" value="<?php echo esc_attr( rc_fmt_num( $line->quantity ?? '' ) ); ?>" /></td>
									<td>
										<select class="rc-line-unit" name="lines[<?php echo (int) $idx; ?>][unit]">
											<?php foreach ( array( 'g', 'ml', 'ea' ) as $u ) : ?>
												<option value="<?php echo esc_attr( $u ); ?>" <?php selected( $line->unit ?? 'g', $u ); ?>><?php echo esc_html( $u ); ?></option>
											<?php endforeach; ?>
										</select>
									</td>
									<td><input type="number" step="0.01" min="0" name="lines[<?php echo (int) $idx; ?>][density_g_per_ml]" value="<?php echo esc_attr( rc_fmt_num( $line->density_g_per_ml ?? '' ) ); ?>" placeholder="—" /></td>
									<td class="imperial-display"><span class="rc-line-imperial">—</span></td>
									<td class="rc-line-cost rc-text-right">—</td>
									<td><button type="button" class="button rc-remove-line" aria-label="<?php esc_attr_e( 'Remove', 'restaurant-costing' ); ?>">&times;</button></td>
								</tr>
							<?php endforeach; ?>
						</tbody>
					</table>
					<p>
						<button type="button" class="button rc-add-line"><?php esc_html_e( '+ Add ingredient line', 'restaurant-costing' ); ?></button>
						<button type="button" class="button rc-open-ingredient-modal"><?php esc_html_e( '+ New ingredient', 'restaurant-costing' ); ?></button>
						<span class="description rc-ml-8"><?php esc_html_e( 'Adds to the Ingredients list and fills the active row if you opened it from a line.', 'restaurant-costing' ); ?></span>
					</p>
				</div>

				<div class="rc-panel rc-mt-16">
					<h2><?php esc_html_e( 'Method', 'restaurant-costing' ); ?></h2>
					<textarea name="method" rows="8" class="large-text"><?php echo esc_textarea( (string) $method ); ?></textarea>
				</div>

				<p class="submit">
					<button type="submit" class="button button-primary"><?php esc_html_e( 'Save recipe', 'restaurant-costing' ); ?></button>
					<?php if ( $recipe_id ) : ?>
						<a class="button" href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=rc_copy_recipe&id=' . (int) $recipe_id ), 'rc_copy_recipe_' . (int) $recipe_id ) ); ?>"><?php esc_html_e( 'Copy to New Recipe', 'restaurant-costing' ); ?></a>
						<a class="button" href="#" id="rc-print-btn"><?php esc_html_e( 'Print', 'restaurant-costing' ); ?></a>
						<script>
						document.getElementById('rc-print-btn').addEventListener('click', function(e) {
							e.preventDefault();
							var id = <?php echo (int) $recipe_id; ?>;
							var url = '<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>';
							url += '?action=rc_print_recipe&id=' + id;
							var cb = document.getElementById('rc-print-scaled');
							if (cb && !cb.checked) {
								url += '&print_scaled=0';
							}
							window.open(url, '_blank');
						});
						document.getElementById('rc-print-btn-top').addEventListener('click', function(e) {
							e.preventDefault();
							document.getElementById('rc-print-btn').click();
						});
						</script>
					<?php endif; ?>
					<a class="button" href="<?php echo esc_url( admin_url( 'admin.php?page=restaurant-costing-recipes' ) ); ?>"><?php esc_html_e( 'Cancel', 'restaurant-costing' ); ?></a>
					<?php if ( $recipe_id ) : ?>
						<span class="rc-ml-auto"></span>
						<a class="button rc-confirm-delete-recipe" href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=rc_delete_recipe&id=' . (int) $recipe_id ), 'rc_delete_recipe_' . (int) $recipe_id ) ); ?>"><?php esc_html_e( 'Delete', 'restaurant-costing' ); ?></a>
						<a class="button<?php echo $is_active ? ' rc-btn-danger' : ''; ?> rc-confirm-toggle-recipe" href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=rc_toggle_recipe_status&id=' . (int) $recipe_id ), 'rc_toggle_recipe_' . (int) $recipe_id ) ); ?>"><?php echo $is_active ? esc_html__( 'Set Inactive', 'restaurant-costing' ) : esc_html__( 'Reactivate', 'restaurant-costing' ); ?></a>
						<script>
						document.addEventListener('DOMContentLoaded', function () {
							if (typeof rcConfirm === 'undefined') return;
							document.querySelector('.rc-confirm-delete-recipe')?.addEventListener('click', function (e) {
								e.preventDefault();
								var href = this.getAttribute('href');
								rcConfirm('<?php echo esc_js( __( 'Delete this recipe?', 'restaurant-costing' ) ); ?>', function (ok) {
									if (ok) window.location.href = href;
								});
							});
							document.querySelector('.rc-confirm-toggle-recipe')?.addEventListener('click', function (e) {
								e.preventDefault();
								var href = this.getAttribute('href');
								var msg = '<?php echo $is_active ? esc_js( __( 'Set this recipe inactive? It will be hidden from the list and its name will be available for new recipes.', 'restaurant-costing' ) ) : esc_js( __( 'Reactivate this recipe? It must have a unique name.', 'restaurant-costing' ) ); ?>';
								var okLbl = '<?php echo $is_active ? esc_js( __( 'Set Inactive', 'restaurant-costing' ) ) : esc_js( __( 'Reactivate', 'restaurant-costing' ) ); ?>';
								rcConfirm(msg, function (ok) {
									if (ok) window.location.href = href;
								}, { okLabel: okLbl });
							});
						});
						</script>
					<?php endif; ?>
				</p>
			</div>

			<div>
				<div class="rc-panel rc-mb-16">
					<table class="form-table">
						<tr>
							<th><label for="rc-menu-price"><?php esc_html_e( 'Menu price', 'restaurant-costing' ); ?></label></th>
							<td><input type="number" step="0.01" min="0" id="rc-menu-price" name="menu_price" value="<?php echo esc_attr( rc_fmt_num( $menu_price ) ); ?>" class="small-text" /></td>
						</tr>
					</table>
				</div>

				<div class="rc-panel rc-summary">
					<h2><?php esc_html_e( 'Summary', 'restaurant-costing' ); ?></h2>
					<dl>
						<dt><?php esc_html_e( 'Cost per portion', 'restaurant-costing' ); ?></dt>
						<dd id="rc-cost-per-portion">$<?php echo esc_html( number_format( (float) ( $totals['cost_per_portion'] ?? 0 ), 2 ) ); ?></dd>
						<dt><?php esc_html_e( 'Food cost %', 'restaurant-costing' ); ?></dt>
						<dd id="rc-food-cost-pct"><?php echo ! empty( $totals['menu_price'] ) ? esc_html( $totals['food_cost_pct'] . '%' ) : '—'; ?></dd>
						<dt><?php esc_html_e( 'Gross profit / portion', 'restaurant-costing' ); ?></dt>
						<dd id="rc-gross-profit"><?php echo ! empty( $totals['menu_price'] ) ? esc_html( '$' . number_format( (float) $totals['gross_profit'], 2 ) ) : '—'; ?></dd>
						<dt><?php esc_html_e( 'Gross margin %', 'restaurant-costing' ); ?></dt>
						<dd id="rc-gross-margin-pct"><?php echo ! empty( $totals['menu_price'] ) ? esc_html( $totals['gross_margin_pct'] . '%' ) : '—'; ?></dd>
						<dt><?php esc_html_e( 'Prep / portion', 'restaurant-costing' ); ?></dt>
						<dd id="rc-labor-cost">$<?php echo esc_html( number_format( (float) ( $totals['labor_per_portion'] ?? 0 ), 2 ) ); ?></dd>
					</dl>
					<?php if ( ! get_option( 'rc_hide_nutrition', 0 ) ) : ?>
					<?php
					$has_missing_nutrition = false;
					if ( ! empty( $lines ) ) {
						foreach ( $lines as $line ) {
							if ( ! empty( $line->ingredient_id ) ) {
								$ing = RC_Ingredient_Repository::get( (int) $line->ingredient_id );
								if ( $ing && ( null === $ing->calories || null === $ing->protein_grams ) ) {
									$has_missing_nutrition = true;
									break;
								}
							}
						}
					}
					if ( $has_missing_nutrition ) :
						?>
						<p style="color:#b32d2e; font-weight:700;"><?php esc_html_e( 'Nutrition values may not be accurate. Some ingredients are missing nutritional information.', 'restaurant-costing' ); ?></p>
					<?php endif; ?>
					<?php
					$nutrition      = $totals['nutrition'] ?? array();
					$portion_weight = $totals['portion_weight'] ?? 0;
					include __DIR__ . '/partials/recipe-nft.php';
					?>
					<?php endif; ?>
				</div>

				<div class="rc-panel rc-mt-16">
					<h2><?php esc_html_e( 'Prep / batch', 'restaurant-costing' ); ?></h2>
					<div class="rc-mb-12">
						<label for="rc-labor-rate" class="rc-fw-600"><?php esc_html_e( 'Prep rate ($/hr)', 'restaurant-costing' ); ?></label>
						<input type="number" step="0.01" min="0" id="rc-labor-rate" name="labor_rate" value="<?php echo esc_attr( rc_fmt_num( $labor_rate ) ); ?>" class="small-text rc-ml-8" />
					</div>
					<div class="rc-labour-list">
						<?php
						$labor_rows = ! empty( $labor ) ? $labor : array();
						foreach ( $labor_rows as $idx => $lab ) :
							?>
							<div class="rc-labour-card">
								<div class="rc-labour-card-header">
									<span><?php esc_html_e( 'Prep item', 'restaurant-costing' ); ?></span>
									<button type="button" class="button rc-remove-labor">&times;</button>
								</div>
								<div class="rc-labour-card-body">
									<label><?php esc_html_e( 'Item', 'restaurant-costing' ); ?></label>
									<input type="text" name="labor[<?php echo (int) $idx; ?>][item_label]" value="<?php echo esc_attr( (string) ( $lab->item_label ?? '' ) ); ?>" />
									<label><?php esc_html_e( 'Time (mins)', 'restaurant-costing' ); ?></label>
									<input type="number" step="0.01" min="0" name="labor[<?php echo (int) $idx; ?>][minutes]" value="<?php echo esc_attr( rc_fmt_num( $lab->minutes ?? '' ) ); ?>" />
								</div>
							</div>
						<?php endforeach; ?>
					</div>
					<p><button type="button" class="button rc-add-labor"><?php esc_html_e( '+ Add prep line', 'restaurant-costing' ); ?></button></p>
				</div>

				<?php if ( ! $is_ingredient ) : ?>
				<div class="rc-panel rc-mt-16">
					<h2><?php esc_html_e( 'Photo', 'restaurant-costing' ); ?></h2>
					<input type="hidden" id="rc-image-url" name="image_url" value="<?php echo esc_attr( $image_url ); ?>" />
					<div id="rc-image-preview" class="rc-mb-8">
						<?php if ( $image_url ) : ?>
							<img src="<?php echo esc_url( $image_url ); ?>" class="rc-max-w-200 rc-max-h-200 rc-p-4 rc-bdr" />
						<?php endif; ?>
					</div>
<p class="rc-mt-0 rc-mb-8">
			<button type="button" class="button" id="rc-add-photo"><?php esc_html_e( 'Add Photo', 'restaurant-costing' ); ?></button>
			<button type="button" class="button" id="rc-remove-photo"<?php echo $image_url ? '' : ' class="rc-hidden"'; ?>><?php esc_html_e( 'Remove Photo', 'restaurant-costing' ); ?></button>
		</p>
		<p class="rc-mt-0 rc-mb-0">
						<label>
							<input type="checkbox" name="print_image" id="rc-print-image" value="1" <?php checked( $print_image, 1 ); ?> />
							<?php esc_html_e( 'Include photo on printed recipe', 'restaurant-costing' ); ?>
						</label>
					</p>
				</div>
			<?php endif; ?>
			</div>
		</div>
	</form>
</div>

<script type="text/html" id="rc-line-template">
<tr class="rc-line-row">
	<td class="col-drag"><span class="rc-drag-handle dashicons dashicons-menu"></span></td>
	<td class="rc-ingredient-cell">
		<input type="hidden" class="rc-ingredient-id" name="lines[{{INDEX}}][ingredient_id]" value="" />
		<input type="text" class="rc-ingredient-input regular-text" name="lines[{{INDEX}}][ingredient_name]" value="" autocomplete="off" />
		<button type="button" class="button-link rc-open-ingredient-modal" title="Add new ingredient">+</button>
	</td>
	<td><input type="number" step="0.01" min="0" name="lines[{{INDEX}}][quantity]" value="" /></td>
	<td>
		<select class="rc-line-unit" name="lines[{{INDEX}}][unit]">
			<option value="g">g</option>
			<option value="ml">ml</option>
			<option value="ea">ea</option>
		</select>
	</td>
	<td><input type="number" step="0.01" min="0" name="lines[{{INDEX}}][density_g_per_ml]" value="" placeholder="—" /></td>
	<td class="imperial-display"><span class="rc-line-imperial">—</span></td>
	<td class="rc-line-cost rc-text-right">—</td>
	<td><button type="button" class="button rc-remove-line">&times;</button></td>
</tr>
</script>

<script type="text/html" id="rc-labor-template">
<div class="rc-labour-card">
	<div class="rc-labour-card-header">
		<span><?php esc_html_e( 'Prep item', 'restaurant-costing' ); ?></span>
		<button type="button" class="button rc-remove-labor">&times;</button>
	</div>
	<div class="rc-labour-card-body">
		<label><?php esc_html_e( 'Item', 'restaurant-costing' ); ?></label>
		<input type="text" name="labor[{{INDEX}}][item_label]" value="" />
		<label><?php esc_html_e( 'Time (mins)', 'restaurant-costing' ); ?></label>
		<input type="number" step="0.01" min="0" name="labor[{{INDEX}}][minutes]" value="" />
	</div>
</div>
</script>

<?php require RC_PLUGIN_DIR . 'admin/views/partials/ingredient-modal.php'; ?>

<script>
document.addEventListener('DOMContentLoaded', function () {
	var frame;
	document.getElementById('rc-add-photo')?.addEventListener('click', function (e) {
		e.preventDefault();
		if (frame) {
			frame.open();
			return;
		}
		frame = wp.media({
			title: '<?php echo esc_js( __( 'Select or Upload Recipe Photo', 'restaurant-costing' ) ); ?>',
			button: { text: '<?php echo esc_js( __( 'Use as Photo', 'restaurant-costing' ) ); ?>' },
			multiple: false
		});
		frame.on('select', function () {
			var attachment = frame.state().get('selection').first().toJSON();
			document.getElementById('rc-image-url').value = attachment.url;
			document.getElementById('rc-image-preview').innerHTML = '<img src="' + attachment.url + '" class="rc-max-w-200 rc-max-h-200 rc-p-4 rc-bdr" />';
			document.getElementById('rc-remove-photo').classList.remove('rc-hidden');
		});
		frame.open();
	});
	document.getElementById('rc-remove-photo')?.addEventListener('click', function () {
		document.getElementById('rc-image-url').value = '';
		document.getElementById('rc-image-preview').innerHTML = '';
		this.classList.add('rc-hidden');
	});
});
</script>
