<!DOCTYPE html>
<html lang="es">
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<?php
		$app_name = !empty($app_config['app_name']) ? $app_config['app_name'] : 'BellaIdea';
		$app_logo = !empty($app_config['logo_path']) ? $app_config['logo_path'] : '';
	?>
	<title>Pedidos | <?php echo html_escape($app_name); ?></title>
	<style>
		:root {
			--bg: #f6f7fb;
			--card: #ffffff;
			--text: #1f2937;
			--muted: #64748b;
			--line: #e2e8f0;
			--primary: #0ea5a3;
			--ok-bg: #dcfce7;
			--ok-text: #166534;
		}
		* { box-sizing: border-box; }
		body { margin: 0; font-family: "Segoe UI", Tahoma, Arial, sans-serif; background: var(--bg); color: var(--text); }
		.appbar { background: var(--card); border-bottom: 1px solid var(--line); padding: 10px 12px; position: sticky; top: 0; z-index: 20; }
		.appbar-inner { max-width: 540px; margin: 0 auto; display: flex; align-items: center; justify-content: space-between; }
		.company-wrap { display: grid; grid-template-columns: 52px minmax(0, 1fr); column-gap: 10px; row-gap: 2px; align-items: center; }
		.company-wrap.no-logo { grid-template-columns: minmax(0, 1fr); }
		.brand { display: contents; }
		.company-logo { width: 52px; height: 52px; border-radius: 8px; object-fit: cover; border: 1px solid var(--line); background: var(--card); grid-column: 1; grid-row: 1 / span 2; }
		.company-name { font-size: 18px; font-weight: 800; color: var(--text); grid-column: 2; grid-row: 1; line-height: 1.15; word-break: break-word; }
		.appbar-user { font-size: 12px; color: var(--muted); grid-column: 2; grid-row: 2; }
		.company-wrap.no-logo .company-name, .company-wrap.no-logo .appbar-user { grid-column: 1; }
		.container { max-width: 540px; margin: 0 auto; padding: 12px 12px 24px; }
		.top { display: flex; align-items: center; justify-content: space-between; margin: 6px 0 12px; }
		.top h1 { margin: 0; font-size: 22px; }
		.menu-btn { width: 42px; height: 42px; border: 1px solid var(--line); border-radius: 10px; background: var(--card); padding: 9px 8px; display: flex; flex-direction: column; justify-content: space-between; }
		.menu-btn span { display: block; height: 3px; border-radius: 5px; background: var(--text); }
		.card { background: var(--card); border-radius: 14px; padding: 12px; border: 1px solid var(--line); margin-bottom: 12px; }
		.action-btn { display: block; width: 100%; text-decoration: none; text-align: center; border: 0; border-radius: 10px; background: var(--primary); color: #fff; padding: 12px; font-size: 28px; font-weight: 700; }
		.action-secondary { margin-top: 8px; display: block; width: 100%; text-decoration: none; text-align: center; border: 1px solid var(--line); border-radius: 10px; background: var(--card); color: var(--text); padding: 10px; font-size: 15px; font-weight: 700; }
		.ok { background: var(--ok-bg); color: var(--ok-text); border-radius: 10px; padding: 10px; font-size: 13px; margin-bottom: 10px; }
		.error { background: #fee2e2; color: #991b1b; }
		h2 { margin: 0 0 10px; font-size: 16px; }
		.item-card { border: 1px solid var(--line); border-radius: 12px; margin-bottom: 8px; overflow: hidden; background: var(--card); }
		.item-card summary { list-style: none; cursor: pointer; padding: 11px 12px; display: flex; align-items: center; justify-content: space-between; gap: 8px; }
		.item-card summary::-webkit-details-marker { display: none; }
		.item-title { font-size: 15px; font-weight: 700; color: var(--text); }
		.item-mini { font-size: 12px; color: var(--muted); margin-top: 2px; }
		.item-right { font-size: 13px; font-weight: 700; }
		.item-details { border-top: 1px solid var(--line); padding: 10px 12px; }
		.meta { font-size: 13px; color: var(--muted); margin-top: 3px; }
		.invoice-head, .invoice-row { display: grid; grid-template-columns: 1fr auto auto; gap: 8px; font-size: 12px; }
		.invoice-head { margin-top: 8px; color: var(--muted); font-weight: 700; }
		.invoice-row { border-top: 1px dashed var(--line); padding-top: 6px; margin-top: 6px; }
		.cell-right { text-align: right; }
		.detail-actions { margin-top: 10px; display: flex; justify-content: flex-end; gap: 8px; }
		.btn-outline { width: auto; margin: 0; border: 1px solid var(--line); background: var(--card); color: var(--text); border-radius: 8px; padding: 7px 12px; font-size: 13px; font-weight: 700; }
		.photo-grid { margin-top: 8px; display: flex; flex-wrap: wrap; gap: 8px; }
		.photo-thumb { width: 68px; height: 68px; border: 1px solid var(--line); border-radius: 8px; background: var(--card); padding: 0; margin: 0; overflow: hidden; cursor: pointer; }
		.photo-thumb img { width: 100%; height: 100%; object-fit: cover; display: block; }
		.modal-backdrop { position: fixed; inset: 0; background: rgba(15, 23, 42, 0.45); opacity: 0; pointer-events: none; transition: opacity 0.2s ease; z-index: 39; }
		.modal { position: fixed; left: 50%; top: 50%; transform: translate(-50%, -48%); width: min(92vw, 560px); max-height: 90vh; overflow-y: auto; background: var(--card); border: 1px solid var(--line); border-radius: 14px; padding: 12px; z-index: 40; opacity: 0; pointer-events: none; transition: all 0.2s ease; }
		.modal.open { opacity: 1; pointer-events: auto; transform: translate(-50%, -50%); }
		.modal-backdrop.open { opacity: 1; pointer-events: auto; }
		.image-viewer { width: min(94vw, 760px); max-height: 92vh; padding: 10px; overflow: hidden; }
		.image-viewer-wrap { width: 100%; height: calc(92vh - 70px); display: flex; align-items: center; justify-content: center; }
		.image-viewer-wrap img { max-width: 100%; max-height: 100%; object-fit: contain; border-radius: 8px; border: 1px solid var(--line); background: var(--card); }
		.modal-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px; }
		.modal-head h3 { margin: 0; font-size: 18px; }
		label { font-size: 13px; font-weight: 600; margin: 8px 0 4px; display: block; }
		input, select { width: 100%; border: 1px solid var(--line); background: var(--card); color: var(--text); border-radius: 10px; padding: 10px; font-size: 15px; }
		button { margin-top: 12px; width: 100%; border: 0; border-radius: 10px; background: var(--primary); color: #fff; padding: 11px; font-size: 15px; font-weight: 700; }
		.inline-field { display: grid; grid-template-columns: minmax(0, 1fr) 40px; gap: 8px; align-items: end; }
		.plus-btn { width: 40px; height: 40px; margin: 0; border-radius: 10px; border: 1px solid var(--line); background: var(--card); color: var(--text); font-size: 26px; line-height: 1; font-weight: 700; padding: 0; }
		.client-quick {
			display: none;
			margin-top: 8px;
			border: 1px dashed var(--line);
			border-radius: 10px;
			padding: 8px;
		}
		.client-quick.open { display: block; }
		.client-quick-actions { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-top: 8px; }
		.client-quick-actions button { margin-top: 0; }
		.client-quick-actions .btn-cancel { background: var(--card); color: var(--text); border: 1px solid var(--line); }
		.client-quick-msg { margin-top: 6px; font-size: 12px; color: var(--muted); }
		.quick-row { display: grid; grid-template-columns: repeat(6, 1fr); gap: 6px; margin-top: 8px; }
		.quick-btn { border: 1px solid var(--line); border-radius: 8px; background: var(--card); color: var(--text); padding: 7px 4px; font-size: 11px; font-weight: 700; cursor: pointer; }
		.material-lines { margin-top: 6px; border: 1px solid var(--line); border-radius: 10px; padding: 8px; max-height: 170px; overflow-y: auto; }
		.material-line { display: grid; grid-template-columns: minmax(0, 1fr) 132px; gap: 8px; align-items: center; padding: 6px 2px; border-bottom: 1px dashed var(--line); }
		.material-line:last-child { border-bottom: 0; }
		.material-line-name { font-size: 13px; font-weight: 700; line-height: 1.2; }
		.material-line-meta { font-size: 12px; color: var(--muted); margin-top: 2px; }
		.qty-stepper { display: grid; grid-template-columns: 32px minmax(0, 1fr) 32px; align-items: center; gap: 4px; }
		.material-line-qty { width: 100%; padding: 7px 6px; font-size: 14px; text-align: center; }
		.qty-btn { width: 32px; height: 32px; margin: 0; border-radius: 8px; border: 1px solid var(--line); background: var(--card); color: var(--text); font-size: 18px; font-weight: 700; line-height: 1; padding: 0; }
		.material-line.extra { grid-template-columns: minmax(0, 1fr) 132px 28px; }
		.rm-extra { width: 28px; height: 34px; margin: 0; border: 1px solid var(--line); border-radius: 8px; background: var(--card); color: var(--text); font-size: 16px; font-weight: 700; line-height: 1; padding: 0; }
		.extra-wrap { margin-top: 8px; border: 1px solid var(--line); border-radius: 10px; padding: 8px; }
		.extra-search { width: 100%; }
		.extra-results { margin-top: 6px; max-height: 140px; overflow-y: auto; border: 1px solid var(--line); border-radius: 8px; }
		.extra-item { display: flex; justify-content: space-between; align-items: center; gap: 8px; padding: 8px; border-bottom: 1px solid var(--line); }
		.extra-item:last-child { border-bottom: 0; }
		.extra-title { font-size: 13px; font-weight: 700; }
		.extra-meta { font-size: 11px; color: var(--muted); margin-top: 1px; }
		.extra-add { width: auto; margin: 0; padding: 6px 10px; font-size: 12px; border-radius: 7px; }
		.preview { margin-top: 10px; border: 1px solid var(--line); border-radius: 10px; padding: 8px; }
		.preview-title { font-size: 13px; font-weight: 700; margin-bottom: 6px; }
		.preview-row { font-size: 12px; color: var(--muted); display: flex; justify-content: space-between; gap: 8px; margin-top: 4px; }
		.preview-total { margin-top: 8px; font-size: 15px; font-weight: 700; display: flex; justify-content: space-between; }
		.drawer-backdrop { position: fixed; inset: 0; background: rgba(15, 23, 42, 0.4); opacity: 0; pointer-events: none; transition: opacity 0.2s ease; z-index: 29; }
		.drawer { position: fixed; top: 0; right: 0; width: min(86vw, 330px); height: 100vh; height: 100dvh; min-height: 100dvh; background: var(--card); border-left: 1px solid var(--line); transform: translateX(100%); transition: transform 0.25s ease; z-index: 30; padding: 16px 14px calc(72px + env(safe-area-inset-bottom)); display: flex; flex-direction: column; overflow-y: auto; }
		.drawer.open { transform: translateX(0); }
		.drawer-backdrop.open { opacity: 1; pointer-events: auto; }
		.drawer-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px; }
		.drawer-title { margin: 0; font-size: 18px; }
		.close-btn { border: 1px solid var(--line); background: var(--card); color: var(--text); border-radius: 8px; width: 34px; height: 34px; font-size: 18px; line-height: 1; margin-top: 0; padding: 0; }
		.module-link { display: block; text-decoration: none; font-weight: 700; color: var(--text); padding: 11px 12px; border-radius: 10px; border: 1px solid var(--line); margin-bottom: 8px; }
		.module-link.active { background: var(--primary); color: #fff; border-color: var(--primary); }
		.drawer-bottom { margin-top: auto; }
		.logout-link { display: block; margin-top: 8px; text-decoration: none; text-align: center; font-weight: 700; color: var(--text); padding: 10px 12px; border: 1px solid var(--line); border-radius: 10px; }
	</style>
</head>
<?php
	$theme_current = $this->session->userdata('theme') ? $this->session->userdata('theme') : 'claro';
	$theme_custom_vars = $this->session->userdata('theme_custom_vars');
	$is_custom_theme = (strpos((string) $theme_current, 'custom_') === 0) && is_array($theme_custom_vars);
	$theme_render = $theme_current;
	if (!$is_custom_theme && strpos((string) $theme_current, 'custom_') === 0) {
		$theme_render = 'claro';
	}
	$body_class = $is_custom_theme ? 'theme-custom' : 'theme-'.html_escape($theme_render);
	$theme_presets = array(
		'claro' => array('bg'=>'#f6f7fb','card'=>'#ffffff','text'=>'#1f2937','muted'=>'#64748b','line'=>'#e2e8f0','primary'=>'#0ea5a3','ok_bg'=>'#dcfce7','ok_text'=>'#166534'),
		'oscuro' => array('bg'=>'#0f172a','card'=>'#111827','text'=>'#e5e7eb','muted'=>'#9ca3af','line'=>'#334155','primary'=>'#14b8a6','ok_bg'=>'#064e3b','ok_text'=>'#bbf7d0'),
		'rosado' => array('bg'=>'#fff1f6','card'=>'#ffffff','text'=>'#4a1028','muted'=>'#8a4661','line'=>'#f8bbd0','primary'=>'#ec4899','ok_bg'=>'#fce7f3','ok_text'=>'#9d174d'),
		'fuccia' => array('bg'=>'#fdf2ff','card'=>'#ffffff','text'=>'#4a044e','muted'=>'#7e22ce','line'=>'#f0abfc','primary'=>'#d946ef','ok_bg'=>'#fae8ff','ok_text'=>'#86198f'),
		'verde' => array('bg'=>'#f0fdf4','card'=>'#ffffff','text'=>'#14532d','muted'=>'#166534','line'=>'#86efac','primary'=>'#22c55e','ok_bg'=>'#dcfce7','ok_text'=>'#166534'),
		'rojo' => array('bg'=>'#fff1f2','card'=>'#ffffff','text'=>'#7f1d1d','muted'=>'#b91c1c','line'=>'#fca5a5','primary'=>'#ef4444','ok_bg'=>'#fee2e2','ok_text'=>'#991b1b'),
		'azul_claro' => array('bg'=>'#eff6ff','card'=>'#ffffff','text'=>'#1e3a8a','muted'=>'#1d4ed8','line'=>'#93c5fd','primary'=>'#38bdf8','ok_bg'=>'#dbeafe','ok_text'=>'#1e40af'),
		'azul_rey' => array('bg'=>'#eef2ff','card'=>'#ffffff','text'=>'#1e1b4b','muted'=>'#312e81','line'=>'#a5b4fc','primary'=>'#4f46e5','ok_bg'=>'#e0e7ff','ok_text'=>'#3730a3')
	);
	$vars = $is_custom_theme ? $theme_custom_vars : (isset($theme_presets[$theme_render]) ? $theme_presets[$theme_render] : $theme_presets['claro']);
	$inline_style = '--bg:'.$vars['bg'].';--card:'.$vars['card'].';--text:'.$vars['text'].';--muted:'.$vars['muted'].';--line:'.$vars['line'].';--primary:'.$vars['primary'].';--ok-bg:'.$vars['ok_bg'].';--ok-text:'.$vars['ok_text'].';';
?>
<body class="<?php echo $body_class; ?>" style="<?php echo html_escape($inline_style); ?>">
	<header class="appbar">
		<div class="appbar-inner">
			<div class="company-wrap <?php echo empty($app_logo) ? 'no-logo' : ''; ?>">
				<div class="brand">
					<?php if (!empty($app_logo)): ?>
						<img class="company-logo" src="<?php echo base_url($app_logo); ?>" alt="Logo">
					<?php endif; ?>
					<div class="company-name"><?php echo html_escape($app_name); ?></div>
				</div>
				<div class="appbar-user">Hola, <?php echo html_escape($this->session->userdata('username')); ?></div>
			</div>
			<button id="openMenu" class="menu-btn" type="button" aria-label="Abrir modulos">
				<span></span><span></span><span></span>
			</button>
		</div>
	</header>

	<div class="container">
		<div class="top"><h1>Pedidos</h1></div>

		<div class="card">
			<?php if ($this->session->flashdata('ok')): ?>
				<div class="ok"><?php echo $this->session->flashdata('ok'); ?></div>
			<?php endif; ?>
			<?php if ($this->session->flashdata('error')): ?>
				<div class="ok error"><?php echo $this->session->flashdata('error'); ?></div>
			<?php endif; ?>
			<a href="#" id="openOrderModal" class="action-btn">Agregar pedido</a>
			<a href="#" id="openHistoryModal" class="action-secondary">Historial</a>
		</div>

		<div class="card">
			<h2>Ultimos pedidos</h2>
			<?php if (empty($pedidos)): ?>
				<div class="meta">Aun no hay pedidos registrados.</div>
			<?php else: ?>
				<?php foreach ($pedidos as $p): ?>
					<?php
						$estado_raw = isset($p['estado']) ? (string) $p['estado'] : 'pendiente';
						$estado_label = 'Pendiente';
						if ($estado_raw === 'producto' || $estado_raw === 'agregado_producto') {
							$estado_label = 'Producto';
						} elseif ($estado_raw === 'finalizado') {
							$estado_label = 'Finalizado';
						}
						$cerrado = ($estado_label !== 'Pendiente');
					?>
					<details class="item-card">
						<summary>
							<div>
								<div class="item-title"><?php echo html_escape($p['cliente_nombre']); ?></div>
								<div class="item-mini"><?php echo html_escape($p['template_nombre']); ?> | <?php echo date('d/m/Y H:i', strtotime($p['fecha'])); ?> | Estado: <?php echo html_escape($estado_label); ?></div>
							</div>
							<div class="item-right"><?php echo number_format((float) $p['total'], 2, '.', ','); ?></div>
						</summary>
						<div class="item-details">
							<div class="meta">Cantidad material: <?php echo number_format((float) $p['cantidad_material'], 2, '.', ','); ?></div>
							<div class="meta">Horas: <?php echo number_format((float) $p['horas_trabajo'], 2, '.', ','); ?></div>
							<div class="meta">Costo materiales: <?php echo number_format((float) $p['costo_materiales'], 2, '.', ','); ?></div>
							<div class="meta">Costo mano de obra: <?php echo number_format((float) $p['costo_mano_obra'], 2, '.', ','); ?></div>
							<div class="meta">Margen <?php echo number_format((float) $p['margen_porcentaje'], 2, '.', ','); ?>%: <?php echo number_format((float) $p['margen_monto'], 2, '.', ','); ?></div>
							<div class="invoice-head">
								<div>Material</div>
								<div class="cell-right">Cant.</div>
								<div class="cell-right">Subtotal</div>
							</div>
							<?php foreach ($p['lineas'] as $ln): ?>
								<div class="invoice-row">
									<div><?php echo html_escape($ln->material_nombre); ?></div>
									<div class="cell-right"><?php echo number_format((float) $ln->cantidad, 2, '.', ','); ?> <?php echo html_escape($ln->unidad); ?></div>
									<div class="cell-right"><?php echo number_format((float) $ln->subtotal, 2, '.', ','); ?></div>
								</div>
							<?php endforeach; ?>
							<?php if (!$cerrado): ?>
								<div class="detail-actions">
									<button type="button" class="btn-outline" data-order-edit="<?php echo (int) $p['id']; ?>">Editar</button>
									<button type="button" class="btn-outline" data-order-photo="<?php echo (int) $p['id']; ?>">Foto</button>
									<button type="button" class="btn-outline" data-order-finalize="<?php echo (int) $p['id']; ?>">Finalizar</button>
								</div>
							<?php endif; ?>
							<?php if (!empty($p['fotos']) || !empty($p['foto_path'])): ?>
								<div class="meta" style="margin-top:8px;">Fotos:</div>
								<div class="photo-grid">
								<?php if (!empty($p['fotos'])): ?>
									<?php foreach ($p['fotos'] as $f): ?>
										<button type="button" class="photo-thumb" data-photo-open="<?php echo html_escape(base_url($f->foto_path)); ?>" aria-label="Ver foto">
											<img src="<?php echo base_url($f->foto_path); ?>" alt="Foto del pedido">
										</button>
									<?php endforeach; ?>
								<?php elseif (!empty($p['foto_path'])): ?>
									<button type="button" class="photo-thumb" data-photo-open="<?php echo html_escape(base_url($p['foto_path'])); ?>" aria-label="Ver foto">
										<img src="<?php echo base_url($p['foto_path']); ?>" alt="Foto del pedido">
									</button>
								<?php endif; ?>
								</div>
							<?php endif; ?>
						</div>
					</details>
				<?php endforeach; ?>
			<?php endif; ?>
		</div>
	</div>

	<div id="orderBackdrop" class="modal-backdrop"></div>
	<div id="orderModal" class="modal">
		<div class="modal-head">
			<h3 id="orderModalTitle">Agregar pedido</h3>
			<button id="closeOrderModal" class="close-btn" type="button" aria-label="Cerrar modal">x</button>
		</div>
		<?php echo form_open('pedidos/guardar', array('id' => 'orderForm')); ?>
			<input type="hidden" id="pedido_id" name="pedido_id" value="">
			<label for="cliente_id">Cliente</label>
			<div class="inline-field">
				<select id="cliente_id" name="cliente_id" required>
					<option value="">Selecciona un cliente</option>
					<?php foreach ($clientes as $c): ?>
						<option value="<?php echo (int) $c->id; ?>"><?php echo html_escape($c->nombre); ?><?php echo !empty($c->telefono) ? ' - '.html_escape($c->telefono) : ''; ?></option>
					<?php endforeach; ?>
				</select>
				<button id="openQuickClient" type="button" class="plus-btn" aria-label="Agregar cliente">+</button>
			</div>
			<div id="quickClientWrap" class="client-quick">
				<label for="quick_client_nombre">Nombre cliente</label>
				<input id="quick_client_nombre" type="text" placeholder="Ej. Maria Suarez">
				<label for="quick_client_telefono">Telefono (opcional)</label>
				<input id="quick_client_telefono" type="text" placeholder="Ej. 0424...">
				<div class="client-quick-actions">
					<button id="saveQuickClient" type="button">Guardar cliente</button>
					<button id="cancelQuickClient" type="button" class="btn-cancel">Cancelar</button>
				</div>
				<div id="quickClientMsg" class="client-quick-msg"></div>
			</div>

			<label for="template_id">Template</label>
			<select id="template_id" name="template_id" required>
				<option value="">Selecciona un template</option>
				<?php foreach ($templates as $t): ?>
					<option value="<?php echo (int) $t->id; ?>"><?php echo html_escape($t->nombre); ?> (<?php echo html_escape($t->parent_nombre); ?>)</option>
				<?php endforeach; ?>
			</select>

			<label>Cantidad por material</label>
			<div id="materialLines" class="material-lines">
				<div class="meta">Selecciona un template para cargar materiales.</div>
			</div>
			<div class="extra-wrap">
				<label for="extraMaterialSearch">Anexar material extra</label>
				<input id="extraMaterialSearch" class="extra-search" type="text" placeholder="Buscar material por nombre, unidad o proveedor">
				<div id="extraMaterialResults" class="extra-results">
					<div class="meta" style="padding:8px;">Escribe para buscar y anexar materiales.</div>
				</div>
			</div>

			<label for="horas_trabajo">Cantidad de horas</label>
			<input id="horas_trabajo" name="horas_trabajo" type="number" min="0" step="0.01" value="0.00" required>

			<label for="margen_porcentaje">Margen de ganancia (%)</label>
			<input id="margen_porcentaje" name="margen_porcentaje" type="number" min="0" step="0.01" value="30.00" required>
			<div class="quick-row">
				<button class="quick-btn" type="button" data-margin="10">10%</button>
				<button class="quick-btn" type="button" data-margin="20">20%</button>
				<button class="quick-btn" type="button" data-margin="30">30%</button>
				<button class="quick-btn" type="button" data-margin="50">50%</button>
				<button class="quick-btn" type="button" data-margin="80">80%</button>
				<button class="quick-btn" type="button" data-margin="100">100%</button>
			</div>
			<label for="total_manual">Total manual</label>
			<input id="total_manual" type="number" min="0" step="0.01" value="0.00">

			<div class="preview">
				<div class="preview-title">Calculo del pedido</div>
				<div id="templateMaterialsPreview"></div>
				<div class="preview-row"><span>Costo materiales</span><span id="vCostoMat">0.00</span></div>
				<div class="preview-row"><span>Mano de obra (<?php echo number_format((float) $parametros_trabajo['monto_mano_obra'], 2, '.', ','); ?>/h)</span><span id="vCostoHora">0.00</span></div>
				<div class="preview-row"><span>Costo base</span><span id="vCostoBase">0.00</span></div>
				<div class="preview-row"><span>Margen</span><span id="vMargen">0.00</span></div>
				<div class="preview-total"><span>Total</span><span id="vTotal">0.00</span></div>
			</div>

			<button type="submit">Guardar pedido</button>
		<?php echo form_close(); ?>
	</div>

	<div id="photoBackdrop" class="modal-backdrop"></div>
	<div id="photoModal" class="modal">
		<div class="modal-head">
			<h3>Agregar foto</h3>
			<button id="closePhotoModal" class="close-btn" type="button" aria-label="Cerrar modal">x</button>
		</div>
		<?php echo form_open_multipart('pedidos/subir-foto'); ?>
			<input type="hidden" id="photo_pedido_id" name="pedido_id" value="">
			<label for="foto_file">Fotos del pedido</label>
			<input id="foto_file" type="file" name="fotos[]" accept="image/*" multiple required>
			<button type="submit">Guardar fotos</button>
		<?php echo form_close(); ?>
	</div>

	<div id="imageViewerBackdrop" class="modal-backdrop"></div>
	<div id="imageViewerModal" class="modal image-viewer">
		<div class="modal-head">
			<h3>Foto del pedido</h3>
			<button id="closeImageViewer" class="close-btn" type="button" aria-label="Cerrar foto">x</button>
		</div>
		<div class="image-viewer-wrap">
			<img id="imageViewerImg" src="" alt="Vista de foto">
		</div>
	</div>

	<div id="finalizeBackdrop" class="modal-backdrop"></div>
	<div id="finalizeModal" class="modal">
		<div class="modal-head">
			<h3>Finalizar pedido</h3>
			<button id="closeFinalizeModal" class="close-btn" type="button" aria-label="Cerrar finalizar">x</button>
		</div>
		<?php echo form_open('pedidos/finalizar'); ?>
			<input type="hidden" id="finalize_pedido_id" name="pedido_id" value="">
			<button type="submit" name="accion" value="add_producto">Añadir a productos</button>
			<button type="submit" name="accion" value="finalizar_venta">Finalizar Venta</button>
		<?php echo form_close(); ?>
	</div>

	<div id="historyBackdrop" class="modal-backdrop"></div>
	<div id="historyModal" class="modal">
		<div class="modal-head">
			<h3>Historial de pedidos</h3>
			<button id="closeHistoryModal" class="close-btn" type="button" aria-label="Cerrar historial">x</button>
		</div>
		<?php if (empty($pedidos_cerrados)): ?>
			<div class="meta">No hay pedidos cerrados todavia.</div>
		<?php else: ?>
			<?php foreach ($pedidos_cerrados as $h): ?>
				<?php
					$estado_raw_h = isset($h['estado']) ? (string) $h['estado'] : 'pendiente';
					$estado_label_h = ($estado_raw_h === 'finalizado') ? 'Finalizado' : 'Producto';
				?>
				<details class="item-card">
					<summary>
						<div>
							<div class="item-title"><?php echo html_escape($h['cliente_nombre']); ?></div>
							<div class="item-mini"><?php echo html_escape($h['template_nombre']); ?> | <?php echo date('d/m/Y H:i', strtotime($h['fecha'])); ?> | Estado: <?php echo html_escape($estado_label_h); ?></div>
						</div>
						<div class="item-right"><?php echo number_format((float) $h['total'], 2, '.', ','); ?></div>
					</summary>
					<div class="item-details">
						<div class="meta">Cantidad material: <?php echo number_format((float) $h['cantidad_material'], 2, '.', ','); ?></div>
						<div class="meta">Horas: <?php echo number_format((float) $h['horas_trabajo'], 2, '.', ','); ?></div>
						<div class="meta">Costo materiales: <?php echo number_format((float) $h['costo_materiales'], 2, '.', ','); ?></div>
						<div class="meta">Costo mano de obra: <?php echo number_format((float) $h['costo_mano_obra'], 2, '.', ','); ?></div>
						<div class="meta">Margen <?php echo number_format((float) $h['margen_porcentaje'], 2, '.', ','); ?>%: <?php echo number_format((float) $h['margen_monto'], 2, '.', ','); ?></div>
						<?php if (!empty($h['fotos']) || !empty($h['foto_path'])): ?>
							<div class="meta" style="margin-top:8px;">Fotos:</div>
							<div class="photo-grid">
							<?php if (!empty($h['fotos'])): ?>
								<?php foreach ($h['fotos'] as $f): ?>
									<button type="button" class="photo-thumb" data-photo-open="<?php echo html_escape(base_url($f->foto_path)); ?>" aria-label="Ver foto">
										<img src="<?php echo base_url($f->foto_path); ?>" alt="Foto del historial">
									</button>
								<?php endforeach; ?>
							<?php elseif (!empty($h['foto_path'])): ?>
								<button type="button" class="photo-thumb" data-photo-open="<?php echo html_escape(base_url($h['foto_path'])); ?>" aria-label="Ver foto">
									<img src="<?php echo base_url($h['foto_path']); ?>" alt="Foto del historial">
								</button>
							<?php endif; ?>
							</div>
						<?php endif; ?>
					</div>
				</details>
			<?php endforeach; ?>
		<?php endif; ?>
	</div>

	<div id="drawerBackdrop" class="drawer-backdrop"></div>
	<aside id="drawer" class="drawer">
		<div class="drawer-head">
			<h3 class="drawer-title">Modulos</h3>
			<button id="closeMenu" class="close-btn" type="button" aria-label="Cerrar menu">x</button>
		</div>
		<a class="module-link" href="<?php echo site_url('dashboard'); ?>">Dashboard</a>
		<a class="module-link" href="<?php echo site_url('clientes'); ?>">Clientes</a>
		<a class="module-link" href="<?php echo site_url('inventario'); ?>">Inventario</a>
		<a class="module-link" href="<?php echo site_url('compras'); ?>">Compras</a>
		<a class="module-link active" href="<?php echo site_url('pedidos'); ?>">Pedidos</a>
		<a class="module-link" href="<?php echo site_url('reportes'); ?>">Reportes</a>
		<div class="drawer-bottom">
			<a class="module-link" href="<?php echo site_url('configuracion'); ?>">Configuracion</a>
			<a class="logout-link" href="<?php echo site_url('logout'); ?>">Salir</a>
		</div>
	</aside>

	<script>
		(function () {
			var openBtn = document.getElementById('openMenu');
			var closeBtn = document.getElementById('closeMenu');
			var drawer = document.getElementById('drawer');
			var backdrop = document.getElementById('drawerBackdrop');
			var openOrderModalBtn = document.getElementById('openOrderModal');
			var closeOrderModalBtn = document.getElementById('closeOrderModal');
			var orderModal = document.getElementById('orderModal');
			var orderBackdrop = document.getElementById('orderBackdrop');
			var openHistoryModalBtn = document.getElementById('openHistoryModal');
			var historyModal = document.getElementById('historyModal');
			var historyBackdrop = document.getElementById('historyBackdrop');
			var closeHistoryModalBtn = document.getElementById('closeHistoryModal');
			var orderModalTitle = document.getElementById('orderModalTitle');
			var orderForm = document.getElementById('orderForm');
			var pedidoIdInput = document.getElementById('pedido_id');
			var photoModal = document.getElementById('photoModal');
			var photoBackdrop = document.getElementById('photoBackdrop');
			var closePhotoModalBtn = document.getElementById('closePhotoModal');
			var photoPedidoIdInput = document.getElementById('photo_pedido_id');
			var imageViewerModal = document.getElementById('imageViewerModal');
			var imageViewerBackdrop = document.getElementById('imageViewerBackdrop');
			var closeImageViewerBtn = document.getElementById('closeImageViewer');
			var imageViewerImg = document.getElementById('imageViewerImg');
			var finalizeModal = document.getElementById('finalizeModal');
			var finalizeBackdrop = document.getElementById('finalizeBackdrop');
			var closeFinalizeModalBtn = document.getElementById('closeFinalizeModal');
			var finalizePedidoIdInput = document.getElementById('finalize_pedido_id');
			var templateSelect = document.getElementById('template_id');
			var clientSelect = document.getElementById('cliente_id');
			var openQuickClientBtn = document.getElementById('openQuickClient');
			var quickClientWrap = document.getElementById('quickClientWrap');
			var quickClientNombre = document.getElementById('quick_client_nombre');
			var quickClientTelefono = document.getElementById('quick_client_telefono');
			var saveQuickClientBtn = document.getElementById('saveQuickClient');
			var cancelQuickClientBtn = document.getElementById('cancelQuickClient');
			var quickClientMsg = document.getElementById('quickClientMsg');
			var materialLines = document.getElementById('materialLines');
			var extraMaterialSearch = document.getElementById('extraMaterialSearch');
			var extraMaterialResults = document.getElementById('extraMaterialResults');
			var horasInput = document.getElementById('horas_trabajo');
			var margenInput = document.getElementById('margen_porcentaje');
			var totalManualInput = document.getElementById('total_manual');
			var materialsPreview = document.getElementById('templateMaterialsPreview');
			var vCostoMat = document.getElementById('vCostoMat');
			var vCostoHora = document.getElementById('vCostoHora');
			var vCostoBase = document.getElementById('vCostoBase');
			var vMargen = document.getElementById('vMargen');
			var vTotal = document.getElementById('vTotal');
			var quickMarginBtns = document.querySelectorAll('[data-margin]');
			var manoObraHora = <?php echo json_encode((float) $parametros_trabajo['monto_mano_obra']); ?>;
			var templatesRaw = <?php echo json_encode($templates_js); ?>;
			var templates = Array.isArray(templatesRaw) ? templatesRaw : [];
			var catalogoRaw = <?php echo json_encode($materiales_catalogo_js); ?>;
			var catalogo = Array.isArray(catalogoRaw) ? catalogoRaw : [];
			var quickClientUrl = '<?php echo site_url('pedidos/crear-cliente-ajax'); ?>';
			var detailUrlBase = '<?php echo site_url('pedidos/detalle'); ?>';
			var orderCreateAction = '<?php echo site_url('pedidos/guardar'); ?>';
			var orderEditAction = '<?php echo site_url('pedidos/editar'); ?>';
			var extraSelected = {};
			var totalEditMode = false;

			function openMenu() { drawer.classList.add('open'); backdrop.classList.add('open'); }
			function closeMenu() { drawer.classList.remove('open'); backdrop.classList.remove('open'); }
			function openOrderModal() { orderModal.classList.add('open'); orderBackdrop.classList.add('open'); renderCalc(); }
			function closeOrderModal() {
				orderModal.classList.remove('open');
				orderBackdrop.classList.remove('open');
				if (quickClientWrap) { quickClientWrap.classList.remove('open'); }
			}
			function openHistoryModal() {
				historyModal.classList.add('open');
				historyBackdrop.classList.add('open');
			}
			function closeHistoryModal() {
				historyModal.classList.remove('open');
				historyBackdrop.classList.remove('open');
			}
			function openPhotoModal(pedidoId) {
				if (photoPedidoIdInput) { photoPedidoIdInput.value = String(pedidoId || ''); }
				photoModal.classList.add('open');
				photoBackdrop.classList.add('open');
			}
			function closePhotoModal() {
				photoModal.classList.remove('open');
				photoBackdrop.classList.remove('open');
			}
			function openImageViewer(src) {
				if (!src || !imageViewerModal || !imageViewerBackdrop || !imageViewerImg) { return; }
				imageViewerImg.src = src;
				imageViewerModal.classList.add('open');
				imageViewerBackdrop.classList.add('open');
			}
			function closeImageViewer() {
				if (!imageViewerModal || !imageViewerBackdrop || !imageViewerImg) { return; }
				imageViewerModal.classList.remove('open');
				imageViewerBackdrop.classList.remove('open');
				imageViewerImg.src = '';
			}
			function openFinalizeModal(pedidoId) {
				if (finalizePedidoIdInput) { finalizePedidoIdInput.value = String(pedidoId || ''); }
				finalizeModal.classList.add('open');
				finalizeBackdrop.classList.add('open');
			}
			function closeFinalizeModal() {
				finalizeModal.classList.remove('open');
				finalizeBackdrop.classList.remove('open');
			}
			function setCreateMode() {
				if (orderForm) { orderForm.action = orderCreateAction; }
				if (pedidoIdInput) { pedidoIdInput.value = ''; }
				if (orderModalTitle) { orderModalTitle.textContent = 'Agregar pedido'; }
				totalEditMode = false;
			}

			function openQuickClient() {
				if (!quickClientWrap) { return; }
				quickClientWrap.classList.add('open');
				if (quickClientMsg) { quickClientMsg.textContent = ''; }
				if (quickClientNombre) { quickClientNombre.focus(); }
			}

			function closeQuickClient() {
				if (!quickClientWrap) { return; }
				quickClientWrap.classList.remove('open');
				if (quickClientNombre) { quickClientNombre.value = ''; }
				if (quickClientTelefono) { quickClientTelefono.value = ''; }
				if (quickClientMsg) { quickClientMsg.textContent = ''; }
			}

			function toNum(v, d) {
				var n = parseFloat(v);
				return isNaN(n) ? d : n;
			}

			function getSelectedTemplate() {
				var id = parseInt(templateSelect.value || '0', 10);
				for (var i = 0; i < templates.length; i++) {
					if (parseInt(templates[i].id, 10) === id) {
						return templates[i];
					}
				}
				return null;
			}

			function money(n) {
				return toNum(n, 0).toFixed(2);
			}

			function escapeHtml(str) {
				return String(str || '')
					.replace(/&/g, '&amp;')
					.replace(/</g, '&lt;')
					.replace(/>/g, '&gt;')
					.replace(/"/g, '&quot;')
					.replace(/'/g, '&#39;');
			}

			function renderMaterialLines() {
				if (!materialLines) { return; }
				var tpl = getSelectedTemplate();
				extraSelected = {};
				if (!tpl) {
					materialLines.innerHTML = '<div class="meta">Selecciona un template para cargar materiales.</div>';
					renderExtraSearch(extraMaterialSearch ? extraMaterialSearch.value : '');
					return;
				}
				if (!tpl.materiales || !tpl.materiales.length) {
					materialLines.innerHTML = '<div class="meta">Este template no tiene materiales.</div>';
					return;
				}

				var html = '';
				for (var i = 0; i < tpl.materiales.length; i++) {
					var m = tpl.materiales[i];
					var mid = parseInt(m.id, 10);
					html += '<div class="material-line">'
						+ '<div>'
						+ '<input type="hidden" name="material_id[]" value="' + mid + '">'
						+ '<div class="material-line-name">' + escapeHtml(m.nombre) + '</div>'
						+ '<div class="material-line-meta">Costo: ' + money(m.costo) + ' / ' + escapeHtml(m.unidad || 'unidad') + '</div>'
						+ '</div>'
						+ '<div class="qty-stepper">'
						+ '<button type="button" class="qty-btn" data-qty-minus="' + mid + '">-</button>'
						+ '<input class="material-line-qty" name="cantidad[]" type="number" min="0" step="1" value="1" data-mat-id="' + mid + '" data-mat-cost="' + money(m.costo) + '">'
						+ '<button type="button" class="qty-btn" data-qty-plus="' + mid + '">+</button>'
						+ '</div>'
						+ '</div>';
				}
				materialLines.innerHTML = html;
				renderExtraSearch(extraMaterialSearch ? extraMaterialSearch.value : '');
			}

			function normalizeText(str) {
				var text = String(str || '').toLowerCase();
				try {
					if (typeof text.normalize === 'function') {
						text = text.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
					}
				} catch (err) {}
				return text.trim();
			}

			function rankExtra(mat, term) {
				var text = normalizeText((mat.nombre || '') + ' ' + (mat.unidad || '') + ' ' + (mat.proveedor || ''));
				if (!term) { return 3; }
				var tokens = normalizeText(term).split(/\s+/).filter(Boolean);
				if (!tokens.length) { return 3; }
				var words = text.split(/\s+/).filter(Boolean);

				var allPrefix = tokens.every(function (tk) {
					return words.some(function (w) { return w.indexOf(tk) === 0; });
				});
				if (allPrefix) { return 0; }

				var allContains = tokens.every(function (tk) {
					return text.indexOf(tk) > -1;
				});
				if (allContains) { return 1; }

				return 99;
			}

			function materialAlreadyInLines(materialId) {
				return !!(materialLines && materialLines.querySelector('input[name="material_id[]"][value="' + String(materialId) + '"]'));
			}

			function renderExtraSearch(term) {
				if (!extraMaterialResults) { return; }
				var t = normalizeText(term);
				var list = catalogo
					.map(function (m) { return { m: m, r: rankExtra(m, t) }; })
					.filter(function (x) { return x.r < 99; })
					.filter(function (x) { return !materialAlreadyInLines(parseInt(x.m.id, 10)); })
					.sort(function (a, b) { return a.r - b.r || String(a.m.nombre || '').localeCompare(String(b.m.nombre || '')); })
					.map(function (x) { return x.m; });

				if (!list.length) {
					extraMaterialResults.innerHTML = '<div class="meta" style="padding:8px;">No hay resultados.</div>';
					return;
				}

				extraMaterialResults.innerHTML = list.slice(0, 12).map(function (m) {
					var mid = parseInt(m.id, 10);
					return '<div class="extra-item">'
						+ '<div><div class="extra-title">' + escapeHtml(m.nombre) + '</div><div class="extra-meta">Costo: ' + money(m.costo) + ' | Stock: ' + parseInt(m.stock_actual || 0, 10) + ' ' + escapeHtml(m.unidad || '') + '</div></div>'
						+ '<button type="button" class="extra-add" data-add-extra="' + mid + '">Agregar</button>'
						+ '</div>';
				}).join('');
			}

			function addExtraMaterial(mid, name, unit, cost) {
				if (!materialLines || materialAlreadyInLines(mid)) { return; }
				var row = document.createElement('div');
				row.className = 'material-line extra';
				row.innerHTML = ''
					+ '<div>'
					+ '<input type="hidden" name="material_id[]" value="' + String(mid) + '">'
					+ '<div class="material-line-name">' + escapeHtml(name) + '</div>'
					+ '<div class="material-line-meta">Extra | Costo: ' + money(cost) + ' / ' + escapeHtml(unit || 'unidad') + '</div>'
					+ '</div>'
					+ '<div class="qty-stepper">'
					+ '<button type="button" class="qty-btn" data-qty-minus="' + String(mid) + '">-</button>'
					+ '<input class="material-line-qty" name="cantidad[]" type="number" min="0" step="1" value="1" data-mat-id="' + String(mid) + '" data-mat-cost="' + money(cost) + '">'
					+ '<button type="button" class="qty-btn" data-qty-plus="' + String(mid) + '">+</button>'
					+ '</div>'
					+ '<button type="button" class="rm-extra" data-rm-extra="' + String(mid) + '">x</button>';
				materialLines.appendChild(row);
				extraSelected[String(mid)] = true;
				renderCalc();
				renderExtraSearch(extraMaterialSearch ? extraMaterialSearch.value : '');
			}

			function renderCalc() {
				var tpl = getSelectedTemplate();
				var horas = Math.max(0, toNum(horasInput.value, 0));
				var margen = Math.max(0, toNum(margenInput.value, 0));
				var costoMat = 0;
				var html = '';

				var qtyInputs = materialLines ? materialLines.querySelectorAll('input[name="cantidad[]"]') : [];
				if (tpl && qtyInputs.length) {
					for (var i = 0; i < qtyInputs.length; i++) {
						var qtyEl = qtyInputs[i];
						var qty = Math.max(0, toNum(qtyEl.value, 0));
						var cost = Math.max(0, toNum(qtyEl.getAttribute('data-mat-cost'), 0));
						var sub = qty * cost;
						costoMat += sub;
						var rowName = qtyEl.closest('.material-line').querySelector('.material-line-name').textContent || '';
						html += '<div class="preview-row"><span>' + escapeHtml(rowName) + ' x ' + money(qty) + '</span><span>' + money(sub) + '</span></div>';
					}
				} else if (tpl) {
					html = '<div class="preview-row"><span>Este template no tiene materiales.</span><span>0.00</span></div>';
				} else {
					html = '<div class="preview-row"><span>Selecciona un template.</span><span>0.00</span></div>';
				}
				materialsPreview.innerHTML = html;

				var costoHora = horas * manoObraHora;
				var base = costoMat + costoHora;
				var margenMonto = base * (margen / 100);
				var total = base + margenMonto;
				if (totalEditMode && totalManualInput) {
					var manual = Math.max(0, toNum(totalManualInput.value, 0));
					total = manual;
					if (base > 0) {
						margen = Math.max(0, ((total / base) - 1) * 100);
					} else {
						margen = 0;
						total = 0;
					}
					margenMonto = total - base;
					margenInput.value = margen.toFixed(2);
				}

				vCostoMat.textContent = money(costoMat);
				vCostoHora.textContent = money(costoHora);
				vCostoBase.textContent = money(base);
				vMargen.textContent = money(margenMonto);
				vTotal.textContent = money(total);
				if (totalManualInput && !totalEditMode) {
					totalManualInput.value = money(total);
				}
			}

			function fillLinesFromMap(lineMap) {
				if (!materialLines) { return; }
				var qtyInputs = materialLines.querySelectorAll('input[name="cantidad[]"]');
				for (var i = 0; i < qtyInputs.length; i++) {
					var q = qtyInputs[i];
					var mid = parseInt(q.getAttribute('data-mat-id') || '0', 10);
					if (mid > 0 && lineMap[mid] !== undefined) {
						q.value = String(Math.round(parseFloat(lineMap[mid]) || 0));
						delete lineMap[mid];
					} else {
						q.value = '0';
					}
				}
				var keys = Object.keys(lineMap);
				for (var k = 0; k < keys.length; k++) {
					var leftId = parseInt(keys[k], 10);
					if (leftId <= 0) { continue; }
					var mat = null;
					for (var j = 0; j < catalogo.length; j++) {
						if (parseInt(catalogo[j].id, 10) === leftId) {
							mat = catalogo[j];
							break;
						}
					}
					if (mat) {
						addExtraMaterial(leftId, mat.nombre || '', mat.unidad || '', toNum(mat.costo, 0));
						var added = materialLines.querySelector('input[name="cantidad[]"][data-mat-id="' + leftId + '"]');
						if (added) {
							added.value = String(Math.round(parseFloat(lineMap[leftId]) || 0));
						}
					}
				}
			}

			if (openBtn) { openBtn.addEventListener('click', openMenu); }
			if (closeBtn) { closeBtn.addEventListener('click', closeMenu); }
			if (backdrop) { backdrop.addEventListener('click', closeMenu); }
			if (openOrderModalBtn) {
				openOrderModalBtn.addEventListener('click', function (e) {
					e.preventDefault();
					setCreateMode();
					if (orderForm) { orderForm.reset(); }
					renderMaterialLines();
					renderExtraSearch('');
					openOrderModal();
				});
			}
			if (openHistoryModalBtn) {
				openHistoryModalBtn.addEventListener('click', function (e) {
					e.preventDefault();
					openHistoryModal();
				});
			}
			if (openQuickClientBtn) {
				openQuickClientBtn.addEventListener('click', function (e) {
					e.preventDefault();
					openQuickClient();
				});
			}
			if (cancelQuickClientBtn) {
				cancelQuickClientBtn.addEventListener('click', function () {
					closeQuickClient();
				});
			}
			if (saveQuickClientBtn) {
				saveQuickClientBtn.addEventListener('click', function () {
					var nombre = quickClientNombre ? quickClientNombre.value.trim() : '';
					var telefono = quickClientTelefono ? quickClientTelefono.value.trim() : '';
					if (!nombre) {
						if (quickClientMsg) { quickClientMsg.textContent = 'Debes escribir el nombre del cliente.'; }
						return;
					}

					if (quickClientMsg) { quickClientMsg.textContent = 'Guardando cliente...'; }
					saveQuickClientBtn.disabled = true;

					var data = new URLSearchParams();
					data.append('nombre', nombre);
					data.append('telefono', telefono);

					fetch(quickClientUrl, {
						method: 'POST',
						credentials: 'same-origin',
						headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
						body: data.toString()
					})
					.then(function (res) { return res.json(); })
					.then(function (json) {
						if (!json || !json.ok || !json.cliente) {
							if (quickClientMsg) {
								quickClientMsg.textContent = (json && json.message) ? json.message : 'No se pudo crear el cliente.';
							}
							return;
						}

						var opt = document.createElement('option');
						opt.value = String(json.cliente.id);
						opt.textContent = String(json.cliente.label || nombre);
						clientSelect.appendChild(opt);
						clientSelect.value = String(json.cliente.id);
						if (quickClientMsg) { quickClientMsg.textContent = 'Cliente agregado correctamente.'; }
						setTimeout(closeQuickClient, 500);
					})
					.catch(function () {
						if (quickClientMsg) { quickClientMsg.textContent = 'Error de conexion al crear cliente.'; }
					})
					.finally(function () {
						saveQuickClientBtn.disabled = false;
					});
				});
			}
			if (closeOrderModalBtn) { closeOrderModalBtn.addEventListener('click', closeOrderModal); }
			if (orderBackdrop) { orderBackdrop.addEventListener('click', closeOrderModal); }
			if (closeHistoryModalBtn) { closeHistoryModalBtn.addEventListener('click', closeHistoryModal); }
			if (historyBackdrop) { historyBackdrop.addEventListener('click', closeHistoryModal); }
			if (closePhotoModalBtn) { closePhotoModalBtn.addEventListener('click', closePhotoModal); }
			if (photoBackdrop) { photoBackdrop.addEventListener('click', closePhotoModal); }
			if (closeImageViewerBtn) { closeImageViewerBtn.addEventListener('click', closeImageViewer); }
			if (imageViewerBackdrop) { imageViewerBackdrop.addEventListener('click', closeImageViewer); }
			if (closeFinalizeModalBtn) { closeFinalizeModalBtn.addEventListener('click', closeFinalizeModal); }
			if (finalizeBackdrop) { finalizeBackdrop.addEventListener('click', closeFinalizeModal); }
			document.addEventListener('click', function (e) {
				var btnEdit = e.target.closest('[data-order-edit]');
				if (btnEdit) {
					var pid = parseInt(btnEdit.getAttribute('data-order-edit') || '0', 10);
					if (pid <= 0) { return; }
					fetch(detailUrlBase + '/' + pid, { credentials: 'same-origin' })
						.then(function (res) { return res.json(); })
						.then(function (json) {
							if (!json || !json.ok || !json.pedido) { return; }
							setCreateMode();
							if (orderForm) { orderForm.action = orderEditAction; }
							if (pedidoIdInput) { pedidoIdInput.value = String(json.pedido.id || ''); }
							if (orderModalTitle) { orderModalTitle.textContent = 'Editar pedido'; }
							if (clientSelect) { clientSelect.value = String(json.pedido.cliente_id || ''); }
							if (templateSelect) { templateSelect.value = String(json.pedido.template_id || ''); }
							if (horasInput) { horasInput.value = String(json.pedido.horas_trabajo || '0'); }
							if (margenInput) { margenInput.value = String(json.pedido.margen_porcentaje || '0'); }
							totalEditMode = false;
							renderMaterialLines();
							var lineMap = {};
							var lineas = Array.isArray(json.pedido.lineas) ? json.pedido.lineas : [];
							for (var i = 0; i < lineas.length; i++) {
								lineMap[parseInt(lineas[i].material_id, 10)] = parseFloat(lineas[i].cantidad || 0);
							}
							fillLinesFromMap(lineMap);
							renderExtraSearch('');
							renderCalc();
							openOrderModal();
						});
					return;
				}
				var btnPhoto = e.target.closest('[data-order-photo]');
				if (btnPhoto) {
					var pid2 = parseInt(btnPhoto.getAttribute('data-order-photo') || '0', 10);
					if (pid2 > 0) { openPhotoModal(pid2); }
					return;
				}
				var btnPhotoOpen = e.target.closest('[data-photo-open]');
				if (btnPhotoOpen) {
					openImageViewer(btnPhotoOpen.getAttribute('data-photo-open') || '');
					return;
				}
				var btnFinalize = e.target.closest('[data-order-finalize]');
				if (btnFinalize) {
					var pid3 = parseInt(btnFinalize.getAttribute('data-order-finalize') || '0', 10);
					if (pid3 > 0) { openFinalizeModal(pid3); }
				}
			});

			[templateSelect, horasInput, margenInput].forEach(function (el) {
				if (!el) { return; }
				el.addEventListener('input', renderCalc);
				el.addEventListener('change', renderCalc);
			});
			if (margenInput) {
				margenInput.addEventListener('input', function () {
					totalEditMode = false;
				});
				margenInput.addEventListener('change', function () {
					totalEditMode = false;
				});
			}
			if (totalManualInput) {
				totalManualInput.addEventListener('input', function () {
					totalEditMode = true;
					renderCalc();
				});
				totalManualInput.addEventListener('change', function () {
					totalEditMode = true;
					renderCalc();
				});
			}
			if (templateSelect) {
				templateSelect.addEventListener('change', function () {
					renderMaterialLines();
					renderCalc();
				});
			}
			if (materialLines) {
				materialLines.addEventListener('input', function (e) {
					if (e.target && e.target.name === 'cantidad[]') {
						renderCalc();
					}
				});
				materialLines.addEventListener('click', function (e) {
					var plus = e.target.getAttribute('data-qty-plus');
					var minus = e.target.getAttribute('data-qty-minus');
					if (plus || minus) {
						var targetId = plus || minus;
						var qtyInput = materialLines.querySelector('input[name="cantidad[]"][data-mat-id="' + String(targetId) + '"]');
						if (qtyInput) {
							var step = 1;
							var min = Math.max(0, toNum(qtyInput.getAttribute('min'), 0));
							var current = Math.max(min, toNum(qtyInput.value, 0));
							var next = current + (plus ? step : -step);
							if (next < min) { next = min; }
							qtyInput.value = String(Math.round(next));
							renderCalc();
						}
						return;
					}
					var rm = e.target.getAttribute('data-rm-extra');
					if (!rm) { return; }
					var row = e.target.closest('.material-line');
					if (row) { row.remove(); }
					delete extraSelected[String(rm)];
					renderCalc();
					renderExtraSearch(extraMaterialSearch ? extraMaterialSearch.value : '');
				});
			}
			if (extraMaterialSearch) {
				extraMaterialSearch.addEventListener('input', function () {
					renderExtraSearch(extraMaterialSearch.value);
				});
			}
			if (extraMaterialResults) {
				extraMaterialResults.addEventListener('click', function (e) {
					var btn = e.target.closest('[data-add-extra]');
					if (!btn) { return; }
					var mid = parseInt(btn.getAttribute('data-add-extra') || '0', 10);
					if (mid <= 0) { return; }
					var mat = null;
					for (var i = 0; i < catalogo.length; i++) {
						if (parseInt(catalogo[i].id, 10) === mid) {
							mat = catalogo[i];
							break;
						}
					}
					if (!mat) { return; }
					var name = mat.nombre || '';
					var unit = mat.unidad || '';
					var cost = toNum(mat.costo, 0);
					addExtraMaterial(mid, name, unit, cost);
				});
			}

			if (quickMarginBtns && quickMarginBtns.length) {
				quickMarginBtns.forEach(function (btn) {
					btn.addEventListener('click', function () {
						margenInput.value = btn.getAttribute('data-margin') || '0';
						totalEditMode = false;
						renderCalc();
					});
				});
			}

			renderMaterialLines();
			renderExtraSearch('');
			renderCalc();
		})();
	</script>
</body>
</html>
