<!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>Compras | <?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);
		}
		body.theme-oscuro {
			--bg: #0f172a;
			--card: #111827;
			--text: #e5e7eb;
			--muted: #9ca3af;
			--line: #334155;
			--primary: #14b8a6;
			--ok-bg: #064e3b;
			--ok-text: #bbf7d0;
		}
		body.theme-rosado {
			--bg: #fff1f6;
			--card: #ffffff;
			--text: #4a1028;
			--muted: #8a4661;
			--line: #f8bbd0;
			--primary: #ec4899;
			--ok-bg: #fce7f3;
			--ok-text: #9d174d;
		}
		body.theme-fuccia {
			--bg: #fdf2ff;
			--card: #ffffff;
			--text: #4a044e;
			--muted: #7e22ce;
			--line: #f0abfc;
			--primary: #d946ef;
			--ok-bg: #fae8ff;
			--ok-text: #86198f;
		}
		body.theme-verde {
			--bg: #f0fdf4;
			--card: #ffffff;
			--text: #14532d;
			--muted: #166534;
			--line: #86efac;
			--primary: #22c55e;
			--ok-bg: #dcfce7;
			--ok-text: #166534;
		}
		body.theme-rojo {
			--bg: #fff1f2;
			--card: #ffffff;
			--text: #7f1d1d;
			--muted: #b91c1c;
			--line: #fca5a5;
			--primary: #ef4444;
			--ok-bg: #fee2e2;
			--ok-text: #991b1b;
		}
		body.theme-azul_claro {
			--bg: #eff6ff;
			--card: #ffffff;
			--text: #1e3a8a;
			--muted: #1d4ed8;
			--line: #93c5fd;
			--primary: #38bdf8;
			--ok-bg: #dbeafe;
			--ok-text: #1e40af;
		}
		body.theme-azul_rey {
			--bg: #eef2ff;
			--card: #ffffff;
			--text: #1e1b4b;
			--muted: #312e81;
			--line: #a5b4fc;
			--primary: #4f46e5;
			--ok-bg: #e0e7ff;
			--ok-text: #3730a3;
		}
		.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;
		}
		.title-wrap h1 {
			margin: 0;
			font-size: 22px;
		}
		.user {
			font-size: 12px;
			color: var(--muted);
			margin-top: 3px;
		}
		.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;
		}
		h2 {
			margin: 0 0 10px;
			font-size: 16px;
		}
		.action-btn {
			display: block;
			width: 100%;
			text-align: center;
			text-decoration: none;
			border: 0;
			border-radius: 10px;
			background: var(--primary);
			color: #fff;
			padding: 12px;
			font-size: 20px;
			font-weight: 700;
		}
		.ok {
			background: var(--ok-bg);
			color: var(--ok-text);
			border-radius: 10px;
			padding: 10px;
			font-size: 13px;
			margin-bottom: 10px;
		}
		.item {
			border: 1px solid var(--line);
			border-radius: 10px;
			padding: 10px;
			margin-bottom: 8px;
		}
		.purchase-card {
			border: 1px solid var(--line);
			border-radius: 12px;
			background: var(--card);
			margin-bottom: 8px;
			overflow: hidden;
		}
		.purchase-card summary {
			list-style: none;
			cursor: pointer;
			padding: 11px 12px;
			display: flex;
			align-items: center;
			justify-content: space-between;
			gap: 8px;
		}
		.purchase-card summary::-webkit-details-marker {
			display: none;
		}
		.purchase-title {
			font-size: 15px;
			font-weight: 700;
		}
		.purchase-mini {
			font-size: 12px;
			color: var(--muted);
			margin-top: 2px;
		}
		.purchase-total {
			font-size: 13px;
			font-weight: 700;
			color: var(--primary);
		}
		.purchase-detail {
			border-top: 1px solid var(--line);
			padding: 10px 12px;
		}
		.invoice-head,
		.invoice-row {
			display: grid;
			grid-template-columns: 1.4fr 0.8fr 0.9fr 0.9fr;
			gap: 8px;
			align-items: center;
			padding: 8px 6px;
		}
		.invoice-head {
			font-size: 12px;
			font-weight: 700;
			color: var(--muted);
			border-bottom: 1px solid var(--line);
			margin-top: 8px;
		}
		.invoice-row {
			font-size: 13px;
			border-bottom: 1px solid var(--line);
		}
		.invoice-row:last-child {
			border-bottom: 0;
		}
		.cell-right {
			text-align: right;
		}
		.name {
			font-size: 15px;
			font-weight: 700;
		}
		.meta {
			font-size: 13px;
			color: var(--muted);
			margin-top: 3px;
		}
		.empty {
			font-size: 14px;
			color: var(--muted);
		}
		.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;
		}
		.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;
		}
		.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%;
			width: min(94vw, 560px);
			max-height: 90vh;
			overflow-y: auto;
			background: var(--card);
			border: 1px solid var(--line);
			border-radius: 14px;
			padding: 14px;
			transform: translate(-50%, -45%);
			opacity: 0;
			pointer-events: none;
			transition: all 0.2s ease;
			z-index: 40;
		}
		.modal.open {
			transform: translate(-50%, -50%);
			opacity: 1;
			pointer-events: auto;
		}
		.modal-backdrop.open {
			opacity: 1;
			pointer-events: auto;
		}
		.modal-head {
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-bottom: 10px;
		}
		.modal-head h3 {
			margin: 0;
			font-size: 18px;
		}
		label {
			display: block;
			font-size: 13px;
			font-weight: 600;
			margin: 8px 0 4px;
		}
		input {
			width: 100%;
			border: 1px solid var(--line);
			background: var(--card);
			color: var(--text);
			border-radius: 10px;
			padding: 10px;
			font-size: 14px;
		}
		.search-results {
			border: 1px solid var(--line);
			border-radius: 10px;
			padding: 8px;
			max-height: 180px;
			overflow-y: auto;
			margin-top: 8px;
		}
		.search-item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			gap: 8px;
			padding: 8px;
			border-radius: 8px;
			border: 1px solid var(--line);
			margin-bottom: 6px;
		}
		.search-item:last-child {
			margin-bottom: 0;
		}
		.search-name {
			font-weight: 700;
			font-size: 13px;
		}
		.search-meta {
			font-size: 12px;
			color: var(--muted);
			margin-top: 2px;
		}
		.add-btn {
			border: 0;
			background: var(--primary);
			color: #fff;
			border-radius: 8px;
			padding: 8px 10px;
			font-weight: 700;
			font-size: 12px;
		}
		.buy-table {
			margin-top: 10px;
			border: 1px solid var(--line);
			border-radius: 10px;
			overflow: hidden;
		}
		.buy-row {
			display: grid;
			grid-template-columns: 1.2fr 0.8fr 0.8fr auto;
			gap: 6px;
			align-items: center;
			padding: 8px;
			border-bottom: 1px solid var(--line);
		}
		.buy-row:last-child {
			border-bottom: 0;
		}
		.buy-row input {
			padding: 8px;
			font-size: 13px;
		}
		.rm-btn {
			border: 1px solid var(--line);
			background: var(--bg);
			color: var(--text);
			border-radius: 8px;
			padding: 8px;
			font-weight: 700;
			font-size: 12px;
		}
		.total {
			margin-top: 10px;
			font-size: 14px;
			font-weight: 700;
			text-align: right;
		}
		.save-btn {
			margin-top: 10px;
			width: 100%;
			border: 0;
			border-radius: 10px;
			background: var(--primary);
			color: #fff;
			padding: 11px;
			font-size: 15px;
			font-weight: 700;
		}
		.error {
			background: #fee2e2;
			color: #991b1b;
		}
	</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">
			<div class="title-wrap">
				<h1>Compras</h1>
			</div>
		</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="openBuyModal" class="action-btn">Hacer Compra</a>
		</div>

		<div class="card">
			<h2>Ultimas compras</h2>
			<?php if (empty($compras_grupo)): ?>
				<div class="empty">Aun no hay compras registradas.</div>
			<?php else: ?>
				<?php foreach ($compras_grupo as $compra): ?>
					<details class="purchase-card">
						<summary>
							<div>
								<div class="purchase-title"><?php echo html_escape($compra['proveedor']); ?></div>
								<div class="purchase-mini">Fecha: <?php echo date('d/m/Y H:i', strtotime($compra['fecha'])); ?></div>
							</div>
							<div class="purchase-total">Monto: <?php echo number_format((float) $compra['monto_total'], 2, '.', ','); ?></div>
						</summary>
						<div class="purchase-detail">
							<div class="meta">Referencia: <?php echo html_escape($compra['compra_ref']); ?></div>
							<div class="invoice-head">
								<div>Material</div>
								<div class="cell-right">Cantidad</div>
								<div class="cell-right">Costo</div>
								<div class="cell-right">Subtotal</div>
							</div>
							<?php foreach ($compra['items'] as $it): ?>
								<div class="invoice-row">
									<div><?php echo html_escape($it->material_nombre); ?></div>
									<div class="cell-right"><?php echo (int) $it->cantidad; ?> <?php echo html_escape($it->unidad); ?></div>
									<div class="cell-right"><?php echo number_format((float) $it->costo_unitario, 2, '.', ','); ?></div>
									<div class="cell-right"><?php echo number_format(((int) $it->cantidad) * ((float) $it->costo_unitario), 2, '.', ','); ?></div>
								</div>
							<?php endforeach; ?>
						</div>
					</details>
				<?php endforeach; ?>
			<?php endif; ?>
		</div>
	</div>

	<div id="buyBackdrop" class="modal-backdrop"></div>
	<div id="buyModal" class="modal">
		<div class="modal-head">
			<h3>Hacer Compra</h3>
			<button id="closeBuyModal" class="close-btn" type="button" aria-label="Cerrar modal">x</button>
		</div>

		<?php echo form_open('compras/guardar', array('id' => 'buyForm')); ?>
			<label for="proveedor">Nombre del proveedor</label>
			<input id="proveedor" name="proveedor" type="text" required>

			<label for="materialSearch">Buscar material</label>
			<input id="materialSearch" type="text" placeholder="Escribe nombre o unidad...">

			<div id="searchResults" class="search-results"></div>

			<div id="buyLines" class="buy-table"></div>
			<div id="buyTotal" class="total">Total: 0.00</div>

			<button type="submit" class="save-btn">Guardar compra</button>
		<?php echo form_close(); ?>
	</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 active" href="<?php echo site_url('compras'); ?>">Compras</a>
		<a class="module-link" 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 buyModal = document.getElementById('buyModal');
			var buyBackdrop = document.getElementById('buyBackdrop');
			var openBuyModalBtn = document.getElementById('openBuyModal');
			var closeBuyModalBtn = document.getElementById('closeBuyModal');
			var materialSearch = document.getElementById('materialSearch');
			var searchResults = document.getElementById('searchResults');
			var buyLines = document.getElementById('buyLines');
			var buyTotal = document.getElementById('buyTotal');
			var buyForm = document.getElementById('buyForm');
			var materialesRaw = <?php echo json_encode($materiales); ?>;
			var materiales = Array.isArray(materialesRaw) ? materialesRaw : Object.keys(materialesRaw || {}).map(function (k) { return materialesRaw[k]; });
			var selected = {};

			function openMenu() {
				drawer.classList.add('open');
				backdrop.classList.add('open');
			}

			function closeMenu() {
				drawer.classList.remove('open');
				backdrop.classList.remove('open');
			}

			function openBuyModal() {
				buyModal.classList.add('open');
				buyBackdrop.classList.add('open');
				renderSearch('');
			}

			function closeBuyModal() {
				buyModal.classList.remove('open');
				buyBackdrop.classList.remove('open');
			}

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

				var tokens = normalizeText(term).split(/\s+/).filter(Boolean);
				if (!tokens.length) { return 3; }

				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; }

				var fuzzyOk = tokens.every(function (tk) {
					return words.some(function (w) {
						if (Math.abs(w.length - tk.length) > 2) { return false; }
						return levenshtein(w, tk) <= 2;
					});
				});
				if (fuzzyOk) { return 2; }

				return 99;
			}

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

			function levenshtein(a, b) {
				if (a === b) { return 0; }
				var al = a.length;
				var bl = b.length;
				if (al === 0) { return bl; }
				if (bl === 0) { return al; }

				var m = [];
				for (var i = 0; i <= bl; i++) { m[i] = [i]; }
				for (var j = 0; j <= al; j++) { m[0][j] = j; }

				for (var r = 1; r <= bl; r++) {
					for (var c = 1; c <= al; c++) {
						var cost = a.charAt(c - 1) === b.charAt(r - 1) ? 0 : 1;
						m[r][c] = Math.min(
							m[r - 1][c] + 1,
							m[r][c - 1] + 1,
							m[r - 1][c - 1] + cost
						);
					}
				}
				return m[bl][al];
			}

			function renderSearch(term) {
				var t = normalizeText(term);
				var list = [];
				try {
					list = materiales
						.map(function (m) { return { m: m, r: rankMaterial(m, t) }; })
						.filter(function (x) { return x.r < 99; })
						.sort(function (a, b) { return a.r - b.r || a.m.nombre.localeCompare(b.m.nombre); })
						.slice(0, 12)
						.map(function (x) { return x.m; });
				} catch (err) {
					list = materiales
						.filter(function (m) {
							var text = (String(m.nombre || '') + ' ' + String(m.unidad || '') + ' ' + String(m.proveedor || '')).toLowerCase();
							return t === '' || text.indexOf(t) > -1;
						})
						.slice(0, 12);
				}

				if (list.length === 0) {
					searchResults.innerHTML = '<div class="empty">No hay resultados.</div>';
					return;
				}

				searchResults.innerHTML = list.map(function (m) {
					return '<div class="search-item">'
						+ '<div><div class="search-name">' + escapeHtml(m.nombre) + '</div>'
						+ '<div class="search-meta">Stock: ' + parseInt(m.stock_actual, 10) + ' ' + escapeHtml(m.unidad) + ' | Proveedor: ' + escapeHtml(m.proveedor || 'Sin proveedor') + '</div></div>'
						+ '<button type="button" class="add-btn" data-id="' + parseInt(m.id, 10) + '">Agregar</button>'
						+ '</div>';
				}).join('');
			}

			function renderLines() {
				var ids = Object.keys(selected);
				if (ids.length === 0) {
					buyLines.innerHTML = '<div class="empty" style="padding:10px;">No hay materiales agregados.</div>';
					buyTotal.textContent = 'Total: 0.00';
					return;
				}

				var total = 0;
				buyLines.innerHTML = ids.map(function (id) {
					var item = selected[id];
					var subtotal = (parseFloat(item.cantidad) || 0) * (parseFloat(item.costo_unitario) || 0);
					var costoShow = parseFloat(item.costo_unitario);
					if (isNaN(costoShow) || costoShow < 0) {
						costoShow = 0;
					}
					total += subtotal;
					return '<div class="buy-row">'
						+ '<div>'
						+ '<div class="search-name">' + escapeHtml(item.nombre) + '</div>'
						+ '<div class="search-meta">' + escapeHtml(item.unidad) + '</div>'
						+ '<input type="hidden" name="material_id[]" value="' + parseInt(item.id, 10) + '">'
						+ '</div>'
						+ '<input name="cantidad[]" type="number" min="1" step="1" value="' + parseInt(item.cantidad, 10) + '" data-k="cantidad" data-id="' + parseInt(item.id, 10) + '">'
						+ '<input name="costo_unitario[]" type="number" min="0" step="0.01" value="' + costoShow.toFixed(2) + '" data-k="costo_unitario" data-id="' + parseInt(item.id, 10) + '">'
						+ '<button type="button" class="rm-btn" data-rm="' + parseInt(item.id, 10) + '">Quitar</button>'
						+ '</div>';
				}).join('');

				buyTotal.textContent = 'Total: ' + total.toFixed(2);
			}

			function addMaterial(id) {
				var mat = materiales.find(function (m) { return parseInt(m.id, 10) === parseInt(id, 10); });
				if (!mat) { return; }
				if (!selected[id]) {
					selected[id] = {
						id: parseInt(mat.id, 10),
						nombre: mat.nombre,
						unidad: mat.unidad,
						cantidad: 1,
						costo_unitario: parseFloat(mat.costo || 0)
					};
				} else {
					selected[id].cantidad = parseInt(selected[id].cantidad, 10) + 1;
				}
				renderLines();
			}

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

			openBtn.addEventListener('click', openMenu);
			closeBtn.addEventListener('click', closeMenu);
			backdrop.addEventListener('click', closeMenu);
			openBuyModalBtn.addEventListener('click', function (e) {
				e.preventDefault();
				openBuyModal();
			});
			closeBuyModalBtn.addEventListener('click', closeBuyModal);
			buyBackdrop.addEventListener('click', closeBuyModal);

			materialSearch.addEventListener('input', function () {
				renderSearch(materialSearch.value);
			});

			searchResults.addEventListener('click', function (e) {
				var id = e.target.getAttribute('data-id');
				if (!id) { return; }
				addMaterial(id);
			});

			buyLines.addEventListener('input', function (e) {
				var id = e.target.getAttribute('data-id');
				var key = e.target.getAttribute('data-k');
				if (!id || !key || !selected[id]) { return; }
				selected[id][key] = e.target.value;
				renderLines();
			});

			buyLines.addEventListener('click', function (e) {
				var id = e.target.getAttribute('data-rm');
				if (!id || !selected[id]) { return; }
				delete selected[id];
				renderLines();
			});

			buyForm.addEventListener('submit', function (e) {
				if (Object.keys(selected).length === 0) {
					e.preventDefault();
					alert('Debes agregar al menos un material.');
				}
			});

			renderLines();
			renderSearch('');
		})();
	</script>
</body>
</html>
