<!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>Reportes | <?php echo html_escape($app_name); ?></title>
	<style>
		:root {
			--bg: #f6f7fb;
			--card: #ffffff;
			--text: #1f2937;
			--muted: #64748b;
			--line: #e2e8f0;
			--primary: #0ea5a3;
		}
		* { box-sizing: border-box; }
		body { margin: 0; font-family: "Segoe UI", Tahoma, Arial, sans-serif; background: var(--bg); color: var(--text); }
		.appbar { background: var(--card); border-bottom: 1px solid var(--line); padding: 10px 12px; position: sticky; top: 0; z-index: 20; }
		.appbar-inner { max-width: 540px; margin: 0 auto; display: flex; align-items: center; justify-content: space-between; }
		.company-wrap { display: grid; grid-template-columns: 52px minmax(0, 1fr); column-gap: 10px; row-gap: 2px; align-items: center; }
		.company-wrap.no-logo { grid-template-columns: minmax(0, 1fr); }
		.brand { display: contents; }
		.company-logo { width: 52px; height: 52px; border-radius: 8px; object-fit: cover; border: 1px solid var(--line); background: var(--card); grid-column: 1; grid-row: 1 / span 2; }
		.company-name { font-size: 18px; font-weight: 800; color: var(--text); grid-column: 2; grid-row: 1; line-height: 1.15; word-break: break-word; }
		.appbar-user { font-size: 12px; color: var(--muted); grid-column: 2; grid-row: 2; }
		.company-wrap.no-logo .company-name, .company-wrap.no-logo .appbar-user { grid-column: 1; }
		.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); }
		.container { max-width: 540px; margin: 0 auto; padding: 12px 12px 24px; }
		.top h1 { margin: 6px 0 12px; font-size: 22px; }
		.card { background: var(--card); border-radius: 14px; padding: 12px; border: 1px solid var(--line); margin-bottom: 12px; }
		.grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
		.metric { border: 1px solid var(--line); border-radius: 12px; padding: 10px; }
		.metric-label { font-size: 12px; color: var(--muted); }
		.metric-value { margin-top: 4px; font-size: 21px; font-weight: 800; line-height: 1; }
		.list-card { border: 1px solid var(--line); border-radius: 12px; margin-top: 8px; overflow: hidden; }
		.list-card summary { list-style: none; cursor: pointer; padding: 10px; }
		.list-card summary::-webkit-details-marker { display: none; }
		.list-head { display: flex; justify-content: space-between; gap: 8px; font-size: 12px; color: var(--muted); margin-bottom: 4px; }
		.list-title { font-size: 15px; font-weight: 700; }
		.list-meta { font-size: 12px; color: var(--muted); margin-top: 2px; }
		.list-right { font-size: 14px; font-weight: 800; color: var(--text); white-space: nowrap; }
		.price-wrap { display: inline-flex; flex-direction: row; align-items: baseline; justify-content: flex-end; gap: 6px; white-space: nowrap; }
		.price-old { font-size: 12px; color: var(--muted); text-decoration: line-through; font-weight: 600; }
		.price-now { font-size: 14px; font-weight: 800; color: var(--text); }
		.report-details { border-top: 1px solid var(--line); padding: 10px; }
		.detail-row { display: flex; justify-content: space-between; gap: 8px; font-size: 12px; color: var(--muted); margin-top: 4px; }
		.material-table { margin-top: 8px; border-top: 1px dashed var(--line); padding-top: 8px; }
		.material-head, .material-row { display: grid; grid-template-columns: 1fr auto auto; gap: 8px; font-size: 12px; }
		.material-head { color: var(--muted); font-weight: 700; margin-bottom: 4px; }
		.material-row { padding: 4px 0; border-top: 1px dashed var(--line); }
		.material-row:first-child { border-top: 0; }
		.right { text-align: right; }
		.photo-grid { margin-top: 8px; display: flex; flex-wrap: wrap; gap: 8px; }
		.photo-thumb { width: 68px; height: 68px; border: 1px solid var(--line); border-radius: 8px; background: var(--card); padding: 0; margin: 0; overflow: hidden; cursor: pointer; }
		.photo-thumb img { width: 100%; height: 100%; object-fit: cover; display: block; }
		.modal-backdrop { position: fixed; inset: 0; background: rgba(15, 23, 42, 0.45); opacity: 0; pointer-events: none; transition: opacity 0.2s ease; z-index: 39; }
		.modal { position: fixed; left: 50%; top: 50%; transform: translate(-50%, -48%); width: min(94vw, 760px); max-height: 92vh; overflow: hidden; background: var(--card); border: 1px solid var(--line); border-radius: 14px; padding: 10px; z-index: 40; opacity: 0; pointer-events: none; transition: all 0.2s ease; }
		.modal.open { opacity: 1; pointer-events: auto; transform: translate(-50%, -50%); }
		.modal-backdrop.open { opacity: 1; pointer-events: auto; }
		.modal-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px; }
		.modal-head h3 { margin: 0; font-size: 18px; }
		.viewer-wrap { width: 100%; height: calc(92vh - 70px); display: flex; align-items: center; justify-content: center; }
		.viewer-wrap img { max-width: 100%; max-height: 100%; object-fit: contain; border-radius: 8px; border: 1px solid var(--line); background: var(--card); }
		.empty { font-size: 13px; 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; margin-top: 0; padding: 0; }
		.module-link { display: block; text-decoration: none; font-weight: 700; color: var(--text); padding: 11px 12px; border-radius: 10px; border: 1px solid var(--line); margin-bottom: 8px; }
		.module-link.active { background: var(--primary); color: #fff; border-color: var(--primary); }
		.drawer-bottom { margin-top: auto; }
		.logout-link { display: block; margin-top: 8px; text-decoration: none; text-align: center; font-weight: 700; color: var(--text); padding: 10px 12px; border: 1px solid var(--line); border-radius: 10px; }
	</style>
</head>
<?php
	$theme_current = $this->session->userdata('theme') ? $this->session->userdata('theme') : 'claro';
	$theme_custom_vars = $this->session->userdata('theme_custom_vars');
	$is_custom_theme = (strpos((string) $theme_current, 'custom_') === 0) && is_array($theme_custom_vars);
	$theme_render = $theme_current;
	if (!$is_custom_theme && strpos((string) $theme_current, 'custom_') === 0) {
		$theme_render = 'claro';
	}
	$body_class = $is_custom_theme ? 'theme-custom' : 'theme-'.html_escape($theme_render);
	$theme_presets = array(
		'claro' => array('bg'=>'#f6f7fb','card'=>'#ffffff','text'=>'#1f2937','muted'=>'#64748b','line'=>'#e2e8f0','primary'=>'#0ea5a3','ok_bg'=>'#dcfce7','ok_text'=>'#166534'),
		'oscuro' => array('bg'=>'#0f172a','card'=>'#111827','text'=>'#e5e7eb','muted'=>'#9ca3af','line'=>'#334155','primary'=>'#14b8a6','ok_bg'=>'#064e3b','ok_text'=>'#bbf7d0'),
		'rosado' => array('bg'=>'#fff1f6','card'=>'#ffffff','text'=>'#4a1028','muted'=>'#8a4661','line'=>'#f8bbd0','primary'=>'#ec4899','ok_bg'=>'#fce7f3','ok_text'=>'#9d174d'),
		'fuccia' => array('bg'=>'#fdf2ff','card'=>'#ffffff','text'=>'#4a044e','muted'=>'#7e22ce','line'=>'#f0abfc','primary'=>'#d946ef','ok_bg'=>'#fae8ff','ok_text'=>'#86198f'),
		'verde' => array('bg'=>'#f0fdf4','card'=>'#ffffff','text'=>'#14532d','muted'=>'#166534','line'=>'#86efac','primary'=>'#22c55e','ok_bg'=>'#dcfce7','ok_text'=>'#166534'),
		'rojo' => array('bg'=>'#fff1f2','card'=>'#ffffff','text'=>'#7f1d1d','muted'=>'#b91c1c','line'=>'#fca5a5','primary'=>'#ef4444','ok_bg'=>'#fee2e2','ok_text'=>'#991b1b'),
		'azul_claro' => array('bg'=>'#eff6ff','card'=>'#ffffff','text'=>'#1e3a8a','muted'=>'#1d4ed8','line'=>'#93c5fd','primary'=>'#38bdf8','ok_bg'=>'#dbeafe','ok_text'=>'#1e40af'),
		'azul_rey' => array('bg'=>'#eef2ff','card'=>'#ffffff','text'=>'#1e1b4b','muted'=>'#312e81','line'=>'#a5b4fc','primary'=>'#4f46e5','ok_bg'=>'#e0e7ff','ok_text'=>'#3730a3')
	);
	$vars = $is_custom_theme ? $theme_custom_vars : (isset($theme_presets[$theme_render]) ? $theme_presets[$theme_render] : $theme_presets['claro']);
	$inline_style = '--bg:'.$vars['bg'].';--card:'.$vars['card'].';--text:'.$vars['text'].';--muted:'.$vars['muted'].';--line:'.$vars['line'].';--primary:'.$vars['primary'].';--ok-bg:'.$vars['ok_bg'].';--ok-text:'.$vars['ok_text'].';';
?>
<body class="<?php echo $body_class; ?>" style="<?php echo html_escape($inline_style); ?>">
	<header class="appbar">
		<div class="appbar-inner">
			<div class="company-wrap <?php echo empty($app_logo) ? 'no-logo' : ''; ?>">
				<?php if (!empty($app_logo)): ?>
					<div class="brand">
						<img class="company-logo" src="<?php echo base_url($app_logo); ?>" alt="Logo">
						<div class="company-name"><?php echo html_escape($app_name); ?></div>
						<div class="appbar-user">Hola, <?php echo html_escape($this->session->userdata('username')); ?></div>
					</div>
				<?php else: ?>
					<div class="brand">
						<div class="company-name"><?php echo html_escape($app_name); ?></div>
						<div class="appbar-user">Hola, <?php echo html_escape($this->session->userdata('username')); ?></div>
					</div>
				<?php endif; ?>
			</div>
			<button id="openMenu" class="menu-btn" type="button" aria-label="Abrir menu">
				<span></span><span></span><span></span>
			</button>
		</div>
	</header>

	<main class="container">
		<div class="top"><h1>Reportes</h1></div>

		<section class="card">
			<div class="grid">
				<div class="metric">
					<div class="metric-label">Clientes</div>
					<div class="metric-value"><?php echo (int) $resumen['total_clientes']; ?></div>
				</div>
				<div class="metric">
					<div class="metric-label">Pedidos pendientes</div>
					<div class="metric-value"><?php echo (int) $resumen['pedidos_pendientes']; ?></div>
				</div>
				<div class="metric">
					<div class="metric-label">Pedidos cerrados</div>
					<div class="metric-value"><?php echo (int) $resumen['pedidos_cerrados']; ?></div>
				</div>
				<div class="metric">
					<div class="metric-label">Stock productos</div>
					<div class="metric-value"><?php echo (int) $resumen['productos_stock']; ?></div>
				</div>
				<div class="metric">
					<div class="metric-label">Ventas del mes</div>
					<div class="metric-value"><?php echo number_format((float) $resumen['ventas_mes'], 2, '.', ','); ?></div>
				</div>
				<div class="metric">
					<div class="metric-label">Ventas totales</div>
					<div class="metric-value"><?php echo number_format((float) $resumen['ventas_totales'], 2, '.', ','); ?></div>
				</div>
			</div>
		</section>

		<section class="card">
			<h2 style="margin:0 0 10px;">Ultimos pedidos cerrados</h2>
			<?php if (empty($cierres_recientes)): ?>
				<div class="empty">Aun no hay pedidos cerrados.</div>
			<?php else: ?>
				<?php foreach ($cierres_recientes as $item): ?>
					<?php $estado = ((string) $item->estado === 'finalizado') ? 'Finalizado' : 'Producto'; ?>
					<?php
						$monto_base = (float) $item->total;
						$monto_real = (float) (isset($item->monto_reporte) ? $item->monto_reporte : $item->total);
						$mostrar_doble = abs($monto_real - $monto_base) > 0.009;
					?>
					<details class="list-card">
						<summary>
							<div class="list-head">
								<div class="list-title"><?php echo html_escape($item->cliente_nombre); ?></div>
								<div class="list-right">
									<?php if ($mostrar_doble): ?>
										<div class="price-wrap">
											<div class="price-old"><?php echo number_format($monto_base, 2, '.', ','); ?></div>
											<div class="price-now"><?php echo number_format($monto_real, 2, '.', ','); ?></div>
										</div>
									<?php else: ?>
										<?php echo number_format($monto_real, 2, '.', ','); ?>
									<?php endif; ?>
								</div>
							</div>
							<div class="list-meta"><?php echo html_escape($item->template_nombre); ?> | <?php echo date('d/m/Y H:i', strtotime($item->creado_en)); ?></div>
							<div class="list-meta">Estado: <?php echo html_escape($estado); ?></div>
						</summary>
						<div class="report-details">
							<div class="detail-row"><span>Costo materiales</span><span><?php echo number_format((float) $item->costo_materiales, 2, '.', ','); ?></span></div>
							<div class="detail-row"><span>Mano de obra</span><span><?php echo number_format((float) $item->costo_mano_obra, 2, '.', ','); ?></span></div>
							<div class="detail-row"><span>Costo base</span><span><?php echo number_format((float) $item->costo_base, 2, '.', ','); ?></span></div>
							<div class="detail-row"><span>Margen <?php echo number_format((float) $item->margen_porcentaje, 2, '.', ','); ?>%</span><span><?php echo number_format((float) $item->margen_monto, 2, '.', ','); ?></span></div>

							<?php if (!empty($item->lineas)): ?>
								<div class="material-table">
									<div class="material-head">
										<div>Material</div>
										<div class="right">Cant.</div>
										<div class="right">Subtotal</div>
									</div>
									<?php foreach ($item->lineas as $ln): ?>
										<div class="material-row">
											<div><?php echo html_escape($ln->material_nombre); ?></div>
											<div class="right"><?php echo number_format((float) $ln->cantidad, 2, '.', ','); ?> <?php echo html_escape($ln->unidad); ?></div>
											<div class="right"><?php echo number_format((float) $ln->subtotal, 2, '.', ','); ?></div>
										</div>
									<?php endforeach; ?>
								</div>
							<?php endif; ?>

							<?php if (!empty($item->fotos)): ?>
								<div class="photo-grid">
									<?php foreach ($item->fotos as $path): ?>
										<button type="button" class="photo-thumb" data-photo-open="<?php echo html_escape(base_url($path)); ?>" aria-label="Ver foto">
											<img src="<?php echo base_url($path); ?>" alt="Foto del pedido">
										</button>
									<?php endforeach; ?>
								</div>
							<?php endif; ?>
						</div>
					</details>
				<?php endforeach; ?>
			<?php endif; ?>
		</section>
	</main>

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

	<div id="drawerBackdrop" class="drawer-backdrop"></div>
	<aside id="drawer" class="drawer">
		<div class="drawer-head">
			<h3 class="drawer-title">Modulos</h3>
			<button id="closeMenu" class="close-btn" type="button" aria-label="Cerrar menu">x</button>
		</div>
		<a class="module-link" href="<?php echo site_url('dashboard'); ?>">Dashboard</a>
		<a class="module-link" href="<?php echo site_url('clientes'); ?>">Clientes</a>
		<a class="module-link" href="<?php echo site_url('inventario'); ?>">Inventario</a>
		<a class="module-link" href="<?php echo site_url('compras'); ?>">Compras</a>
		<a class="module-link" href="<?php echo site_url('pedidos'); ?>">Pedidos</a>
		<a class="module-link active" 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 imageViewerModal = document.getElementById('imageViewerModal');
			var imageViewerBackdrop = document.getElementById('imageViewerBackdrop');
			var closeImageViewerBtn = document.getElementById('closeImageViewer');
			var imageViewerImg = document.getElementById('imageViewerImg');

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

			if (openBtn) openBtn.addEventListener('click', openMenu);
			if (closeBtn) closeBtn.addEventListener('click', closeMenu);
			if (backdrop) backdrop.addEventListener('click', closeMenu);

			function openImageViewer(src) {
				if (!imageViewerModal || !imageViewerBackdrop || !imageViewerImg || !src) return;
				imageViewerImg.src = src;
				imageViewerModal.classList.add('open');
				imageViewerBackdrop.classList.add('open');
			}

			function closeImageViewer() {
				if (!imageViewerModal || !imageViewerBackdrop || !imageViewerImg) return;
				imageViewerModal.classList.remove('open');
				imageViewerBackdrop.classList.remove('open');
				imageViewerImg.src = '';
			}

			document.addEventListener('click', function (e) {
				var btnPhotoOpen = e.target.closest('[data-photo-open]');
				if (btnPhotoOpen) {
					e.preventDefault();
					openImageViewer(btnPhotoOpen.getAttribute('data-photo-open') || '');
				}
			});

			if (closeImageViewerBtn) closeImageViewerBtn.addEventListener('click', closeImageViewer);
			if (imageViewerBackdrop) imageViewerBackdrop.addEventListener('click', closeImageViewer);
		})();
	</script>
</body>
</html>
