<!DOCTYPE html>
<html lang="es">
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title><?php echo html_escape($catalog_name); ?> | Panel</title>
	<link rel="preconnect" href="https://fonts.googleapis.com">
	<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
	<link href="https://fonts.googleapis.com/css2?family=Outfit:wght@400;600;700;800&display=swap" rel="stylesheet">
	<style>
		:root { --bg:#f1f5f9; --ink:#0f172a; --muted:#64748b; --line:#dbe4ef; --panel:#ffffff; --brand:#0f766e; --brand2:#0b4f6c; --accent:#f59e0b; }
		* { box-sizing:border-box; }
		body { margin:0; font-family:'Outfit',sans-serif; background:radial-gradient(circle at 20% 5%, #d2f4ff 0, rgba(210,244,255,0) 20%), var(--bg); color:var(--ink); }
		.layout { max-width:1320px; margin:0 auto; padding:18px 14px 28px; display:grid; grid-template-columns:260px 1fr; gap:14px; }
		.sidebar { background:linear-gradient(160deg, var(--brand2), #1e293b); border-radius:18px; padding:16px; color:#fff; position:sticky; top:14px; height:fit-content; box-shadow:0 16px 32px rgba(15,23,42,.24); }
		.logo { font-size:22px; font-weight:800; margin:0 0 4px; }
		.sub { font-size:13px; color:#dbeafe; margin:0 0 16px; }
		.nav a { display:block; color:#dbeafe; text-decoration:none; padding:10px 11px; border-radius:10px; margin-bottom:7px; font-weight:600; }
		.nav a.active, .nav a:hover { background:rgba(255,255,255,.18); color:#fff; }
		.subnav { margin:-2px 0 8px 0; padding-left:12px; }
		.subnav a { display:block; color:#c7d2fe; text-decoration:none; padding:7px 10px; border-left:2px solid rgba(255,255,255,.25); margin:0 0 6px; font-size:13px; font-weight:600; }
		.subnav a.active, .subnav a:hover { color:#fff; border-left-color:#fcd34d; background:rgba(255,255,255,.12); border-radius:8px; }
		.user { margin-top:14px; padding-top:12px; border-top:1px solid rgba(255,255,255,.22); font-size:13px; }
		.user a { color:#fde68a; text-decoration:none; font-weight:700; }
		.main { display:flex; flex-direction:column; gap:12px; }
		.hero { background:linear-gradient(120deg, #0f766e, #2563eb); border-radius:16px; padding:18px; color:#fff; }
		.hero h1 { margin:0 0 6px; font-size:30px; }
		.hero p { margin:0; color:#dbeafe; }
		.grid-3 { display:grid; grid-template-columns:repeat(3, 1fr); gap:10px; }
		.stat { background:var(--panel); border:1px solid var(--line); border-radius:14px; padding:14px; }
		.stat .k { color:var(--muted); font-size:12px; text-transform:uppercase; letter-spacing:.06em; }
		.stat .v { font-size:28px; font-weight:800; margin-top:4px; }
		.card { background:var(--panel); border:1px solid var(--line); border-radius:14px; padding:14px; }
		h2 { margin:0 0 10px; font-size:20px; }
		h3 { margin:0 0 10px; font-size:18px; }
		label { display:block; color:var(--muted); font-size:13px; margin-bottom:4px; }
		input, select, textarea { width:100%; border:1px solid #cbd5e1; border-radius:10px; padding:10px; font:inherit; }
		.row { display:grid; grid-template-columns:1fr 1fr; gap:10px; margin-bottom:10px; }
		.btn { background:var(--brand); color:#fff; border:none; border-radius:10px; padding:10px 14px; font-weight:700; cursor:pointer; }
		.btn:hover { filter:brightness(.95); }
		table { width:100%; border-collapse:collapse; }
		th, td { border-bottom:1px solid var(--line); padding:8px; text-align:left; font-size:14px; vertical-align:top; }
		th { font-size:12px; color:var(--muted); text-transform:uppercase; letter-spacing:.05em; }
		.tag { display:inline-block; padding:4px 8px; border-radius:999px; background:#dcfce7; color:#166534; font-size:12px; font-weight:700; }
		.tag.off { background:#fee2e2; color:#991b1b; }
		.muted { color:var(--muted); font-size:13px; }
		.preview-frame { width:100%; min-height:72vh; border:1px solid var(--line); border-radius:12px; background:#fff; }
		.actions-row { display:flex; justify-content:space-between; align-items:center; gap:10px; margin-bottom:10px; }
		.link-btn { background:none; border:none; color:#0b5ecf; cursor:pointer; padding:0; font:inherit; }
		.link-btn.danger { color:#b91c1c; }
		.action-menu { position:relative; display:inline-block; }
		.action-menu summary { list-style:none; cursor:pointer; }
		.action-menu summary::-webkit-details-marker { display:none; }
		.action-toggle { background:#0f766e; color:#fff; border:none; border-radius:10px; padding:6px 10px; font-weight:700; cursor:pointer; }
		.action-pop { position:absolute; right:0; top:calc(100% + 6px); min-width:170px; background:#fff; border:1px solid #dbe4ef; border-radius:10px; box-shadow:0 12px 24px rgba(15,23,42,.15); padding:6px; z-index:15; }
		.action-pop form { margin:0; }
		.action-item { width:100%; text-align:left; background:#fff; border:none; border-radius:8px; padding:8px 10px; cursor:pointer; font:inherit; }
		.action-item:hover { background:#f8fafc; }
		.action-item.danger { color:#b91c1c; }
		.inv-photo-list { display:flex; gap:6px; flex-wrap:wrap; align-items:center; }
		.inv-photo { width:44px; height:44px; border-radius:8px; object-fit:cover; border:1px solid #cbd5e1; background:#fff; }
		.inv-photo-btn { border:none; background:transparent; padding:0; cursor:pointer; }
		.inv-actions { display:flex; gap:8px; flex-wrap:wrap; align-items:center; }
		.inv-actions form { margin:0; display:flex; gap:6px; align-items:center; }
		.inv-upload { max-width:220px; }
		.inv-toggle-form { display:flex; align-items:center; gap:8px; }
		.inventory-table { width:100%; }
		.inventory-table th,
		.inventory-table td { overflow-wrap:anywhere; word-break:break-word; }
		.inv-search-row { display:flex; gap:8px; align-items:center; margin:0 0 10px; }
		.inv-search-input { flex:1; }
		.inv-search-clear { white-space:nowrap; }
		.inv-upload-modal-file { width:100%; }
		.inv-switch { position:relative; display:inline-block; width:52px; height:30px; }
		.inv-switch input { opacity:0; width:0; height:0; }
		.inv-slider { position:absolute; cursor:pointer; inset:0; background:#cbd5e1; border-radius:999px; transition:.2s; }
		.inv-slider:before { content:''; position:absolute; width:24px; height:24px; left:3px; top:3px; background:#fff; border-radius:50%; transition:.2s; box-shadow:0 1px 3px rgba(2,6,23,.35); }
		.inv-switch input:checked + .inv-slider { background:#0f766e; }
		.inv-switch input:checked + .inv-slider:before { transform:translateX(22px); }
		.inv-gallery-stage { position:relative; min-height:420px; display:flex; align-items:center; justify-content:center; background:#f8fafc; border:1px solid #e2e8f0; border-radius:10px; touch-action:pan-y pinch-zoom; user-select:none; }
		.inv-gallery-image { max-width:100%; max-height:72vh; object-fit:contain; }
		.inv-gallery-nav { position:absolute; top:50%; transform:translateY(-50%); width:40px; height:40px; border:none; border-radius:999px; background:rgba(15,23,42,.65); color:#fff; cursor:pointer; font-size:20px; display:flex; align-items:center; justify-content:center; }
		.inv-gallery-prev { left:10px; }
		.inv-gallery-next { right:10px; }
		.inv-gallery-thumbs { display:flex; gap:8px; flex-wrap:wrap; margin-top:10px; }
		.inv-gallery-thumb { width:56px; height:56px; border:2px solid transparent; border-radius:8px; overflow:hidden; padding:0; background:#fff; cursor:pointer; }
		.inv-gallery-thumb img { width:100%; height:100%; object-fit:cover; display:block; }
		.inv-gallery-thumb.active { border-color:#0f766e; }
		.inv-gallery-actions { display:flex; gap:8px; justify-content:flex-end; flex-wrap:wrap; margin-top:10px; }
		.modal-backdrop { position:fixed; inset:0; background:rgba(15,23,42,.52); display:none; align-items:center; justify-content:center; z-index:99; padding:14px; }
		.modal-backdrop.show { display:flex; }
		.modal { width:min(980px, 96vw); max-height:92vh; overflow:auto; background:#fff; border:1px solid var(--line); border-radius:14px; padding:14px; }
		.modal-head { display:flex; justify-content:space-between; align-items:center; gap:8px; margin-bottom:8px; }
		.modal-close { border:none; background:#e2e8f0; border-radius:8px; padding:6px 9px; cursor:pointer; font-weight:700; }
		.color-picker-row { display:flex; align-items:center; gap:8px; }
		input[type="color"] { width:64px; min-width:64px; height:42px; padding:0; border-radius:10px; border:1px solid #cbd5e1; background:#fff; cursor:pointer; }
		input[type="color"]::-webkit-color-swatch-wrapper { padding:4px; border-radius:8px; }
		input[type="color"]::-webkit-color-swatch { border:none; border-radius:6px; }
		input[type="color"]::-moz-color-swatch { border:none; border-radius:6px; }
		.color-value { font-family:monospace; font-size:13px; color:#334155; background:#f8fafc; border:1px solid #e2e8f0; border-radius:8px; padding:8px 10px; min-width:86px; }
		.settings-tabs { display:flex; gap:8px; flex-wrap:wrap; margin:12px 0 10px; }
		.settings-tab-btn { border:1px solid #cbd5e1; background:#fff; color:#334155; border-radius:10px; padding:8px 12px; font:inherit; font-weight:700; cursor:pointer; }
		.settings-tab-btn.active { background:#0f766e; color:#fff; border-color:#0f766e; }
		.settings-panel { display:none; border:1px solid #dbe4ef; border-radius:12px; padding:12px; background:#fff; }
		.settings-panel.active { display:block; }
		.smart-wrap { position:relative; }
		.smart-list { position:absolute; left:0; right:0; top:calc(100% + 6px); background:#fff; border:1px solid #cbd5e1; border-radius:10px; box-shadow:0 12px 24px rgba(15,23,42,.14); z-index:12; max-height:260px; overflow:auto; display:none; }
		.smart-item { width:100%; border:none; background:#fff; text-align:left; padding:10px 11px; cursor:pointer; border-bottom:1px solid #eef2f7; }
		.smart-item:last-child { border-bottom:none; }
		.smart-item:hover { background:#f8fafc; }
		.smart-item-title { display:block; font-weight:700; color:#0f172a; }
		.smart-item-sub { display:block; font-size:12px; color:#64748b; margin-top:2px; }
		a { color:#0b5ecf; text-decoration:none; }
		a:hover { text-decoration:underline; }
		@media (max-width: 1000px) { .layout { grid-template-columns:1fr; } .sidebar { position:static; } .grid-3 { grid-template-columns:1fr; } .row { grid-template-columns:1fr; } }
		@media (max-width: 1024px), (hover: none) and (pointer: coarse) {
			.orders-table { width:100%; }
			.orders-table thead { display:none; }
			.orders-table tbody { display:block; width:100%; }
			.orders-table tr {
				display:grid;
				grid-template-columns:minmax(130px,1fr) auto auto;
				grid-template-areas:
					"main total reports"
					"customer customer customer"
					"status action action";
				column-gap:10px;
				row-gap:6px;
				margin:0 0 14px;
				padding:12px;
				border:1px solid #d5deea;
				border-radius:14px;
				background:#f8fbff;
				box-shadow:0 4px 14px rgba(15,23,42,.06);
			}
			.orders-table tr:last-child { margin-bottom:0; }
			.orders-table td {
				border-bottom:none;
				padding:0;
				min-width:0;
			}
			.orders-table td::before { display:none !important; content:none !important; }
			.orders-table .orders-cell-main { grid-area:main; }
			.orders-table .orders-cell-main a { font-weight:700; font-size:20px; line-height:1; text-decoration:none; }
			.orders-table .orders-cell-main .muted { font-size:13px; line-height:1.2; }
			.orders-table .orders-cell-total { grid-area:total; font-size:24px; font-weight:800; line-height:1; white-space:nowrap; align-self:start; }
			.orders-table .orders-cell-reports { grid-area:reports; align-self:start; white-space:nowrap; }
			.orders-table .orders-cell-reports a { font-weight:700; }
			.orders-table .orders-cell-customer { grid-area:customer; line-height:1.2; font-size:15px; }
			.orders-table .orders-cell-customer .muted { font-size:13px; }
			.orders-table .orders-cell-status { grid-area:status; align-self:center; }
			.orders-table .orders-cell-action { grid-area:action; justify-self:end; align-self:center; }
			.orders-table .orders-cell-action .action-menu { width:auto; }
			.orders-table .orders-cell-action .action-toggle { width:auto; text-align:center; min-width:88px; }
			.orders-table .orders-cell-action .action-pop {
				position:static;
				margin-top:6px;
				box-shadow:none;
				border:1px solid #dbe4ef;
				background:#fff;
			}
			.inventory-table { width:100%; }
			.inventory-table thead { display:none; }
			.inventory-table tbody { display:block; width:100%; }
			.inventory-table tr[data-inv-item-id] {
				display:grid;
				grid-template-columns:minmax(140px,1fr) auto auto auto;
				grid-template-rows:auto auto;
				column-gap:10px;
				row-gap:2px;
				margin:0 0 12px;
				padding:10px 8px;
				border-bottom:2px solid #1f5f85;
				background:#fff;
			}
			.inventory-table tr[data-inv-item-id] td {
				border-bottom:none;
				padding:0;
				min-width:0;
			}
			.inventory-table tr[data-inv-item-id] td::before { display:none !important; content:none !important; }
			.inventory-table .inv-cell-name { grid-column:1; grid-row:1; font-size:17px; font-weight:700; line-height:1.22; }
			.inventory-table .inv-cell-model { grid-column:1; grid-row:2; font-size:34px; color:#0f172a; line-height:1.1; }
			.inventory-table .inv-cell-ecommerce { grid-column:2; grid-row:1 / span 2; align-self:center; }
			.inventory-table .inv-cell-photos { grid-column:3; grid-row:1 / span 2; align-self:center; }
			.inventory-table .inv-cell-actions { grid-column:4; grid-row:1 / span 2; align-self:center; }
			.inventory-table .inv-toggle-form { gap:6px; }
			.inventory-table .inv-photo-list { gap:2px; flex-direction:column; align-items:center; text-align:center; }
			.inventory-table .inv-photo-list .inv-photo-btn:nth-child(n+2) { display:none; }
			.inventory-table .inv-photo-list .muted { font-size:12px; }
			.inventory-table .inv-actions .btn { padding:8px 10px; line-height:1.1; white-space:normal; }
		}
		@media (max-width: 620px) {
			.orders-table tr {
				grid-template-columns:minmax(120px,1fr) auto;
				grid-template-areas:
					"main total"
					"reports reports"
					"customer customer"
					"status action";
			}
			.orders-table .orders-cell-total { font-size:24px; }
			.inventory-table tr[data-inv-item-id] { grid-template-columns:minmax(120px,1fr) auto auto; }
			.inventory-table .inv-cell-actions { grid-column:2 / span 2; grid-row:3; margin-top:4px; justify-self:end; }
			.inventory-table .inv-cell-model { font-size:28px; }
		}
	</style>
</head>
<body>
	<div class="layout">
		<aside class="sidebar">
			<h2 class="logo">Catalogo</h2>
			<p class="sub"><?php echo html_escape($catalog_name); ?></p>
			<nav class="nav">
				<?php if (!empty($permissions['can_view_dashboard'])): ?>
					<a href="<?php echo site_url('catalog/admin/dashboard'); ?>" class="<?php echo $active_tab === 'dashboard' ? 'active' : ''; ?>">Dashboard</a>
				<?php endif; ?>
				<?php if (!empty($permissions['can_manage_links'])): ?>
					<a href="<?php echo site_url('catalog/admin/links'); ?>" class="<?php echo $active_tab === 'links' ? 'active' : ''; ?>">Links</a>
				<?php endif; ?>
				<?php if (!empty($permissions['can_view_orders'])): ?>
					<a href="<?php echo site_url('catalog/admin/orders'); ?>" class="<?php echo $active_tab === 'orders' ? 'active' : ''; ?>">Pedidos</a>
				<?php endif; ?>
				<?php if (!empty($permissions['can_manage_inventory'])): ?>
					<a href="<?php echo site_url('catalog/admin/inventory'); ?>" class="<?php echo $active_tab === 'inventory' ? 'active' : ''; ?>">Inventario</a>
				<?php endif; ?>
				<?php if (!empty($permissions['can_manage_permissions'])): ?>
					<a href="<?php echo site_url('catalog/admin/employees'); ?>" class="<?php echo $active_tab === 'employees' ? 'active' : ''; ?>">Empleados</a>
				<?php endif; ?>
				<?php if (!empty($permissions['can_manage_catalog'])): ?>
					<a href="<?php echo site_url('catalog/admin/catalog'); ?>" class="<?php echo in_array($active_tab, array('settings', 'templates', 'preview'), TRUE) ? 'active' : ''; ?>">Catalogo</a>
					<div class="subnav">
						<a href="<?php echo site_url('catalog/admin/settings'); ?>" class="<?php echo $active_tab === 'settings' ? 'active' : ''; ?>">Configuracion</a>
						<a href="<?php echo site_url('catalog/admin/preview'); ?>" class="<?php echo $active_tab === 'preview' ? 'active' : ''; ?>">Ver Catalogo</a>
						<a href="<?php echo site_url('catalog/admin/templates'); ?>" class="<?php echo $active_tab === 'templates' ? 'active' : ''; ?>">Plantillas</a>
					</div>
				<?php endif; ?>
			</nav>
			<div class="user">
				Sesion: <strong><?php echo html_escape($current_user['name'] !== '' ? $current_user['name'] : $current_user['username']); ?></strong><br>
				<a href="<?php echo site_url('catalog/logout'); ?>">Cerrar sesion</a>
			</div>
		</aside>

		<main class="main">
			<?php if (!empty($this->session->flashdata('catalog_notice'))): ?>
				<section class="card" style="border-color:#fbbf24;background:#fffbeb;">
					<strong><?php echo html_escape($this->session->flashdata('catalog_notice')); ?></strong>
				</section>
			<?php endif; ?>

			<?php if ($active_tab === 'dashboard'): ?>
				<section class="hero">
					<h1>Dashboard</h1>
					<p>Resumen general de links, pedidos y ventas del catalogo.</p>
				</section>
				<section class="grid-3">
					<div class="stat">
						<div class="k">Links Activos</div>
						<div class="v"><?php echo (int) $stats['links_active']; ?></div>
					</div>
					<div class="stat">
						<div class="k">Pedidos</div>
						<div class="v"><?php echo (int) $stats['orders_total']; ?></div>
					</div>
					<div class="stat">
						<div class="k">Total Vendido</div>
						<div class="v"><?php echo html_escape($currency_symbol . number_format((float)$stats['sales_amount'], 2)); ?></div>
					</div>
				</section>
				<section class="card">
					<h2>Accesos Rapidos</h2>
					<p class="muted">
						<?php if (!empty($permissions['can_manage_links'])): ?><a href="<?php echo site_url('catalog/admin/links'); ?>">Crear link de catalogo</a><?php endif; ?>
						<?php if (!empty($permissions['can_manage_links']) && (!empty($permissions['can_view_orders']) || !empty($permissions['can_manage_permissions']) || !empty($permissions['can_manage_catalog']))): ?> | <?php endif; ?>
						<?php if (!empty($permissions['can_view_orders'])): ?><a href="<?php echo site_url('catalog/admin/orders'); ?>">Ver pedidos y reportes</a><?php endif; ?>
						<?php if (!empty($permissions['can_view_orders']) && (!empty($permissions['can_manage_permissions']) || !empty($permissions['can_manage_catalog']))): ?> | <?php endif; ?>
						<?php if (!empty($permissions['can_manage_permissions'])): ?><a href="<?php echo site_url('catalog/admin/employees'); ?>">Administrar permisos</a><?php endif; ?>
						<?php if (!empty($permissions['can_manage_permissions']) && !empty($permissions['can_manage_catalog'])): ?> | <?php endif; ?>
						<?php if (!empty($permissions['can_manage_catalog'])): ?><a href="<?php echo site_url('catalog/admin/templates'); ?>">Gestionar plantillas</a><?php endif; ?>
					</p>
				</section>
			<?php endif; ?>

			<?php if ($active_tab === 'links'): ?>
				<section class="card">
					<div class="actions-row" style="margin-bottom:0;">
						<div>
							<h2 style="margin:0;">Links</h2>
							<p class="muted" style="margin:6px 0 0;">Crea links de catalogo desde el boton Nuevo Link.</p>
						</div>
						<div style="display:flex;gap:8px;">
							<button type="button" class="btn btn-outline" id="openLinksHistoryModal">Historial</button>
							<button type="button" class="btn" id="openCreateLinkModal" onclick="var m=document.getElementById('linkModalBackdrop'); if(m){m.classList.add('show'); m.setAttribute('aria-hidden','false');}">Nuevo Link</button>
						</div>
					</div>
				</section>
				<div class="modal-backdrop" id="linkModalBackdrop" aria-hidden="true" onclick="if(event.target===this){this.classList.remove('show'); this.setAttribute('aria-hidden','true');}">
					<div class="modal" role="dialog" aria-modal="true" aria-labelledby="linkModalTitle">
						<div class="modal-head">
							<h3 id="linkModalTitle">Nuevo Link</h3>
							<button type="button" class="modal-close" id="closeLinkModal" onclick="var m=document.getElementById('linkModalBackdrop'); if(m){m.classList.remove('show'); m.setAttribute('aria-hidden','true');}">X</button>
						</div>
						<form method="post" action="<?php echo site_url('catalog/admin/create'); ?>">
							<div style="margin-bottom:10px;">
								<label>Cliente</label>
								<input type="hidden" name="customer_id" id="link_customer_id" value="">
								<input type="text" id="link_customer_search" list="link_customer_datalist" autocomplete="off" placeholder="Buscar por empresa, nombre o correo...">
								<datalist id="link_customer_datalist">
									<?php foreach ($customers as $c): ?>
										<?php
											$customer_label = trim($c['company_name']) !== '' ? $c['company_name'] : trim($c['first_name'].' '.$c['last_name']);
											$customer_hint = '';
											if (!empty($c['email']))
											{
												$customer_hint = ' | ' . (string) $c['email'];
											}
											$option_label = trim($customer_label . $customer_hint);
										?>
										<option value="<?php echo html_escape($option_label); ?>"></option>
									<?php endforeach; ?>
								</datalist>
								<p class="muted" style="margin:6px 0 0;">Si no seleccionas cliente, el link queda solo ver catalogo.</p>
							</div>
							<div class="row">
								<div>
									<label>Vencimiento</label>
									<select name="expires_days" id="expires_days_select">
										<option value="1" selected>1 Dia</option>
										<option value="2">2 Dias</option>
										<option value="3">3 Dias</option>
										<option value="4">4 Dias</option>
										<option value="5">5 Dias</option>
										<option value="6">6 Dias</option>
										<option value="custom">Personalizado</option>
									</select>
								</div>
								<div id="custom_expiry_wrap" style="display:none;">
									<label>Fecha personalizada</label>
									<input type="datetime-local" name="expires_at" id="expires_at_input" value="<?php echo html_escape($default_expire); ?>" disabled>
								</div>
							</div>
							<div class="row">
								<div>
									<label>Empleado para la Venta Suspendida</label>
									<select name="employee_id" id="link_employee_select" required>
										<?php foreach ($employees as $e): ?>
											<?php $employee_name = trim($e['first_name'].' '.$e['last_name']); ?>
											<option value="<?php echo (int) $e['person_id']; ?>" <?php echo ((int)$e['person_id'] === (int)$default_employee_id) ? 'selected' : ''; ?>>
												<?php echo html_escape($employee_name !== '' ? $employee_name : $e['username']); ?>
											</option>
										<?php endforeach; ?>
									</select>
								</div>
								<div>
									<label>Sucursal para precios y venta</label>
									<select name="location_id" id="link_location_select" required>
										<?php
											$allowed_default_locations = isset($employee_location_map[(int)$default_employee_id]) ? $employee_location_map[(int)$default_employee_id] : array();
											foreach ($locations as $loc):
												$loc_id = (int) $loc['location_id'];
												if (!empty($allowed_default_locations) && !in_array($loc_id, $allowed_default_locations, TRUE))
												{
													continue;
												}
										?>
											<option value="<?php echo $loc_id; ?>" <?php echo ($loc_id === (int)$default_location_id) ? 'selected' : ''; ?>>
												#<?php echo $loc_id; ?> - <?php echo html_escape(trim($loc['name'])); ?>
											</option>
										<?php endforeach; ?>
									</select>
								</div>
							</div>
							<div style="display:flex;gap:8px;justify-content:flex-end;margin-top:10px;">
								<button type="button" class="modal-close" id="cancelLinkModal" onclick="var m=document.getElementById('linkModalBackdrop'); if(m){m.classList.remove('show'); m.setAttribute('aria-hidden','true');}">Cancelar</button>
								<button class="btn" type="submit">Generar Link</button>
							</div>
						</form>
					</div>
				</div>
				<div class="modal-backdrop" id="linksHistoryBackdrop" aria-hidden="true">
					<div class="modal" role="dialog" aria-modal="true" aria-labelledby="linksHistoryTitle">
						<div class="modal-head">
							<h3 id="linksHistoryTitle">Historial de Links</h3>
							<button type="button" class="modal-close" id="closeLinksHistoryModal">X</button>
						</div>
						<p class="muted" style="margin-top:0;">Diferencia: <strong>Eliminado</strong> = se desactivo manualmente con boton Eliminar. <strong>Expirado</strong> = vencio por fecha/hora.</p>
						<table>
							<thead>
								<tr>
									<th>ID</th>
									<th>Cliente</th>
									<th>Vence</th>
									<th>Estado</th>
									<th>Motivo</th>
								</tr>
							</thead>
							<tbody>
								<?php if (empty($links_history)): ?>
									<tr><td colspan="5">Sin historial de links.</td></tr>
								<?php else: ?>
									<?php foreach ($links_history as $hl): ?>
										<?php
											$hist_expired = strtotime($hl['expires_at']) < time();
											$hist_deleted = (int)$hl['status'] !== 1;
											$hist_status = $hist_deleted ? 'Desactivado' : 'Expirado';
											$hist_status_off = TRUE;
											$motivo = $hist_deleted && $hist_expired ? 'Eliminado y luego expirado' : ($hist_deleted ? 'Eliminado manualmente' : 'Expirado por tiempo');
										?>
										<tr>
											<td>#<?php echo (int) $hl['id']; ?></td>
											<td><?php echo html_escape($hl['customer_name']); ?></td>
											<td><?php echo html_escape($hl['expires_at']); ?></td>
											<td><span class="tag <?php echo $hist_status_off ? 'off' : ''; ?>"><?php echo html_escape($hist_status); ?></span></td>
											<td><?php echo html_escape($motivo); ?></td>
										</tr>
									<?php endforeach; ?>
								<?php endif; ?>
							</tbody>
						</table>
						<div style="display:flex;justify-content:flex-end;margin-top:10px;">
							<button type="button" class="modal-close" id="cancelLinksHistoryModal">Cerrar</button>
						</div>
					</div>
				</div>
				<section class="card">
					<h3>Links Generados</h3>
					<table>
						<thead>
							<tr>
								<th>ID</th>
								<th>Cliente</th>
								<th>Creado Por</th>
								<th>Vence</th>
								<th>Estado</th>
								<th>URL</th>
								<th>Accion</th>
							</tr>
						</thead>
						<tbody>
							<?php if (count($links) === 0): ?>
								<tr><td colspan="7">Sin links.</td></tr>
							<?php else: ?>
								<?php foreach ($links as $l): ?>
									<?php $is_expired = strtotime($l['expires_at']) < time(); ?>
									<?php $is_inactive = (int) $l['status'] !== 1; ?>
									<tr>
										<td>#<?php echo (int) $l['id']; ?></td>
										<td><?php echo html_escape($l['customer_name']); ?></td>
										<td>
											<?php
												$created_by_label = trim((string) $l['created_by']);
												$created_by_label = preg_replace('/\s*\(#\d+\)\s*$/', '', $created_by_label);
												echo html_escape($created_by_label !== '' ? $created_by_label : '-');
											?>
										</td>
										<td><?php echo html_escape($l['expires_at']); ?></td>
										<td>
											<?php if ($is_inactive): ?>
												<span class="tag off">Desactivado</span>
											<?php else: ?>
												<span class="tag <?php echo $is_expired ? 'off' : ''; ?>"><?php echo $is_expired ? 'Expirado' : 'Activo'; ?></span>
											<?php endif; ?>
										</td>
										<td>
											<?php if (!$is_inactive): ?>
												<a href="<?php echo site_url('catalog/l/'.rawurlencode($l['token'])); ?>" target="_blank">Abrir</a>
											<?php else: ?>
												<span class="muted">Sin acceso</span>
											<?php endif; ?>
										</td>
										<td>
											<?php if (!$is_inactive): ?>
												<form method="post" action="<?php echo site_url('catalog/admin/links/delete/'.(int) $l['id']); ?>" style="display:inline;" onsubmit="return confirm('Deseas desactivar este link?');">
													<button type="submit" class="link-btn danger">Eliminar</button>
												</form>
											<?php else: ?>
												<span class="muted">-</span>
											<?php endif; ?>
										</td>
									</tr>
								<?php endforeach; ?>
							<?php endif; ?>
						</tbody>
					</table>
				</section>
			<?php endif; ?>

			<?php if ($active_tab === 'orders'): ?>
				<section class="card">
					<div class="actions-row">
						<h2 style="margin:0;">Pedidos Recientes</h2>
						<button type="button" class="btn" id="openOrdersHistoryModal">Historial</button>
					</div>
					<table class="orders-table">
						<thead>
							<tr>
								<th>Pedido</th>
								<th>Cliente</th>
								<th>Total</th>
								<th>Estado</th>
								<th>Accion</th>
								<th>Reportes</th>
							</tr>
						</thead>
						<tbody>
							<?php if (count($orders) === 0): ?>
								<tr><td colspan="6">Sin pedidos todavia.</td></tr>
							<?php else: ?>
								<?php foreach ($orders as $o): ?>
									<?php
										$sale_id = (int) $o['sale_id'];
										$sale_suspended = isset($o['sale_suspended']) ? (int) $o['sale_suspended'] : NULL;
										$sale_deleted = isset($o['sale_deleted']) ? (int) $o['sale_deleted'] : NULL;
										$status_text = 'Pendiente';
										$status_off = FALSE;
										if ($sale_id > 0)
										{
											$status_text = 'Suspendido';
											if ($sale_deleted === 1 || $sale_suspended === 0)
											{
												$status_text = 'Cerrado';
												$status_off = TRUE;
											}
										}
									?>
									<tr>
										<td class="orders-cell-main" data-label="Pedido"><a href="<?php echo site_url('catalog/admin/orders/'.(int)$o['id']); ?>">#<?php echo (int) $o['id']; ?></a><br><span class="muted"><?php echo html_escape($o['ordered_at']); ?></span></td>
										<td class="orders-cell-customer" data-label="Cliente"><?php echo html_escape($o['customer_name']); ?><br><span class="muted">Venta susp: <?php echo (int) $o['sale_id']; ?> | Loc: <?php echo (int) $o['location_id']; ?> | Emp: <?php echo (int) $o['employee_id']; ?></span></td>
										<td class="orders-cell-total" data-label="Total"><?php echo html_escape($currency_symbol . number_format((float)$o['total'], 2)); ?></td>
										<td class="orders-cell-status" data-label="Estado"><span class="tag <?php echo $status_off ? 'off' : ''; ?>"><?php echo html_escape($status_text); ?></span></td>
										<td class="orders-cell-action" data-label="Accion">
											<details class="action-menu">
												<summary><span class="action-toggle">Accion</span></summary>
												<div class="action-pop">
													<?php if ((int) $o['sale_id'] > 0): ?>
														<div class="muted" style="padding:8px 10px;">Ya procesado</div>
													<?php else: ?>
														<form method="post" action="<?php echo site_url('catalog/admin/orders/'.(int)$o['id'].'/process'); ?>" onsubmit="return confirm('Procesar este pedido y crearlo como venta suspendida en PHPPOS?');">
															<button type="submit" class="action-item">Procesar pedido</button>
														</form>
													<?php endif; ?>
													<form method="post" action="<?php echo site_url('catalog/admin/orders/'.(int)$o['id'].'/delete'); ?>" onsubmit="return confirm('Eliminar este pedido del listado?');">
														<button type="submit" class="action-item danger">Eliminar</button>
													</form>
												</div>
											</details>
										</td>
										<td class="orders-cell-reports" data-label="Reportes"><a href="<?php echo site_url('catalog/admin/orders/'.(int)$o['id'].'/csv'); ?>">CSV</a> | <a href="<?php echo site_url('catalog/admin/orders/'.(int)$o['id'].'/pdf'); ?>">PDF</a></td>
									</tr>
								<?php endforeach; ?>
							<?php endif; ?>
						</tbody>
					</table>
				</section>
				<div class="modal-backdrop" id="ordersHistoryBackdrop" aria-hidden="true">
					<div class="modal" role="dialog" aria-modal="true" aria-labelledby="ordersHistoryTitle">
						<div class="modal-head">
							<h3 id="ordersHistoryTitle">Historial de Pedidos</h3>
							<button type="button" class="modal-close" id="closeOrdersHistoryModal">X</button>
						</div>
						<p class="muted" style="margin-top:0;">Aqui se muestran pedidos procesados y eliminados.</p>
						<table>
							<thead>
								<tr>
									<th>Pedido</th>
									<th>Cliente</th>
									<th>Estado</th>
									<th>Venta Susp.</th>
									<th>Fecha</th>
								</tr>
							</thead>
							<tbody>
								<?php if (empty($order_history)): ?>
									<tr><td colspan="5">Sin historial todavia.</td></tr>
								<?php else: ?>
									<?php foreach ($order_history as $h): ?>
										<?php
											$is_deleted = isset($h['status']) && $h['status'] === 'deleted';
											$is_processed = !$is_deleted && ((isset($h['status']) && $h['status'] === 'processed') || ((int)$h['sale_id'] > 0));
										?>
										<tr>
											<td>#<?php echo (int) $h['id']; ?></td>
											<td><?php echo html_escape($h['customer_name']); ?></td>
											<td>
												<?php if ($is_deleted): ?>
													<span class="tag off">Eliminado</span>
												<?php elseif ($is_processed): ?>
													<span class="tag">Procesado</span>
												<?php else: ?>
													<span class="muted"><?php echo html_escape((string)$h['status']); ?></span>
												<?php endif; ?>
											</td>
											<td><?php echo (int) $h['sale_id'] > 0 ? '#'.(int)$h['sale_id'] : '-'; ?></td>
											<td><?php echo html_escape($h['ordered_at']); ?></td>
										</tr>
									<?php endforeach; ?>
								<?php endif; ?>
							</tbody>
						</table>
						<div style="display:flex;justify-content:flex-end;margin-top:10px;">
							<button type="button" class="modal-close" id="cancelOrdersHistoryModal">Cerrar</button>
						</div>
					</div>
				</div>
			<?php endif; ?>

			<?php if ($active_tab === 'inventory'): ?>
				<section class="card">
					<h2>Inventario PHPPOS</h2>
					<p id="inventoryNotice" class="muted" style="margin:0 0 10px;"></p>
					<div class="inv-search-row">
						<input
							type="text"
							id="inventorySearchInput"
							class="inv-search-input"
							placeholder="Buscar por nombre o modelo..."
							autocomplete="off"
						>
						<button type="button" class="modal-close inv-search-clear" id="inventorySearchClear">Limpiar</button>
					</div>
					<p id="inventorySearchHint" class="muted" style="margin:0 0 10px;display:none;">Sin resultados para esta búsqueda.</p>
					<table class="inventory-table">
						<thead>
							<tr>
								<th>Nombre</th>
								<th>Modelo</th>
								<th class="inv-col-ecommerce">Ecommerce</th>
								<th>Fotos</th>
								<th>Acciones</th>
							</tr>
						</thead>
						<tbody>
							<?php if (empty($inventory_items)): ?>
								<tr><td colspan="5">Sin items para mostrar.</td></tr>
							<?php else: ?>
								<?php foreach ($inventory_items as $it): ?>
									<tr data-inv-item-id="<?php echo (int) $it['item_id']; ?>" data-search="<?php echo html_escape(strtolower(trim($it['name'].' '.$it['model_code']))); ?>">
										<td class="js-inv-item-name inv-cell-name" data-label="Nombre"><?php echo html_escape($it['name']); ?></td>
										<td class="inv-cell-model" data-label="Modelo"><?php echo html_escape(trim((string)$it['model_code']) !== '' ? $it['model_code'] : '-'); ?></td>
										<td class="inv-col-ecommerce inv-cell-ecommerce" data-label="Ecommerce">
											<form class="inv-toggle-form js-inv-toggle-form" method="post" action="<?php echo site_url('catalog/admin/inventory/'.(int)$it['item_id'].'/ecommerce'); ?>">
												<input type="hidden" name="is_ecommerce" value="0">
												<label class="inv-switch" title="Activar o desactivar ecommerce">
													<input type="checkbox" name="is_ecommerce" value="1" <?php echo ((int)$it['is_ecommerce'] === 1) ? 'checked' : ''; ?>>
													<span class="inv-slider"></span>
												</label>
												<span class="muted js-inv-ecom-label"><?php echo ((int)$it['is_ecommerce'] === 1) ? 'Si' : 'No'; ?></span>
											</form>
										</td>
										<td class="inv-cell-photos" data-label="Fotos">
											<div class="inv-photo-list js-inv-photo-list">
												<?php if (!empty($it['image_ids'])): ?>
													<?php $inv_images_json = json_encode(array_values($it['image_ids'])); ?>
													<?php $shown = 0; foreach ($it['image_ids'] as $img_id): if ($shown >= 3) { break; } ?>
														<button
															type="button"
															class="inv-photo-btn js-inv-open-gallery"
															data-images="<?php echo html_escape($inv_images_json); ?>"
															data-start-index="<?php echo (int) $shown; ?>"
															data-item-name="<?php echo html_escape($it['name']); ?>"
															data-item-id="<?php echo (int) $it['item_id']; ?>"
														>
															<img class="inv-photo" src="<?php echo site_url('catalog/image/'.(int)$img_id); ?>" alt="Foto item">
														</button>
													<?php $shown++; endforeach; ?>
													<span class="muted"><?php echo (int) $it['image_count']; ?> foto(s)</span>
												<?php else: ?>
													<span class="muted">Sin fotos</span>
												<?php endif; ?>
											</div>
										</td>
										<td class="inv-cell-actions" data-label="Acciones">
											<div class="inv-actions">
												<button
													type="button"
													class="btn js-open-inv-upload-modal"
													style="padding:6px 10px;"
													data-item-id="<?php echo (int) $it['item_id']; ?>"
													data-item-name="<?php echo html_escape($it['name']); ?>"
													data-upload-url="<?php echo site_url('catalog/admin/inventory/'.(int)$it['item_id'].'/upload-image'); ?>"
												>Subir imagen</button>
											</div>
										</td>
									</tr>
								<?php endforeach; ?>
							<?php endif; ?>
						</tbody>
					</table>
				</section>
				<div class="modal-backdrop" id="inventoryUploadBackdrop" aria-hidden="true">
					<div class="modal" role="dialog" aria-modal="true" aria-labelledby="inventoryUploadTitle" style="width:min(560px,96vw);">
						<div class="modal-head">
							<h3 id="inventoryUploadTitle">Subir imagen</h3>
							<button type="button" class="modal-close" id="closeInventoryUploadModal">X</button>
						</div>
						<p class="muted" id="inventoryUploadItemLabel" style="margin-top:0;"></p>
						<form id="inventoryUploadModalForm" method="post" enctype="multipart/form-data">
							<input class="inv-upload-modal-file" type="file" name="inventory_image" id="inventoryUploadFileInput" accept=".jpg,.jpeg,.png,.gif,.webp,image/jpeg,image/png,image/gif,image/webp" required>
							<div style="display:flex;justify-content:flex-end;gap:8px;margin-top:12px;">
								<button type="button" class="modal-close" id="cancelInventoryUploadModal">Cancelar</button>
								<button type="submit" class="btn" id="submitInventoryUploadModal">Subir</button>
							</div>
						</form>
					</div>
				</div>
				<div class="modal-backdrop" id="inventoryGalleryBackdrop" aria-hidden="true">
					<div class="modal" role="dialog" aria-modal="true" aria-labelledby="inventoryGalleryTitle" style="width:min(980px,96vw);">
						<div class="modal-head">
							<h3 id="inventoryGalleryTitle">Fotos del item</h3>
							<button type="button" class="modal-close" id="closeInventoryGalleryModal">X</button>
						</div>
						<div class="inv-gallery-stage" id="inventoryGalleryStage">
							<button type="button" class="inv-gallery-nav inv-gallery-prev" id="inventoryGalleryPrev">&#8249;</button>
							<img class="inv-gallery-image" id="inventoryGalleryImage" src="" alt="Foto inventario">
							<button type="button" class="inv-gallery-nav inv-gallery-next" id="inventoryGalleryNext">&#8250;</button>
						</div>
						<div class="inv-gallery-thumbs" id="inventoryGalleryThumbs"></div>
						<div class="inv-gallery-actions">
							<button type="button" class="modal-close" id="inventoryGalleryMovePrev">Mover izquierda</button>
							<button type="button" class="modal-close" id="inventoryGalleryMoveNext">Mover derecha</button>
							<button type="button" class="modal-close" id="inventoryGalleryDelete" style="color:#b91c1c;">Eliminar foto</button>
						</div>
						<div style="display:flex;justify-content:flex-end;margin-top:10px;">
							<button type="button" class="modal-close" id="cancelInventoryGalleryModal">Cerrar</button>
						</div>
					</div>
				</div>
			<?php endif; ?>

			<?php if ($active_tab === 'employees'): ?>
				<section class="card">
					<h2>Permisos De Empleados</h2>
					<p class="muted">Permisos por modulo: solo vera y podra entrar a lo que tenga habilitado.</p>
					<form method="post" action="<?php echo site_url('catalog/admin/permissions/save'); ?>">
						<table>
							<thead>
								<tr>
									<th>Empleado</th>
									<th>Dashboard</th>
									<th>Links</th>
									<th>Ver Pedidos</th>
									<th>Inventario</th>
									<th>Catalogo</th>
									<th>Descargar</th>
									<th>Empleados</th>
								</tr>
							</thead>
							<tbody>
								<?php foreach ($permission_rows as $row): ?>
									<?php $label = trim($row['first_name'].' '.$row['last_name']); if ($label === '') { $label = $row['username']; } ?>
									<tr>
										<td>#<?php echo (int) $row['person_id']; ?> - <?php echo html_escape($label); ?></td>
										<td><input type="checkbox" name="perm[<?php echo (int) $row['person_id']; ?>][can_view_dashboard]" value="1" <?php echo ((int)$row['can_view_dashboard'] === 1) ? 'checked' : ''; ?>></td>
										<td><input type="checkbox" name="perm[<?php echo (int) $row['person_id']; ?>][can_manage_links]" value="1" <?php echo ((int)$row['can_manage_links'] === 1) ? 'checked' : ''; ?>></td>
										<td><input type="checkbox" name="perm[<?php echo (int) $row['person_id']; ?>][can_view_orders]" value="1" <?php echo ((int)$row['can_view_orders'] === 1) ? 'checked' : ''; ?>></td>
										<td><input type="checkbox" name="perm[<?php echo (int) $row['person_id']; ?>][can_manage_inventory]" value="1" <?php echo ((int)$row['can_manage_inventory'] === 1) ? 'checked' : ''; ?>></td>
										<td><input type="checkbox" name="perm[<?php echo (int) $row['person_id']; ?>][can_manage_catalog]" value="1" <?php echo ((int)$row['can_manage_catalog'] === 1) ? 'checked' : ''; ?>></td>
										<td><input type="checkbox" name="perm[<?php echo (int) $row['person_id']; ?>][can_download_reports]" value="1" <?php echo ((int)$row['can_download_reports'] === 1) ? 'checked' : ''; ?>></td>
										<td><input type="checkbox" name="perm[<?php echo (int) $row['person_id']; ?>][can_manage_permissions]" value="1" <?php echo ((int)$row['can_manage_permissions'] === 1) ? 'checked' : ''; ?>></td>
									</tr>
								<?php endforeach; ?>
							</tbody>
						</table>
						<p style="margin-top:10px;"><button class="btn" type="submit">Guardar Permisos</button></p>
					</form>
				</section>
			<?php endif; ?>

			<?php if ($active_tab === 'settings'): ?>
				<section class="card">
					<h2>Configuracion Catalogo</h2>
					<form method="post" action="<?php echo site_url('catalog/admin/settings/save'); ?>" style="margin-top:10px;">
						<div class="settings-tabs" id="settingsTabs">
							<button type="button" class="settings-tab-btn active" data-settings-tab="general">General</button>
							<button type="button" class="settings-tab-btn" data-settings-tab="precios">Precios</button>
							<button type="button" class="settings-tab-btn" data-settings-tab="mensaje">Mensajes</button>
							<button type="button" class="settings-tab-btn" data-settings-tab="categorias">Categorias</button>
						</div>

						<div class="settings-panel active" data-settings-panel="general">
							<div class="row">
							<div>
								<label>Orden de mercancia dentro de categoria</label>
								<select name="product_order">
									<option value="name_asc" <?php echo $product_order === 'name_asc' ? 'selected' : ''; ?>>Nombre A - Z</option>
									<option value="name_desc" <?php echo $product_order === 'name_desc' ? 'selected' : ''; ?>>Nombre Z - A</option>
									<option value="newest" <?php echo $product_order === 'newest' ? 'selected' : ''; ?>>Mas recientes primero</option>
									<option value="oldest" <?php echo $product_order === 'oldest' ? 'selected' : ''; ?>>Mas antiguos primero</option>
								</select>
							</div>
							<div>
								<label>Stock minimo visible por sucursal</label>
								<input type="number" name="min_visible_stock" min="0" step="1" value="<?php echo (int) $min_visible_stock; ?>">
								<p class="muted" style="margin:6px 0 0;">0 muestra todo. Si colocas un valor mayor, solo se muestran productos con inventario >= ese minimo en la sucursal del link.</p>
							</div>
						</div>
						</div>

						<div class="settings-panel" data-settings-panel="precios">
							<div>
								<label>Tier price a mostrar en el catalogo</label>
								<select name="catalog_price_tier_id">
									<option value="0" <?php echo ((int) $catalog_price_tier_id === 0) ? 'selected' : ''; ?>>Usar tier del cliente del link</option>
									<?php foreach ($price_tiers as $tier): ?>
										<option value="<?php echo (int) $tier['id']; ?>" <?php echo ((int) $catalog_price_tier_id === (int) $tier['id']) ? 'selected' : ''; ?>>
											<?php echo html_escape($tier['name']); ?> (Tier #<?php echo (int) $tier['id']; ?>)
										</option>
									<?php endforeach; ?>
								</select>
								<p class="muted" style="margin:6px 0 0;">Si eliges un tier aqui, se aplica ese precio para todos los links del catalogo.</p>
							</div>
						</div>

						<div class="settings-panel" data-settings-panel="mensaje">
							<div style="margin-bottom:0;">
								<label>Mensaje final de agradecimiento</label>
								<textarea name="thank_you_message" rows="4" placeholder="Ej: Gracias por su pedido."><?php echo html_escape($thank_you_message); ?></textarea>
								<p class="muted" style="margin:6px 0 0;">Este mensaje aparece en la pagina final luego de confirmar el pedido.</p>
								<p style="margin:8px 0 0;">
									<a class="btn" href="<?php echo site_url('catalog/admin/preview_thanks_page'); ?>" target="_blank">Visualizar pagina de agradecimiento</a>
								</p>
							</div>
							<div style="margin-top:12px;">
								<label>Anuncio en catalogo</label>
								<textarea name="catalog_announcement" rows="3" placeholder="Ej: Promocion de la semana, entrega especial, aviso importante..."><?php echo html_escape($catalog_announcement); ?></textarea>
								<p class="muted" style="margin:6px 0 0;">Este anuncio aparece en el catalogo publico, debajo del encabezado.</p>
							</div>
							<div style="margin-top:12px;">
								<label>Mensaje para link desactivado</label>
								<textarea name="disabled_link_message" rows="3" placeholder="Ej: Este link fue desactivado. Contacte a su asesor."><?php echo html_escape($disabled_link_message); ?></textarea>
								<p class="muted" style="margin:6px 0 0;">Este mensaje aparece cuando un cliente abre un link desactivado.</p>
								<p style="margin:8px 0 0;">
									<a class="btn" href="<?php echo site_url('catalog/admin/preview_disabled_page'); ?>" target="_blank">Visualizar pagina de link desactivado</a>
								</p>
							</div>
							<div style="margin-top:12px;">
								<label>Terminos y condiciones de compra</label>
								<textarea name="checkout_terms" rows="4" placeholder="Ej: Al confirmar acepto tiempos de entrega, politicas de cambio y condiciones de pago."><?php echo html_escape($checkout_terms); ?></textarea>
								<p class="muted" style="margin:6px 0 0;">Este texto aparece en el modal de confirmar compra y el cliente debe aceptarlo para continuar.</p>
							</div>
						</div>

						<div class="settings-panel" data-settings-panel="categorias">
							<h3 style="margin-bottom:8px;">Orden de categorias</h3>
							<table>
								<thead>
									<tr>
										<th>Orden</th>
										<th>Categoria</th>
										<th>Items visibles</th>
									</tr>
								</thead>
								<tbody>
									<?php if (empty($category_order_rows)): ?>
										<tr><td colspan="3">Sin categorias detectadas para el catalogo actual.</td></tr>
									<?php else: ?>
										<?php foreach ($category_order_rows as $cat_row): ?>
											<tr>
												<td style="width:130px;">
													<input type="number" min="1" step="1" name="category_order[<?php echo (int) $cat_row['category_id']; ?>]" value="<?php echo (int) $cat_row['sort_order']; ?>">
												</td>
												<td><?php echo html_escape($cat_row['category_name']); ?></td>
												<td><?php echo (int) $cat_row['total_items']; ?></td>
											</tr>
										<?php endforeach; ?>
									<?php endif; ?>
								</tbody>
							</table>
						</div>
						<p style="margin-top:10px;">
							<button class="btn" type="submit">Guardar Configuracion De Catalogo</button>
						</p>
					</form>
				</section>
			<?php endif; ?>

			<?php if ($active_tab === 'templates'): ?>
				<section class="card">
					<h2>Plantillas Del Catalogo</h2>
					<p class="muted">Crea estilos visuales y activa uno para que se use en los links publicos.</p>
					<div class="actions-row">
						<div class="muted">Administra estilos y tipografias del catalogo.</div>
						<button type="button" class="btn" id="openCreateTemplate">Nueva Plantilla</button>
					</div>
				</section>

				<section class="card">
					<h3>Plantillas Guardadas</h3>
					<table>
						<thead>
							<tr>
								<th>Nombre</th>
								<th>Colores</th>
								<th>Tipografia</th>
								<th>Estilo</th>
								<th>Estado</th>
								<th>Accion</th>
							</tr>
						</thead>
						<tbody>
							<?php foreach ($templates as $tpl): ?>
								<tr>
									<td><?php echo html_escape($tpl['name']); ?></td>
									<td>
										<span style="display:inline-block;width:14px;height:14px;border-radius:3px;background:<?php echo html_escape($tpl['primary_color']); ?>;"></span>
										<?php echo html_escape($tpl['primary_color']); ?> /
										<span style="display:inline-block;width:14px;height:14px;border-radius:3px;background:<?php echo html_escape($tpl['secondary_color']); ?>;"></span>
										<?php echo html_escape($tpl['secondary_color']); ?> /
										<span style="display:inline-block;width:14px;height:14px;border-radius:3px;background:<?php echo html_escape($tpl['bg_color']); ?>;border:1px solid #ccc;"></span>
										<?php echo html_escape($tpl['bg_color']); ?> /
										<span style="display:inline-block;width:14px;height:14px;border-radius:3px;background:<?php echo html_escape($tpl['border_color']); ?>;border:1px solid #ccc;"></span>
										<?php echo html_escape($tpl['border_color']); ?>
									</td>
									<td>
										Titulo: <?php echo (int) $tpl['title_size_px']; ?>px<br>
										Desc: <?php echo (int) $tpl['desc_size_px']; ?>px<br>
										Precio: <?php echo (int) $tpl['price_size_px']; ?>px<br>
										Logo: <?php echo (int) $tpl['logo_size_px']; ?>px
									</td>
									<td><?php echo html_escape($tpl['card_style']); ?></td>
									<td><span class="tag <?php echo ((int)$tpl['is_active'] === 1) ? '' : 'off'; ?>"><?php echo ((int)$tpl['is_active'] === 1) ? 'Activa' : 'Inactiva'; ?></span></td>
									<td>
										<button
											type="button"
											class="link-btn edit-template-btn"
											data-id="<?php echo (int) $tpl['id']; ?>"
											data-name="<?php echo html_escape($tpl['name']); ?>"
											data-card_style="<?php echo html_escape($tpl['card_style']); ?>"
											data-primary_color="<?php echo html_escape($tpl['primary_color']); ?>"
											data-secondary_color="<?php echo html_escape($tpl['secondary_color']); ?>"
											data-bg_color="<?php echo html_escape($tpl['bg_color']); ?>"
											data-image_bg_color="<?php echo html_escape($tpl['image_bg_color']); ?>"
											data-border_color="<?php echo html_escape($tpl['border_color']); ?>"
											data-text_color="<?php echo html_escape($tpl['text_color']); ?>"
											data-muted_text_color="<?php echo html_escape($tpl['muted_text_color']); ?>"
											data-title_size_px="<?php echo (int) $tpl['title_size_px']; ?>"
											data-desc_size_px="<?php echo (int) $tpl['desc_size_px']; ?>"
											data-price_size_px="<?php echo (int) $tpl['price_size_px']; ?>"
											data-logo_size_px="<?php echo (int) $tpl['logo_size_px']; ?>"
										>Editar</button>
										|
										<?php if ((int)$tpl['is_active'] !== 1): ?>
											<a href="<?php echo site_url('catalog/admin/templates/activate/'.(int)$tpl['id']); ?>">Activar</a>
											|
											<form method="post" action="<?php echo site_url('catalog/admin/templates/delete/'.(int)$tpl['id']); ?>" style="display:inline;" onsubmit="return confirm('Eliminar plantilla <?php echo html_escape($tpl['name']); ?>?');">
												<button type="submit" class="link-btn danger">Eliminar</button>
											</form>
										<?php else: ?>
											<span class="muted">En uso</span>
										<?php endif; ?>
									</td>
								</tr>
							<?php endforeach; ?>
						</tbody>
					</table>
				</section>

				<div class="modal-backdrop" id="templateModalBackdrop" aria-hidden="true">
					<div class="modal" role="dialog" aria-modal="true">
						<div class="modal-head">
							<h3 id="templateModalTitle">Nueva plantilla</h3>
							<button type="button" class="modal-close" id="closeTemplateModal">X</button>
						</div>
						<form method="post" id="templateModalForm" action="<?php echo site_url('catalog/admin/templates/create'); ?>">
							<input type="hidden" name="set_active" id="tpl_set_active" value="0">
							<div class="row">
								<div>
									<label>Nombre plantilla</label>
									<input type="text" name="name" id="tpl_name" placeholder="Ej: Promo Navideno">
								</div>
								<div>
									<label>Estilo de tarjeta</label>
									<select name="card_style" id="tpl_card_style">
										<option value="rounded">Rounded</option>
										<option value="soft">Soft</option>
										<option value="sharp">Sharp</option>
									</select>
								</div>
							</div>
							<div class="row">
							<div>
								<label>Color principal</label>
								<div class="color-picker-row">
									<input type="color" name="primary_color" id="tpl_primary_color" value="#d62828">
									<span class="color-value" id="tpl_primary_color_label">#D62828</span>
								</div>
							</div>
							<div>
								<label>Color secundario</label>
								<div class="color-picker-row">
									<input type="color" name="secondary_color" id="tpl_secondary_color" value="#003049">
									<span class="color-value" id="tpl_secondary_color_label">#003049</span>
								</div>
							</div>
						</div>
						<div class="row">
							<div>
								<label>Color de fondo</label>
								<div class="color-picker-row">
									<input type="color" name="bg_color" id="tpl_bg_color" value="#fcfaf5">
									<span class="color-value" id="tpl_bg_color_label">#FCFAF5</span>
								</div>
							</div>
							<div>
								<label>Color fondo de imagen</label>
								<div class="color-picker-row">
									<input type="color" name="image_bg_color" id="tpl_image_bg_color" value="#f4f1e6">
									<span class="color-value" id="tpl_image_bg_color_label">#F4F1E6</span>
								</div>
							</div>
						</div>
						<div class="row">
							<div>
								<label>Color de borde</label>
								<div class="color-picker-row">
									<input type="color" name="border_color" id="tpl_border_color" value="#e4ddce">
									<span class="color-value" id="tpl_border_color_label">#E4DDCE</span>
								</div>
							</div>
						</div>
						<div class="row">
							<div>
								<label>Color texto principal</label>
								<div class="color-picker-row">
									<input type="color" name="text_color" id="tpl_text_color" value="#0f172a">
									<span class="color-value" id="tpl_text_color_label">#0F172A</span>
								</div>
							</div>
							<div>
								<label>Color texto secundario</label>
								<div class="color-picker-row">
									<input type="color" name="muted_text_color" id="tpl_muted_text_color" value="#546278">
									<span class="color-value" id="tpl_muted_text_color_label">#546278</span>
								</div>
							</div>
						</div>
							<div class="row">
								<div>
									<label>Tamano titulo (px)</label>
									<input type="number" name="title_size_px" id="tpl_title_size_px" value="17" min="12" max="42">
								</div>
								<div>
									<label>Tamano descripcion (px)</label>
									<input type="number" name="desc_size_px" id="tpl_desc_size_px" value="13" min="10" max="28">
								</div>
							</div>
							<div class="row">
								<div>
									<label>Tamano precio (px)</label>
									<input type="number" name="price_size_px" id="tpl_price_size_px" value="24" min="14" max="56">
								</div>
								<div>
									<label>Tamano logo (px)</label>
									<input type="number" name="logo_size_px" id="tpl_logo_size_px" value="64" min="36" max="180">
								</div>
							</div>
							<div style="display:flex;gap:8px;justify-content:flex-end;margin-top:10px;">
								<button type="button" class="modal-close" id="cancelTemplateModal">Cancelar</button>
								<button type="submit" class="btn" id="submitTemplateModal">Guardar Plantilla</button>
							</div>
						</form>
					</div>
				</div>
			<?php endif; ?>

			<?php if ($active_tab === 'preview'): ?>
				<section class="card">
					<h2>Ver Catalogo</h2>
					<p class="muted">Vista previa de como lo ve el cliente usando el link activo mas reciente.</p>
					<?php if (!empty($preview_url)): ?>
						<p>
							<a href="<?php echo html_escape($preview_url); ?>" target="_blank">Abrir en pestaña nueva</a>
							| 
							<span class="muted"><?php echo html_escape($preview_url); ?></span>
						</p>
						<iframe class="preview-frame" src="<?php echo html_escape($preview_url); ?>" title="Preview catalogo"></iframe>
					<?php else: ?>
						<p class="muted">No hay links activos para vista previa. Primero crea un link en la pestaña <strong>Links</strong>.</p>
					<?php endif; ?>
				</section>
			<?php endif; ?>
		</main>
	</div>
	<script>
	(function() {
		var activeTab = <?php echo json_encode($active_tab); ?>;
		if (activeTab !== 'links') return;

		var linkBackdrop = document.getElementById('linkModalBackdrop');
		var openLinkModalBtn = document.getElementById('openCreateLinkModal');
		var closeLinkModalBtn = document.getElementById('closeLinkModal');
		var cancelLinkModalBtn = document.getElementById('cancelLinkModal');
		var linksHistoryBackdrop = document.getElementById('linksHistoryBackdrop');
		var openLinksHistoryBtn = document.getElementById('openLinksHistoryModal');
		var closeLinksHistoryBtn = document.getElementById('closeLinksHistoryModal');
		var cancelLinksHistoryBtn = document.getElementById('cancelLinksHistoryModal');
		var customerSearchInput = document.getElementById('link_customer_search');
		var customerIdInput = document.getElementById('link_customer_id');
		var employeeSelect = document.getElementById('link_employee_select');
		var locationSelect = document.getElementById('link_location_select');
		var expiresSelect = document.getElementById('expires_days_select');
		var expiresInput = document.getElementById('expires_at_input');
		var customWrap = document.getElementById('custom_expiry_wrap');
		if (!linkBackdrop || !openLinkModalBtn || !closeLinkModalBtn || !cancelLinkModalBtn || !linksHistoryBackdrop || !openLinksHistoryBtn || !closeLinksHistoryBtn || !cancelLinksHistoryBtn || !customerSearchInput || !customerIdInput || !employeeSelect || !locationSelect || !expiresSelect || !expiresInput || !customWrap) return;

		<?php
			$customer_picker_map = array();
			foreach ($customers as $c)
			{
				$customer_label = trim($c['company_name']) !== '' ? $c['company_name'] : trim($c['first_name'].' '.$c['last_name']);
				$customer_hint = '';
				if (!empty($c['email']))
				{
					$customer_hint = ' | ' . (string) $c['email'];
				}
				$option_label = trim($customer_label . $customer_hint);
				$customer_picker_map[$option_label] = (int) $c['id'];
				$customer_picker_map[$customer_label] = (int) $c['id'];
			}
		?>
		var customerMap = <?php echo json_encode($customer_picker_map, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT); ?>;
		var allLocations = <?php echo json_encode($locations, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT); ?>;
		var employeeLocationMap = <?php echo json_encode($employee_location_map, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT); ?>;
		var defaultLocationId = <?php echo (int) $default_location_id; ?>;

		function syncCustomerId() {
			var raw = String(customerSearchInput.value || '').trim();
			if (raw === '') {
				customerIdInput.value = '';
				return;
			}
			customerIdInput.value = customerMap[raw] ? String(customerMap[raw]) : '';
		}

		function renderLocationsForEmployee() {
			var employeeId = String(employeeSelect.value || '');
			var allowed = employeeLocationMap[employeeId] || [];
			var previousValue = String(locationSelect.value || '');
			locationSelect.innerHTML = '';

			var allowedSet = {};
			for (var i = 0; i < allowed.length; i++) {
				allowedSet[String(allowed[i])] = true;
			}

			var hasAny = false;
			for (var j = 0; j < allLocations.length; j++) {
				var loc = allLocations[j];
				var locId = String(loc.location_id);
				if (!allowedSet[locId]) {
					continue;
				}
				hasAny = true;
				var opt = document.createElement('option');
				opt.value = locId;
				opt.textContent = '#' + locId + ' - ' + String(loc.name || '');
				locationSelect.appendChild(opt);
			}

			if (!hasAny) {
				var empty = document.createElement('option');
				empty.value = '';
				empty.textContent = 'Sin sucursales activas para este empleado';
				locationSelect.appendChild(empty);
				locationSelect.value = '';
				return;
			}

			if (allowedSet[previousValue]) {
				locationSelect.value = previousValue;
				return;
			}

			if (allowedSet[String(defaultLocationId)]) {
				locationSelect.value = String(defaultLocationId);
				return;
			}

			locationSelect.selectedIndex = 0;
		}

		function openLinkModal() {
			var linkForm = linkBackdrop.querySelector('form');
			if (linkForm) linkForm.reset();
			customerIdInput.value = '';
			customerSearchInput.value = '';
			syncExpiryMode();
			renderLocationsForEmployee();
			linkBackdrop.classList.add('show');
			linkBackdrop.setAttribute('aria-hidden', 'false');
		}

		function closeLinkModal() {
			linkBackdrop.classList.remove('show');
			linkBackdrop.setAttribute('aria-hidden', 'true');
		}

		function openLinksHistoryModal() {
			linksHistoryBackdrop.classList.add('show');
			linksHistoryBackdrop.setAttribute('aria-hidden', 'false');
		}

		function closeLinksHistoryModal() {
			linksHistoryBackdrop.classList.remove('show');
			linksHistoryBackdrop.setAttribute('aria-hidden', 'true');
		}

		function syncExpiryMode() {
			var isCustom = expiresSelect.value === 'custom';
			customWrap.style.display = isCustom ? 'block' : 'none';
			expiresInput.disabled = !isCustom;
			expiresInput.required = isCustom;
		}

		openLinkModalBtn.addEventListener('click', openLinkModal);
		closeLinkModalBtn.addEventListener('click', closeLinkModal);
		cancelLinkModalBtn.addEventListener('click', closeLinkModal);
		openLinksHistoryBtn.addEventListener('click', openLinksHistoryModal);
		closeLinksHistoryBtn.addEventListener('click', closeLinksHistoryModal);
		cancelLinksHistoryBtn.addEventListener('click', closeLinksHistoryModal);
		customerSearchInput.addEventListener('change', syncCustomerId);
		customerSearchInput.addEventListener('blur', syncCustomerId);
		customerSearchInput.addEventListener('input', function() {
			if (String(customerSearchInput.value || '').trim() === '') {
				customerIdInput.value = '';
			}
		});
		employeeSelect.addEventListener('change', renderLocationsForEmployee);
		linkBackdrop.addEventListener('click', function(e) {
			if (e.target === linkBackdrop) closeLinkModal();
		});
		linksHistoryBackdrop.addEventListener('click', function(e) {
			if (e.target === linksHistoryBackdrop) closeLinksHistoryModal();
		});
		var linkForm = linkBackdrop.querySelector('form');
		if (linkForm) {
			linkForm.addEventListener('submit', syncCustomerId);
		}
		expiresSelect.addEventListener('change', syncExpiryMode);
		renderLocationsForEmployee();
		syncExpiryMode();
	})();

	(function() {
		var activeTab = <?php echo json_encode($active_tab); ?>;
		if (activeTab !== 'templates') return;

		var backdrop = document.getElementById('templateModalBackdrop');
		var openCreate = document.getElementById('openCreateTemplate');
		var closeBtn = document.getElementById('closeTemplateModal');
		var cancelBtn = document.getElementById('cancelTemplateModal');
		var form = document.getElementById('templateModalForm');
		var title = document.getElementById('templateModalTitle');
		var submit = document.getElementById('submitTemplateModal');

		function byId(id) { return document.getElementById(id); }
		function openModal() { backdrop.classList.add('show'); backdrop.setAttribute('aria-hidden', 'false'); }
		function closeModal() { backdrop.classList.remove('show'); backdrop.setAttribute('aria-hidden', 'true'); }
		function syncColorLabel(inputId) {
			var input = byId(inputId);
			var label = byId(inputId + '_label');
			if (!input || !label) return;
			label.textContent = String(input.value || '').toUpperCase();
		}
		function syncAllColorLabels() {
			['tpl_primary_color','tpl_secondary_color','tpl_bg_color','tpl_image_bg_color','tpl_border_color','tpl_text_color','tpl_muted_text_color'].forEach(syncColorLabel);
		}

		function fillDefaults() {
			form.action = <?php echo json_encode(site_url('catalog/admin/templates/create')); ?>;
			title.textContent = 'Nueva plantilla';
			submit.textContent = 'Guardar Plantilla';
			byId('tpl_set_active').value = '0';
			byId('tpl_name').value = '';
			byId('tpl_card_style').value = 'rounded';
			byId('tpl_primary_color').value = '#d62828';
			byId('tpl_secondary_color').value = '#003049';
			byId('tpl_bg_color').value = '#fcfaf5';
			byId('tpl_image_bg_color').value = '#f4f1e6';
			byId('tpl_border_color').value = '#e4ddce';
			byId('tpl_text_color').value = '#0f172a';
			byId('tpl_muted_text_color').value = '#546278';
			byId('tpl_title_size_px').value = '17';
			byId('tpl_desc_size_px').value = '13';
			byId('tpl_price_size_px').value = '24';
			byId('tpl_logo_size_px').value = '64';
			syncAllColorLabels();
		}

		function openForCreate() {
			fillDefaults();
			openModal();
		}

		function openForEdit(btn) {
			form.action = <?php echo json_encode(site_url('catalog/admin/templates/update')); ?> + '/' + btn.dataset.id;
			title.textContent = 'Editar plantilla';
			submit.textContent = 'Guardar Cambios';
			byId('tpl_name').value = btn.dataset.name || '';
			byId('tpl_card_style').value = btn.dataset.card_style || 'rounded';
			byId('tpl_primary_color').value = btn.dataset.primary_color || '#d62828';
			byId('tpl_secondary_color').value = btn.dataset.secondary_color || '#003049';
			byId('tpl_bg_color').value = btn.dataset.bg_color || '#fcfaf5';
			byId('tpl_image_bg_color').value = btn.dataset.image_bg_color || '#f4f1e6';
			byId('tpl_border_color').value = btn.dataset.border_color || '#e4ddce';
			byId('tpl_text_color').value = btn.dataset.text_color || '#0f172a';
			byId('tpl_muted_text_color').value = btn.dataset.muted_text_color || '#546278';
			byId('tpl_title_size_px').value = btn.dataset.title_size_px || '17';
			byId('tpl_desc_size_px').value = btn.dataset.desc_size_px || '13';
			byId('tpl_price_size_px').value = btn.dataset.price_size_px || '24';
			byId('tpl_logo_size_px').value = btn.dataset.logo_size_px || '64';
			syncAllColorLabels();
			openModal();
		}

		openCreate.addEventListener('click', openForCreate);
		closeBtn.addEventListener('click', closeModal);
		cancelBtn.addEventListener('click', closeModal);
		backdrop.addEventListener('click', function(e) {
			if (e.target === backdrop) closeModal();
		});
		document.querySelectorAll('.edit-template-btn').forEach(function(btn) {
			btn.addEventListener('click', function() { openForEdit(btn); });
		});
		['tpl_primary_color','tpl_secondary_color','tpl_bg_color','tpl_image_bg_color','tpl_border_color','tpl_text_color','tpl_muted_text_color'].forEach(function(id) {
			var el = byId(id);
			if (el) { el.addEventListener('input', function() { syncColorLabel(id); }); }
		});

		<?php if (!empty($edit_template)): ?>
		var prefillEdit = {
			id: <?php echo (int) $edit_template['id']; ?>,
			name: <?php echo json_encode($edit_template['name']); ?>,
			card_style: <?php echo json_encode($edit_template['card_style']); ?>,
			primary_color: <?php echo json_encode($edit_template['primary_color']); ?>,
			secondary_color: <?php echo json_encode($edit_template['secondary_color']); ?>,
			bg_color: <?php echo json_encode($edit_template['bg_color']); ?>,
			image_bg_color: <?php echo json_encode($edit_template['image_bg_color']); ?>,
			border_color: <?php echo json_encode($edit_template['border_color']); ?>,
			text_color: <?php echo json_encode($edit_template['text_color']); ?>,
			muted_text_color: <?php echo json_encode($edit_template['muted_text_color']); ?>,
			title_size_px: <?php echo (int) $edit_template['title_size_px']; ?>,
			desc_size_px: <?php echo (int) $edit_template['desc_size_px']; ?>,
			price_size_px: <?php echo (int) $edit_template['price_size_px']; ?>,
			logo_size_px: <?php echo (int) $edit_template['logo_size_px']; ?>
		};
		openForEdit({ dataset: prefillEdit });
		<?php endif; ?>
	})();
	(function() {
		var activeTab = <?php echo json_encode($active_tab); ?>;
		if (activeTab !== 'settings') return;

		var tabButtons = document.querySelectorAll('[data-settings-tab]');
		var panels = document.querySelectorAll('[data-settings-panel]');
		if (!tabButtons.length || !panels.length) return;

		function showPanel(target) {
			tabButtons.forEach(function(btn) {
				btn.classList.toggle('active', btn.getAttribute('data-settings-tab') === target);
			});
			panels.forEach(function(panel) {
				panel.classList.toggle('active', panel.getAttribute('data-settings-panel') === target);
			});
		}

		tabButtons.forEach(function(btn) {
			btn.addEventListener('click', function() {
				showPanel(btn.getAttribute('data-settings-tab'));
			});
		});
	})();
	(function() {
		var activeTab = <?php echo json_encode($active_tab); ?>;
		if (activeTab !== 'orders') return;

		var openBtn = document.getElementById('openOrdersHistoryModal');
		var backdrop = document.getElementById('ordersHistoryBackdrop');
		var closeBtn = document.getElementById('closeOrdersHistoryModal');
		var cancelBtn = document.getElementById('cancelOrdersHistoryModal');
		if (!openBtn || !backdrop || !closeBtn || !cancelBtn) return;

		function openModal() {
			backdrop.classList.add('show');
			backdrop.setAttribute('aria-hidden', 'false');
		}

		function closeModal() {
			backdrop.classList.remove('show');
			backdrop.setAttribute('aria-hidden', 'true');
		}

		openBtn.addEventListener('click', openModal);
		closeBtn.addEventListener('click', closeModal);
		cancelBtn.addEventListener('click', closeModal);
		backdrop.addEventListener('click', function(e) {
			if (e.target === backdrop) closeModal();
		});
	})();
	(function() {
		var activeTab = <?php echo json_encode($active_tab); ?>;
		if (activeTab !== 'inventory') return;

		var notice = document.getElementById('inventoryNotice');
		var imageBase = <?php echo json_encode(site_url('catalog/image/')); ?>;
		var uploadBackdrop = document.getElementById('inventoryUploadBackdrop');
		var openUploadButtons = document.querySelectorAll('.js-open-inv-upload-modal');
		var closeUploadBtn = document.getElementById('closeInventoryUploadModal');
		var cancelUploadBtn = document.getElementById('cancelInventoryUploadModal');
		var uploadForm = document.getElementById('inventoryUploadModalForm');
		var uploadFileInput = document.getElementById('inventoryUploadFileInput');
		var uploadSubmitBtn = document.getElementById('submitInventoryUploadModal');
		var uploadItemLabel = document.getElementById('inventoryUploadItemLabel');
		var galleryBackdrop = document.getElementById('inventoryGalleryBackdrop');
		var galleryTitle = document.getElementById('inventoryGalleryTitle');
		var galleryStage = document.getElementById('inventoryGalleryStage');
		var galleryImage = document.getElementById('inventoryGalleryImage');
		var galleryThumbs = document.getElementById('inventoryGalleryThumbs');
		var galleryPrev = document.getElementById('inventoryGalleryPrev');
		var galleryNext = document.getElementById('inventoryGalleryNext');
		var galleryMovePrevBtn = document.getElementById('inventoryGalleryMovePrev');
		var galleryMoveNextBtn = document.getElementById('inventoryGalleryMoveNext');
		var galleryDeleteBtn = document.getElementById('inventoryGalleryDelete');
		var closeGalleryBtn = document.getElementById('closeInventoryGalleryModal');
		var cancelGalleryBtn = document.getElementById('cancelInventoryGalleryModal');
		var searchInput = document.getElementById('inventorySearchInput');
		var searchClear = document.getElementById('inventorySearchClear');
		var searchHint = document.getElementById('inventorySearchHint');
		var pendingUploadItemId = '';
		var pendingUploadUrl = '';
		var currentGalleryImages = [];
		var currentGalleryIndex = 0;
		var currentGalleryItemId = 0;
		var currentGalleryItemName = '';
		var galleryTouchStartX = 0;
		var galleryTouchStartY = 0;
		var galleryTouchDeltaX = 0;
		var galleryTouchDeltaY = 0;

		function setNotice(msg, isError) {
			if (!notice) return;
			notice.textContent = msg || '';
			notice.style.color = isError ? '#b91c1c' : '#0f766e';
		}

		function normalizeSearchText(value) {
			var txt = String(value || '').toLowerCase().trim();
			if (txt.normalize) {
				txt = txt.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
			}
			return txt;
		}

		function applyInventoryFilter() {
			var query = normalizeSearchText(searchInput ? searchInput.value : '');
			var tokens = query === '' ? [] : query.split(/\s+/).filter(Boolean);
			var rows = document.querySelectorAll('tr[data-inv-item-id]');
			var visibleCount = 0;
			rows.forEach(function(row) {
				var hay = normalizeSearchText(row.getAttribute('data-search') || row.textContent || '');
				var ok = tokens.length === 0 || tokens.every(function(tok) { return hay.indexOf(tok) !== -1; });
				row.style.display = ok ? '' : 'none';
				if (ok) visibleCount++;
			});
			if (searchHint) {
				searchHint.style.display = (tokens.length > 0 && visibleCount === 0) ? '' : 'none';
			}
		}

		function openUploadModal(itemId, itemName, uploadUrl) {
			if (!uploadBackdrop || !uploadForm || !uploadFileInput) return;
			pendingUploadItemId = String(itemId || '');
			pendingUploadUrl = String(uploadUrl || '');
			uploadForm.action = pendingUploadUrl;
			uploadForm.reset();
			if (uploadItemLabel) {
				uploadItemLabel.textContent = itemName ? ('Item #' + pendingUploadItemId + ' - ' + itemName) : ('Item #' + pendingUploadItemId);
			}
			uploadBackdrop.classList.add('show');
			uploadBackdrop.setAttribute('aria-hidden', 'false');
			uploadFileInput.focus();
		}

		function closeUploadModal() {
			if (!uploadBackdrop || !uploadForm) return;
			uploadBackdrop.classList.remove('show');
			uploadBackdrop.setAttribute('aria-hidden', 'true');
			pendingUploadItemId = '';
			pendingUploadUrl = '';
			uploadForm.reset();
		}

		function renderGallery() {
			if (!galleryImage || !galleryThumbs || !currentGalleryImages.length) return;
			galleryImage.src = imageBase + String(currentGalleryImages[currentGalleryIndex]);
			if (galleryPrev) galleryPrev.style.display = currentGalleryImages.length > 1 ? 'flex' : 'none';
			if (galleryNext) galleryNext.style.display = currentGalleryImages.length > 1 ? 'flex' : 'none';

			galleryThumbs.innerHTML = '';
			for (var i = 0; i < currentGalleryImages.length; i++) {
				(function(idx) {
					var btn = document.createElement('button');
					btn.type = 'button';
					btn.className = 'inv-gallery-thumb' + (idx === currentGalleryIndex ? ' active' : '');
					btn.addEventListener('click', function() {
						currentGalleryIndex = idx;
						renderGallery();
					});
					var img = document.createElement('img');
					img.src = imageBase + String(currentGalleryImages[idx]);
					img.alt = 'Miniatura';
					btn.appendChild(img);
					galleryThumbs.appendChild(btn);
				})(i);
			}
		}

		function syncGalleryButtonsState() {
			var hasImages = currentGalleryImages.length > 0;
			var canMovePrev = hasImages && currentGalleryIndex > 0;
			var canMoveNext = hasImages && currentGalleryIndex < (currentGalleryImages.length - 1);
			if (galleryMovePrevBtn) galleryMovePrevBtn.disabled = !canMovePrev;
			if (galleryMoveNextBtn) galleryMoveNextBtn.disabled = !canMoveNext;
			if (galleryDeleteBtn) galleryDeleteBtn.disabled = !hasImages;
		}

		function syncGalleryOrder(itemId, imageIds) {
			var id = Number(itemId || 0);
			if (id <= 0 || !Array.isArray(imageIds) || imageIds.length === 0) {
				return Promise.resolve(null);
			}
			var fd = new FormData();
			for (var i = 0; i < imageIds.length; i++) {
				fd.append('image_ids[]', String(imageIds[i]));
			}
			return fetch('<?php echo site_url('catalog/admin/inventory'); ?>/' + String(id) + '/images/reorder', {
				method: 'POST',
				body: fd,
				headers: { 'X-Requested-With': 'XMLHttpRequest' }
			})
			.then(function(r) { return r.json().then(function(data){ return { ok:r.ok, data:data }; }); })
			.then(function(res) {
				if (!res.ok || !res.data || !res.data.ok) {
					throw new Error((res.data && res.data.message) ? res.data.message : 'No se pudo guardar el orden.');
				}
				if (res.data.item) {
					updateRow(res.data.item);
				}
				setNotice(res.data.message || 'Orden de fotos guardado.', false);
				return res.data;
			});
		}

		function openGallery(itemName, images, startIndex, itemId) {
			if (!galleryBackdrop || !galleryImage) return;
			currentGalleryImages = (images || []).filter(function(v){ return Number(v) > 0; });
			if (!currentGalleryImages.length) return;
			currentGalleryIndex = Number(startIndex || 0);
			currentGalleryItemId = Number(itemId || 0);
			currentGalleryItemName = String(itemName || '');
			if (currentGalleryIndex < 0 || currentGalleryIndex >= currentGalleryImages.length) {
				currentGalleryIndex = 0;
			}
			if (galleryTitle) {
				galleryTitle.textContent = itemName ? ('Fotos - ' + itemName) : 'Fotos del item';
			}
			renderGallery();
			syncGalleryButtonsState();
			galleryBackdrop.classList.add('show');
			galleryBackdrop.setAttribute('aria-hidden', 'false');
		}

		function closeGallery() {
			if (!galleryBackdrop) return;
			galleryBackdrop.classList.remove('show');
			galleryBackdrop.setAttribute('aria-hidden', 'true');
			currentGalleryImages = [];
			currentGalleryIndex = 0;
			currentGalleryItemId = 0;
			currentGalleryItemName = '';
			if (galleryImage) galleryImage.src = '';
			if (galleryThumbs) galleryThumbs.innerHTML = '';
			syncGalleryButtonsState();
		}

		function moveGallery(step) {
			if (!currentGalleryImages.length) return;
			currentGalleryIndex = (currentGalleryIndex + step + currentGalleryImages.length) % currentGalleryImages.length;
			renderGallery();
		}

		function buildGalleryButton(imageIds, startIndex, itemName, itemId) {
			var btn = document.createElement('button');
			btn.type = 'button';
			btn.className = 'inv-photo-btn js-inv-open-gallery';
			btn.setAttribute('data-images', JSON.stringify(imageIds || []));
			btn.setAttribute('data-start-index', String(Number(startIndex || 0)));
			btn.setAttribute('data-item-name', String(itemName || ''));
			btn.setAttribute('data-item-id', String(Number(itemId || 0)));

			var img = document.createElement('img');
			img.className = 'inv-photo';
			img.src = imageBase + String(imageIds[startIndex]);
			img.alt = 'Foto item';
			btn.appendChild(img);
			return btn;
		}

		function updateRow(item) {
			if (!item || !item.item_id) return;
			var row = document.querySelector('tr[data-inv-item-id="' + String(item.item_id) + '"]');
			if (!row) return;

			var label = row.querySelector('.js-inv-ecom-label');
			if (label) {
				label.textContent = Number(item.is_ecommerce) === 1 ? 'Si' : 'No';
			}

			var toggle = row.querySelector('.js-inv-toggle-form input[type="checkbox"][name="is_ecommerce"]');
			if (toggle) {
				toggle.checked = Number(item.is_ecommerce) === 1;
			}

			var photoList = row.querySelector('.js-inv-photo-list');
			if (photoList && Array.isArray(item.image_ids)) {
				var rowItemName = '';
				var nameCell = row.querySelector('.js-inv-item-name');
				if (nameCell) {
					rowItemName = (nameCell.textContent || '').trim();
				}
				var itemName = String(item.name || rowItemName || '');
				var imageIds = item.image_ids.filter(function(v){ return Number(v) > 0; });
				photoList.innerHTML = '';
				if (imageIds.length === 0) {
					var empty = document.createElement('span');
					empty.className = 'muted';
					empty.textContent = 'Sin fotos';
					photoList.appendChild(empty);
					return;
				}

				for (var i = 0; i < imageIds.length && i < 3; i++) {
					photoList.appendChild(buildGalleryButton(imageIds, i, itemName, item.item_id));
				}
				var count = document.createElement('span');
				count.className = 'muted';
				count.textContent = String(Number(item.image_count || imageIds.length)) + ' foto(s)';
				photoList.appendChild(count);
			}
		}

		document.querySelectorAll('.js-inv-toggle-form').forEach(function(form) {
			var checkbox = form.querySelector('input[type="checkbox"][name="is_ecommerce"]');
			if (!checkbox) return;

			checkbox.addEventListener('change', function() {
				var fd = new FormData(form);
				checkbox.disabled = true;
				fetch(form.action, {
					method: 'POST',
					body: fd,
					headers: { 'X-Requested-With': 'XMLHttpRequest' }
				})
				.then(function(r) { return r.json().then(function(data){ return { ok:r.ok, data:data }; }); })
				.then(function(res) {
					if (!res.ok || !res.data || !res.data.ok) {
						throw new Error((res.data && res.data.message) ? res.data.message : 'No se pudo guardar ecommerce.');
					}
					updateRow(res.data.item);
					setNotice(res.data.message || 'Estado ecommerce actualizado.', false);
				})
				.catch(function(err) {
					checkbox.checked = !checkbox.checked;
					setNotice(err.message || 'Error al guardar ecommerce.', true);
				})
				.finally(function() {
					checkbox.disabled = false;
				});
			});
		});

		openUploadButtons.forEach(function(btn) {
			btn.addEventListener('click', function() {
				openUploadModal(btn.getAttribute('data-item-id'), btn.getAttribute('data-item-name'), btn.getAttribute('data-upload-url'));
			});
		});

		if (searchInput) {
			searchInput.addEventListener('input', applyInventoryFilter);
		}
		if (searchClear) {
			searchClear.addEventListener('click', function() {
				if (!searchInput) return;
				searchInput.value = '';
				applyInventoryFilter();
				searchInput.focus();
			});
		}

		document.addEventListener('click', function(e) {
			var btn = e.target && e.target.closest ? e.target.closest('.js-inv-open-gallery') : null;
			if (!btn) return;
			var images = [];
			try { images = JSON.parse(btn.getAttribute('data-images') || '[]'); } catch (err) { images = []; }
			openGallery(
				btn.getAttribute('data-item-name') || '',
				images,
				btn.getAttribute('data-start-index') || 0,
				btn.getAttribute('data-item-id') || 0
			);
		});

		if (closeUploadBtn) closeUploadBtn.addEventListener('click', closeUploadModal);
		if (cancelUploadBtn) cancelUploadBtn.addEventListener('click', closeUploadModal);
		if (uploadBackdrop) {
			uploadBackdrop.addEventListener('click', function(e) {
				if (e.target === uploadBackdrop) closeUploadModal();
			});
		}
		if (galleryPrev) galleryPrev.addEventListener('click', function(){ moveGallery(-1); });
		if (galleryNext) galleryNext.addEventListener('click', function(){ moveGallery(1); });
		if (galleryMovePrevBtn) {
			galleryMovePrevBtn.addEventListener('click', function() {
				if (currentGalleryIndex <= 0 || currentGalleryImages.length < 2) return;
				var idx = currentGalleryIndex;
				var prev = idx - 1;
				var tmp = currentGalleryImages[prev];
				currentGalleryImages[prev] = currentGalleryImages[idx];
				currentGalleryImages[idx] = tmp;
				currentGalleryIndex = prev;
				renderGallery();
				syncGalleryButtonsState();
				syncGalleryOrder(currentGalleryItemId, currentGalleryImages).catch(function(err) {
					setNotice(err.message || 'No se pudo guardar el orden.', true);
				});
			});
		}
		if (galleryMoveNextBtn) {
			galleryMoveNextBtn.addEventListener('click', function() {
				if (currentGalleryIndex >= currentGalleryImages.length - 1 || currentGalleryImages.length < 2) return;
				var idx = currentGalleryIndex;
				var next = idx + 1;
				var tmp = currentGalleryImages[next];
				currentGalleryImages[next] = currentGalleryImages[idx];
				currentGalleryImages[idx] = tmp;
				currentGalleryIndex = next;
				renderGallery();
				syncGalleryButtonsState();
				syncGalleryOrder(currentGalleryItemId, currentGalleryImages).catch(function(err) {
					setNotice(err.message || 'No se pudo guardar el orden.', true);
				});
			});
		}
		if (galleryDeleteBtn) {
			galleryDeleteBtn.addEventListener('click', function() {
				if (!currentGalleryImages.length || Number(currentGalleryItemId) <= 0) return;
				var imageId = Number(currentGalleryImages[currentGalleryIndex] || 0);
				if (imageId <= 0) return;
				if (!window.confirm('Deseas eliminar esta foto?')) return;

				fetch('<?php echo site_url('catalog/admin/inventory'); ?>/' + String(currentGalleryItemId) + '/image/' + String(imageId) + '/delete', {
					method: 'POST',
					headers: { 'X-Requested-With': 'XMLHttpRequest' }
				})
				.then(function(r) { return r.json().then(function(data){ return { ok:r.ok, data:data }; }); })
				.then(function(res) {
					if (!res.ok || !res.data || !res.data.ok) {
						throw new Error((res.data && res.data.message) ? res.data.message : 'No se pudo eliminar la imagen.');
					}
					if (res.data.item) {
						updateRow(res.data.item);
						currentGalleryImages = Array.isArray(res.data.item.image_ids) ? res.data.item.image_ids.filter(function(v){ return Number(v) > 0; }) : [];
					} else {
						currentGalleryImages.splice(currentGalleryIndex, 1);
					}
					if (!currentGalleryImages.length) {
						closeGallery();
					} else {
						if (currentGalleryIndex >= currentGalleryImages.length) {
							currentGalleryIndex = currentGalleryImages.length - 1;
						}
						openGallery(currentGalleryItemName, currentGalleryImages, currentGalleryIndex, currentGalleryItemId);
					}
					setNotice(res.data.message || 'Imagen eliminada correctamente.', false);
				})
				.catch(function(err) {
					setNotice(err.message || 'No se pudo eliminar la imagen.', true);
				});
			});
		}
		if (closeGalleryBtn) closeGalleryBtn.addEventListener('click', closeGallery);
		if (cancelGalleryBtn) cancelGalleryBtn.addEventListener('click', closeGallery);
		if (galleryStage) {
			galleryStage.addEventListener('touchstart', function(e) {
				if (!e.touches || e.touches.length !== 1) return;
				galleryTouchStartX = e.touches[0].clientX;
				galleryTouchStartY = e.touches[0].clientY;
				galleryTouchDeltaX = 0;
				galleryTouchDeltaY = 0;
			}, { passive: true });

			galleryStage.addEventListener('touchmove', function(e) {
				if (!e.touches || e.touches.length !== 1) return;
				galleryTouchDeltaX = e.touches[0].clientX - galleryTouchStartX;
				galleryTouchDeltaY = e.touches[0].clientY - galleryTouchStartY;
				if (Math.abs(galleryTouchDeltaX) > Math.abs(galleryTouchDeltaY)) {
					e.preventDefault();
				}
			}, { passive: false });

			galleryStage.addEventListener('touchend', function() {
				if (currentGalleryImages.length < 2) return;
				var absX = Math.abs(galleryTouchDeltaX);
				var absY = Math.abs(galleryTouchDeltaY);
				var minSwipe = 45;
				if (absX >= minSwipe && absX > absY * 1.15) {
					if (galleryTouchDeltaX < 0) {
						moveGallery(1);
					} else {
						moveGallery(-1);
					}
				}
				galleryTouchStartX = 0;
				galleryTouchStartY = 0;
				galleryTouchDeltaX = 0;
				galleryTouchDeltaY = 0;
			}, { passive: true });
		}
		if (galleryBackdrop) {
			galleryBackdrop.addEventListener('click', function(e) {
				if (e.target === galleryBackdrop) closeGallery();
			});
		}
		syncGalleryButtonsState();

		if (uploadForm) {
			uploadForm.addEventListener('submit', function(e) {
				e.preventDefault();
				if (!uploadFileInput || !uploadFileInput.files || uploadFileInput.files.length === 0) {
					setNotice('Debes seleccionar una imagen.', true);
					return;
				}
				if (!pendingUploadUrl) {
					setNotice('No se pudo determinar el item para subir la imagen.', true);
					return;
				}

				var fd = new FormData(uploadForm);
				if (uploadSubmitBtn) uploadSubmitBtn.disabled = true;
				fetch(pendingUploadUrl, {
					method: 'POST',
					body: fd,
					headers: { 'X-Requested-With': 'XMLHttpRequest' }
				})
				.then(function(r) { return r.json().then(function(data){ return { ok:r.ok, data:data }; }); })
				.then(function(res) {
					if (!res.ok || !res.data || !res.data.ok) {
						throw new Error((res.data && res.data.message) ? res.data.message : 'No se pudo subir la imagen.');
					}
					updateRow(res.data.item);
					closeUploadModal();
					setNotice(res.data.message || 'Imagen cargada correctamente.', false);
				})
				.catch(function(err) {
					setNotice(err.message || 'Error al subir imagen.', true);
				})
				.finally(function() {
					if (uploadSubmitBtn) uploadSubmitBtn.disabled = false;
				});
			});
		}

	})();
	</script>
</body>
</html>
