siip-whatsapp-notifications.../public.php

1525 lines
60 KiB
PHP
Executable File

<?php
require_once __DIR__ . '/vendor/autoload.php';
chdir(__DIR__);
use Ubnt\UcrmPluginSdk\Service\PluginConfigManager;
use Ubnt\UcrmPluginSdk\Service\UcrmApi;
use SmsNotifier\Service\PaymentIntentService;
// Carga manual del servicio
require_once __DIR__ . '/src/Service/PaymentIntentService.php';
if (!file_exists(__DIR__ . '/data/config.json')) {
die('Acceso denegado o configuración no encontrada.');
}
$configManager = PluginConfigManager::create();
$config = $configManager->loadConfig();
$logger = new \SmsNotifier\Service\Logger();
// LOG DE EMERGENCIA
$debugLogPath = __DIR__ . '/data/debug_public.log';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$input = file_get_contents('php://input');
$jsonData = json_decode((string)$input, true);
if ($jsonData && (isset($jsonData['uuid']) || isset($jsonData['eventName']) || isset($jsonData['type']))) {
file_put_contents($debugLogPath, "[" . date('Y-m-d H:i:s') . "] Webhook in public.php. Delegating..." . PHP_EOL, FILE_APPEND);
$builder = new \DI\ContainerBuilder();
$container = $builder->build();
$plugin = $container->get(\SmsNotifier\Plugin::class);
$plugin->run();
exit;
}
}
$ipServer = $config['ipserver'] ?? 'localhost';
$ucrmApiUrl = 'https://' . $ipServer . '/crm/api/v1.0/';
$ucrmPublicUrl = 'https://' . $ipServer . '/crm';
$httpClient = new \GuzzleHttp\Client([
'base_uri' => $ucrmApiUrl,
'verify' => false,
'timeout' => 15
]);
$ucrmApi = new UcrmApi($httpClient, $config['apitoken'] ?? '');
$stripeService = new PaymentIntentService(
$ucrmApi,
$config['tokenstripe'] ?? '',
$logger
);
// Admins Logic
$admins = [];
$defaultStripeAdminId = null;
try {
$adminsRaw = $ucrmApi->get('users/admins');
foreach ($adminsRaw as $admin) {
$nombre = trim(($admin['firstName'] ?? '') . ' ' . ($admin['lastName'] ?? ''));
$admins[] = ['id' => $admin['id'], 'nombre' => $nombre];
if (strtolower($nombre) === 'stripe' || strtolower($admin['username'] ?? '') === 'stripe') {
$defaultStripeAdminId = $admin['id'];
}
}
if ($defaultStripeAdminId === null && !empty($admins)) $defaultStripeAdminId = $admins[0]['id'];
} catch (\Exception $e) {
}
// API HANDLERS
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
if ($_POST['action'] === 'save_installers') {
$installersJson = $_POST['installers_data'] ?? '';
if (json_decode($installersJson) !== null) {
$configPath = __DIR__ . '/data/config.json';
$currentConfig = json_decode(file_get_contents($configPath), true);
$currentConfig['installersDataWhatsApp'] = $installersJson;
file_put_contents($configPath, json_encode($currentConfig, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
echo json_encode(['success' => true]);
exit;
}
echo json_encode(['success' => false]);
exit;
}
if ($_POST['action'] === 'resend_payment') {
$paymentId = $_POST['paymentId'] ?? null;
try {
$payment = $ucrmApi->get("payments/$paymentId");
$client = $ucrmApi->get("clients/{$payment['clientId']}");
$payload = [
'uuid' => 'manual-trigger',
'changeType' => 'insert',
'entity' => 'payment',
'entityId' => (int)$paymentId,
'eventName' => 'payment.add',
'clientData' => $client,
'paymentData' => $payment
];
// Internal Loopback
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$selfUrl = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$ch = curl_init($selfUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
$res = curl_exec($ch);
curl_close($ch);
echo json_encode(['success' => true, 'message' => 'Notificación disparada.']);
} catch (\Exception $e) {
echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
exit;
}
}
if (isset($_GET['action'])) {
header('Content-Type: application/json');
if ($_GET['action'] === 'search_clients') {
$q = $_GET['q'] ?? '';
try {
$clients = $ucrmApi->get('clients', ['query' => $q, 'limit' => 6]);
echo json_encode($clients);
} catch (\Exception $e) {
echo json_encode([]);
}
exit;
}
if ($_GET['action'] === 'get_payments') {
$clientId = $_GET['clientId'] ?? null;
try {
$payments = $ucrmApi->get('payments', ['clientId' => $clientId, 'limit' => 20, 'order' => 'createdDate', 'direction' => 'DESC']);
$methods = $ucrmApi->get('payment-methods');
$methodMap = [];
foreach ($methods as $m) $methodMap[$m['id']] = $m['name'];
$formatted = array_slice($payments, 0, 10);
foreach ($formatted as &$p) $p['methodName'] = $methodMap[$p['methodId']] ?? 'N/A';
echo json_encode($formatted);
} catch (\Exception $e) {
echo json_encode([]);
}
exit;
}
if ($_GET['action'] === 'search_stripe') {
$q = $_GET['q'] ?? '';
echo json_encode($stripeService->searchClients($q));
exit;
}
if ($_GET['action'] === 'get_stripe_details') {
echo json_encode($stripeService->getClientDetails($_GET['id'] ?? null));
exit;
}
if ($_GET['action'] === 'image' || $_GET['action'] === 'get_image') {
// Image Handler
if (ob_get_level()) ob_end_clean();
$filename = basename($_GET['file'] ?? $_GET['name'] ?? '');
$paths = [__DIR__ . '/img/' . $filename, __DIR__ . '/vouchers_oxxo/' . $filename];
$finalPath = null;
foreach ($paths as $p) {
if (file_exists($p)) {
$finalPath = $p;
break;
}
}
if ($finalPath) {
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
$type = ($ext === 'png') ? 'image/png' : (($ext === 'webp') ? 'image/webp' : 'image/jpeg');
header("Content-Type: $type");
header("Content-Length: " . filesize($finalPath));
readfile($finalPath);
} else {
http_response_code(404);
echo "Not Found";
}
exit;
}
}
// POST Actions for Intents
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
header('Content-Type: application/json');
if ($_POST['action'] === 'create_intent') {
$clientId = $_POST['clientId'] ?? null;
$amount = $_POST['amount'] ?? 0;
$stripeCustomerId = $_POST['stripeCustomerId'] ?? null;
$adminId = $_POST['adminId'] ?? null;
echo json_encode($stripeService->createPaymentIntent($clientId, $amount, $stripeCustomerId, $adminId));
exit;
}
if ($_POST['action'] === 'create_oxxo_intent') {
try {
$builder = new \DI\ContainerBuilder();
$container = $builder->build();
$oxxoService = $container->get(\SmsNotifier\Facade\PluginOxxoNotifierFacade::class);
if (ob_get_length()) ob_clean();
$result = $oxxoService->createOxxoPaymentIntent(['client_id' => $_POST['clientId']], $_POST['amount'], false);
if (ob_get_length()) ob_clean();
echo json_encode(['success' => true, 'data' => $result]);
} catch (\Exception $e) {
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
exit;
}
}
$installersData = json_decode($config['installersDataWhatsApp'] ?? '{"instaladores":[]}', true);
?>
<!DOCTYPE html>
<html lang="es" data-theme="light">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SIIP - Notificaciones y Pagos</title>
<link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600;700&display=swap" rel="stylesheet">
<style>
:root {
--primary: #2563eb;
--primary-hover: #1d4ed8;
--bg-body: #f8fafc;
--bg-card: #ffffff;
--text-main: #1e293b;
--text-muted: #64748b;
--border: #e2e8f0;
--danger: #ef4444;
--success: #22c55e;
--transition: all 0.3s ease;
--primary-surface: rgba(37, 99, 235, 0.08);
/* Re-added for standard consistency */
}
[data-theme="dark"] {
--primary: #60a5fa;
--primary-hover: #93c5fd;
--bg-body: #0f172a;
--bg-card: #1e293b;
--text-main: #f1f5f9;
--text-muted: #94a3b8;
--border: #334155;
--primary-surface: rgba(96, 165, 250, 0.15);
}
/* RESET BOX-SIZING */
*,
*::before,
*::after {
box-sizing: border-box;
}
body {
font-family: 'Outfit', sans-serif;
background-color: var(--bg-body);
color: var(--text-main);
padding: 2rem;
margin: 0;
min-height: 100vh;
transition: var(--transition);
display: flex;
flex-direction: column;
}
.container {
max-width: 1400px;
margin: 0 auto;
flex: 1;
}
/* HEADER - Restored Layout */
.header {
background: var(--bg-card);
padding: 2rem;
border-radius: 16px;
margin-bottom: 2rem;
border: 1px solid var(--border);
display: flex;
justify-content: space-between;
align-items: center;
}
/* MENU DASHBOARD */
.menu-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 25px;
max-width: 1200px;
margin: 0 auto;
}
.menu-item {
background-color: var(--bg-card);
border-radius: 12px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
padding: 25px;
text-align: center;
transition: var(--transition);
cursor: pointer;
border: 1px solid var(--border);
display: flex;
flex-direction: column;
align-items: center;
min-height: 250px;
}
.menu-item:hover {
transform: translateY(-5px);
border-color: var(--primary);
}
.menu-item img {
width: 120px;
height: 120px;
object-fit: contain;
margin-bottom: 20px;
}
.menu-item h3 {
margin: 0 0 10px 0;
font-size: 1.6em;
}
.menu-item p {
margin: 0;
color: var(--text-muted);
}
/* MODULES & NEW SEARCH UI */
.section-view {
display: none;
}
.section-view.active {
display: block;
}
/* TAB NAVIGATION SYSTEM */
.tabs {
display: flex;
gap: 10px;
padding: 1rem 0;
border-bottom: 2px solid var(--border);
margin-bottom: 2rem;
flex-wrap: wrap;
position: sticky;
top: 0;
background: var(--bg-body);
z-index: 100;
}
.tab {
padding: 12px 24px;
border-radius: 8px 8px 0 0;
text-decoration: none;
color: var(--text-main);
font-weight: 500;
transition: all 0.3s ease;
border: 2px solid transparent;
white-space: nowrap;
display: flex;
align-items: center;
cursor: pointer;
}
.tab:hover {
background: var(--bg-card);
border-color: var(--primary);
}
.tab.active {
background: var(--primary);
color: white;
border-color: var(--primary);
}
.hidden {
display: none !important;
}
.card {
background: var(--bg-card);
border-radius: 16px;
padding: 2rem;
border: 1px solid var(--border);
margin-bottom: 2rem;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}
/* SEARCH STYLES */
.search-wrapper {
position: relative;
width: 100%;
}
.search-icon {
position: absolute;
left: 15px;
top: 50%;
transform: translateY(-50%);
color: var(--text-muted);
width: 20px;
height: 20px;
}
.search-input-padded {
padding-left: 45px !important;
}
.form-control {
width: 100%;
padding: 12px 16px;
border-radius: 10px;
border: 1px solid var(--border);
background: var(--bg-body);
color: var(--text-main);
font-size: 1rem;
}
/* RICH SEARCH RESULTS */
.search-results {
position: absolute;
top: 100%;
left: 0;
right: 0;
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: 10px;
margin-top: 5px;
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
z-index: 2000;
display: none;
max-height: 400px;
overflow-y: auto;
}
.search-item {
padding: 15px;
border-bottom: 1px solid var(--border);
cursor: pointer;
transition: background 0.2s;
display: flex;
align-items: flex-start;
gap: 12px;
}
.search-item:hover {
background: var(--bg-body);
}
.search-item:last-child {
border-bottom: none;
}
.status-dot {
width: 10px;
height: 10px;
border-radius: 50%;
margin-top: 6px;
flex-shrink: 0;
}
.status-dot.active {
background-color: var(--success);
}
.status-dot.suspended {
background-color: var(--danger);
box-shadow: 0 0 0 2px rgba(239, 68, 68, 0.2);
}
.client-info {
flex: 1;
}
.client-header {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
margin-bottom: 4px;
}
.client-name {
font-weight: 700;
font-size: 1.05rem;
color: var(--text-main);
}
.highlight {
background-color: #fde047;
color: black;
padding: 0 2px;
border-radius: 2px;
}
.badge-suspended {
background-color: #fffbeb;
color: #d97706;
border: 1px solid #fcd34d;
font-size: 0.7rem;
padding: 2px 8px;
border-radius: 4px;
text-transform: uppercase;
font-weight: 700;
}
.client-details {
font-size: 0.85rem;
color: var(--text-muted);
line-height: 1.4;
}
/* BUTTONS & BADGES */
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
padding: 10px 20px;
border-radius: 10px;
border: none;
font-weight: 600;
cursor: pointer;
}
.btn-primary {
background: var(--primary);
color: white;
}
.btn-secondary {
background: var(--bg-body);
border: 1px solid var(--border);
color: var(--text-main);
}
.btn-whatsapp {
background-color: #25D366;
color: white !important;
}
.badge {
padding: 4px 12px;
border-radius: 100px;
font-size: 0.85rem;
font-weight: 600;
}
/* THEME TOGGLE (Restored) */
.theme-toggle {
background: var(--bg-card);
border: 1px solid var(--border);
padding: 10px;
border-radius: 10px;
cursor: pointer;
transition: var(--transition);
display: flex;
align-items: center;
gap: 8px;
}
/* Modal & Tables */
.modal-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.5);
display: none;
align-items: center;
justify-content: center;
z-index: 3000;
}
.modal {
background: var(--bg-card);
padding: 2rem;
border-radius: 16px;
width: 90%;
max-width: 500px;
}
table {
width: 100%;
border-collapse: collapse;
}
th,
td {
padding: 12px;
text-align: left;
border-bottom: 1px solid var(--border);
}
/* Toast */
#toast {
position: fixed;
bottom: 2rem;
left: 50%;
transform: translate(-50%, 150%);
padding: 1rem 2rem;
border-radius: 12px;
background: #333;
color: #fff;
transition: transform 0.3s;
z-index: 4000;
}
#toast.show {
transform: translate(-50%, 0);
}
/* STRIPE MODULE REDESIGN */
.client-header-grid {
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 1rem;
padding-bottom: 1.5rem;
border-bottom: 1px solid var(--border);
margin-bottom: 1.5rem;
}
.client-info h3 {
margin: 0 0 4px 0;
font-size: 1.25rem;
}
.client-info p {
margin: 0;
font-size: 0.9rem;
}
.client-balance {
text-align: right;
}
.client-balance .label {
display: block;
font-size: 0.8rem;
color: var(--text-muted);
margin-bottom: 4px;
}
.client-balance .badge {
font-size: 1.1rem;
padding: 6px 16px;
}
.details-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 1.5rem;
margin-bottom: 2rem;
background: var(--bg-body);
padding: 1.5rem;
border-radius: 12px;
border: 1px solid var(--border);
}
.detail-item label {
display: block;
font-size: 0.75rem;
color: var(--text-muted);
margin-bottom: 6px;
text-transform: uppercase;
letter-spacing: 0.5px;
font-weight: 700;
}
.detail-item .value-box {
font-family: 'Courier New', monospace;
font-size: 1rem;
color: var(--text-main);
word-break: break-all;
background: var(--bg-card);
padding: 8px 12px;
border-radius: 6px;
border: 1px solid var(--border);
}
.form-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1.5rem;
margin-bottom: 1.5rem;
}
@media (max-width: 768px) {
.form-grid {
grid-template-columns: 1fr;
}
}
.form-group {
margin-bottom: 0;
}
.form-group label {
display: block;
margin-bottom: 8px;
font-weight: 600;
color: var(--text-main);
font-size: 0.9rem;
}
.section-title {
margin: 0 0 1.5rem 0;
font-size: 1.1rem;
color: var(--text-main);
border-left: 4px solid var(--primary);
padding-left: 12px;
}
.input-group {
position: relative;
display: flex;
align-items: center;
}
.input-prefix {
position: absolute;
left: 12px;
color: var(--text-muted);
font-weight: 500;
z-index: 10;
}
.input-with-prefix {
padding-left: 35px !important;
}
.actions-row {
display: flex;
gap: 1rem;
margin-top: 2rem;
justify-content: flex-end;
}
.btn-lg {
padding: 12px 24px;
font-size: 1rem;
}
.btn-outline {
background: transparent;
border: 2px solid var(--border);
color: var(--text-main);
}
.btn-outline:hover {
border-color: var(--primary);
color: var(--primary);
}
</style>
</head>
<body>
<div class="container">
<!-- HEADER -->
<div class="header">
<div style="display: flex; align-items: center; gap: 15px;">
<img src="?action=image&file=logo-empresa.png" style="width:80px; height:80px; object-fit: contain; border-radius: 12px; background: white; padding: 5px; border: 1px solid var(--border);">
<div>
<!-- RESTORED HEADER TEXT -->
<h1 style="margin: 0; font-size: 24px;">Portal Administrativo de Pagos de STRIPE y Notificaciones WhatsApp</h1>
<p style="margin: 0; color: #666;">Administración de Notificaciones vía WhatsApp, Intenciones de pago con Stripe y Fichas de OXXO Pay</p>
</div>
</div>
<div style="display: flex; gap: 10px; align-items: center;">
<button class="btn btn-secondary hidden" id="btnBackToMenu" onclick="showDashboard()">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
<polyline points="9 22 9 12 15 12 15 22" />
</svg>
Menú Principal
</button>
<!-- RESTORED THEME BUTTON -->
<button class="theme-toggle" id="themeBtn" onclick="toggleTheme()">
<span class="theme-icon">☀️</span>
<span class="theme-text" id="themeText">Modo Oscuro</span>
</button>
</div>
</div>
<!-- MAIN MENU -->
<div class="menu-container" id="mainDashboard">
<div class="menu-item" onclick="showModule('installers')">
<img src="?action=image&file=instalador.png">
<h3>Instaladores</h3>
<p>Administra los técnicos e instaladores registrados en el sistema.</p>
</div>
<div class="menu-item" onclick="showModule('notifications')">
<img src="?action=image&file=whatsapp-logo.png">
<h3>Notificaciones</h3>
<p>Re-envía manualmente notificaciones de pago vía WhatsApp.</p>
</div>
<div class="menu-item" onclick="showModule('stripe')">
<img src="?action=image&file=stripe-logo.png">
<h3>Pagos SPEI</h3>
<p>Genera referencias de Transferencia Bancaria personalizadas.</p>
</div>
<div class="menu-item" onclick="showModule('oxxo')">
<img src="?action=image&file=oxxo-logo.png">
<h3>Pagos OXXO</h3>
<p>Genera fichas y códigos de barras para pago en tiendas OXXO.</p>
</div>
</div>
<!-- MODULES -->
<div id="moduleView" class="hidden">
<!-- Tabs Navigation -->
<nav class="tabs">
<a href="#" class="tab active" onclick="switchTab('instaladores'); return false;">
<img src="?action=get_image&name=installers-management.png" style="width:24px;height:24px;vertical-align:middle;margin-right:8px;"> Instaladores
</a>
<a href="#" class="tab" onclick="switchTab('notificaciones'); return false;">
<img src="?action=get_image&name=whatsapp-notification.png" style="width:24px;height:24px;vertical-align:middle;margin-right:8px;"> Notificaciones
</a>
<a href="#" class="tab" onclick="switchTab('pagos-spei'); return false;">
<img src="?action=get_image&name=online-payments-stripe.png" style="width:24px;height:24px;vertical-align:middle;margin-right:8px;"> Pagos SPEI
</a>
<a href="#" class="tab" onclick="switchTab('pagos-oxxo'); return false;">
<img src="?action=get_image&name=oxxo-payments.png" style="width:24px;height:24px;vertical-align:middle;margin-right:8px;"> Pagos OXXO
</a>
</nav>
<!-- MODULE 1: INSTALLERS -->
<section id="section-instaladores" class="section-view active">
<div class="card">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem;">
<div>
<h2 style="margin: 0; display: flex; align-items: center; gap: 10px;">
<img src="?action=get_image&name=installers-management.png" style="width:64px;height:64px;"> Gestión de Instaladores
</h2>
<p style="color: var(--text-muted); margin: 5px 0 0 0;">👷 Administra tu equipo de técnicos y asigna instalaciones de manera eficiente</p>
</div>
<button class="btn btn-primary" onclick="openInstallerModal()">+ Nuevo Instalador</button>
</div>
<div style="overflow-x: auto;">
<table id="installersTable">
<thead>
<tr>
<th>ID</th>
<th>Nombre</th>
<th>WhatsApp</th>
<th>Acciones</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</section>
<!-- MODULE 2: NOTIFICATIONS -->
<section id="section-notificaciones" class="section-view">
<div class="card">
<div style="margin-bottom: 1.5rem;">
<h2 style="margin: 0; display: flex; align-items: center; gap: 10px;">
<img src="?action=get_image&name=whatsapp-notification.png" style="width:64px;height:64px;"> Notificaciones WhatsApp
</h2>
<p style="color: var(--text-muted); margin: 5px 0 0 0;">📱 Busca clientes y envía comprobantes de pago directamente a su WhatsApp</p>
</div>
<div class="form-group" style="position: relative;">
<label>Buscar Cliente (Nombre, Email o ID)</label>
<div class="search-wrapper">
<svg class="search-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="11" cy="11" r="8" />
<line x1="21" y1="21" x2="16.65" y2="16.65" />
</svg>
<input type="text" id="clientSearch" class="form-control search-input-padded" placeholder="Escribe para buscar (ej. Juan Perez)..." autocomplete="off">
</div>
<div id="searchResults" class="search-results"></div>
</div>
</div>
<div id="paymentsContainer" class="card" style="display: none;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem; flex-wrap: wrap; gap: 10px;">
<h3 id="selectedClientName" style="margin: 0;">Pagos del Cliente</h3>
<div style="display: flex; gap: 8px;">
<a id="btnNotifCrm" href="#" target="_blank" class="btn btn-secondary" style="height: 38px;">Ver en CRM</a>
<button class="btn btn-secondary" onclick="refreshClientPayments()" style="height: 38px;">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M23 4v6h-6" />
<path d="M1 20v-6h6" />
<path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15" />
</svg>
Refrescar Pagos
</button>
</div>
</div>
<div style="overflow-x: auto;">
<table id="paymentsTable">
<thead>
<tr>
<th>ID</th>
<th>Fecha</th>
<th>Monto</th>
<th>Método</th>
<th>Acción</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</section>
<!-- MODULE 3: STRIPE -->
<section id="section-pagos-spei" class="section-view">
<div class="card">
<div style="margin-bottom: 1.5rem;">
<h2 style="margin: 0; display: flex; align-items: center; gap: 10px;">
<img src="?action=get_image&name=online-payments-stripe.png" style="width:64px;height:64px;"> Pagos SPEI
</h2>
<p style="color: var(--text-muted); margin: 5px 0 0 0;">🏦 Genera referencias de transferencia bancaria para que tus clientes paguen vía SPEI</p>
</div>
<label>Buscar Cliente para Stripe</label>
<div class="search-wrapper">
<svg class="search-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="11" cy="11" r="8" />
<line x1="21" y1="21" x2="16.65" y2="16.65" />
</svg>
<input type="text" id="stripeSearch" class="form-control search-input-padded" placeholder="Buscar cliente..." autocomplete="off">
<div id="stripeResults" class="search-results"></div>
</div>
</div>
<div id="stripeDetailContainer" class="card" style="display: none;">
<!-- HEADER: CLIENT INFO & BALANCE -->
<div class="client-header-grid">
<div class="client-info">
<h3 id="stripeClientName">Nombre del Cliente</h3>
<p id="stripeClientIdDisplay" style="color: var(--text-muted);">ID: #0</p>
</div>
<div class="client-balance">
<span class="label">Saldo Actual</span>
<span class="badge" id="stripeBalanceBadge">$0.00</span>
</div>
</div>
<!-- TECHNICAL DETAILS GRID -->
<div class="details-grid">
<div class="detail-item">
<label>Stripe Customer ID</label>
<div class="value-box" id="stripeCustomerIdDisplay">-</div>
</div>
<div class="detail-item">
<label>Clabe Interbancaria</label>
<div class="value-box" id="stripeClabeDisplay">-</div>
</div>
</div>
<!-- PAYMENT INTENT FORM -->
<div>
<h4 class="section-title">Generar Intención de Pago</h4>
<div class="form-grid">
<div class="form-group">
<label>Monto a Cobrar</label>
<div class="input-group">
<span class="input-prefix">$</span>
<input type="number" id="stripeAmount" class="form-control input-with-prefix" placeholder="0.00">
</div>
</div>
<div class="form-group">
<label>Asignar a Administrador</label>
<select id="stripeAdminSelect" class="form-control">
<option value="">-- Automático (Sistema) --</option>
<?php foreach ($admins as $admin): echo "<option value='{$admin['id']}'>{$admin['nombre']}</option>";
endforeach; ?>
</select>
</div>
</div>
<div class="actions-row">
<a id="btnVerEnCrm" href="#" target="_blank" class="btn btn-secondary btn-lg">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path>
<polyline points="15 3 21 3 21 9"></polyline>
<line x1="10" y1="14" x2="21" y2="3"></line>
</svg>
Ver en CRM
</a>
<button id="btnCreateIntent" class="btn btn-primary btn-lg">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<rect x="1" y="4" width="22" height="16" rx="2" ry="2"></rect>
<line x1="1" y1="10" x2="23" y2="10"></line>
</svg>
Generar Referencia SPEI
</button>
</div>
</div>
</div>
</section>
<!-- MODULE 4: OXXO -->
<section id="section-pagos-oxxo" class="section-view">
<div class="card">
<div style="margin-bottom: 1.5rem;">
<h2 style="margin: 0; display: flex; align-items: center; gap: 10px;">
<img src="?action=get_image&name=oxxo-payments.png" style="width:64px;height:64px;"> Pagos OXXO
</h2>
<p style="color: var(--text-muted); margin: 5px 0 0 0;">🏪 Genera fichas de pago OXXO para que tus clientes paguen en tiendas de conveniencia</p>
</div>
<label>Buscar Cliente para OXXO</label>
<div class="search-wrapper">
<svg class="search-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="11" cy="11" r="8" />
<line x1="21" y1="21" x2="16.65" y2="16.65" />
</svg>
<input type="text" id="oxxoSearch" class="form-control search-input-padded" placeholder="Buscar cliente..." autocomplete="off">
<div id="oxxoResults" class="search-results"></div>
</div>
</div>
<div id="oxxoDetailContainer" class="card" style="display: none;">
<div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 1.5rem;">
<div>
<h3 id="oxxoClientName">Nombre</h3>
<p id="oxxoClientIdDisplay" style="color: var(--text-muted);">ID: #0</p>
</div>
<div style="text-align: right; display: flex; flex-direction: column; align-items: flex-end; gap: 8px;">
<span class="badge" id="oxxoBalanceBadge" style="background: #fee2e2; color: #ef4444;">Saldo: $0.00</span>
<a id="btnOxxoCrm" href="#" target="_blank" class="btn btn-secondary" style="padding: 5px 12px; font-size: 0.8rem;">Ver en CRM</a>
</div>
</div>
<div style="max-width: 400px;">
<input type="number" id="oxxoAmount" class="form-control" placeholder="Monto (MXN)" style="margin-bottom: 1rem;">
<button id="btnCreateOxxoIntent" class="btn btn-secondary" style="width: 100%; border-color: #ef4444; color: #ef4444;">
<img src="?action=image&file=oxxo-logo.png" style="height: 20px;"> Generar Ficha OXXO Pay
</button>
</div>
<div id="oxxoInlineResult" style="margin-top: 1.5rem; display: none;"></div>
</div>
</section>
</div>
</div>
<!-- FOOTER -->
<footer style="
margin-top: 80px;
padding: 20px;
text-align: center;
border-top: 2px solid var(--primary);
box-shadow: 0 -2px 10px rgba(0,0,0,0.05);
background: var(--bg-card);
border-radius: 12px 12px 0 0;
">
<p style="margin: 0; font-size: 0.9rem; color: var(--text-main);">
Plugin Desarrollado por <strong>SIIP INTERNET</strong> - Todos los derechos reservados.
</p>
<p style="margin: 5px 0 0 0; font-size: 0.85rem; color: var(--text-muted);">
© <?php echo date('Y'); ?> SIIP Internet. Versión 4.2.1
</p>
</footer>
<!-- MODAL INSTALLER -->
<div class="modal-overlay" id="modalOverlay">
<div class="modal">
<h2 id="modalTitle">Registro de Instalador</h2>
<form id="installerForm">
<input type="hidden" id="editIndex">
<div class="form-group" id="adminSelectGroup">
<label>Seleccionar Administrador UCRM</label>
<select id="adminSelect" class="form-control" onchange="fillInstallerData(this)">
<option value="">-- Seleccionar --</option>
<?php foreach ($admins as $admin): echo "<option value='{$admin['id']}' data-name='{$admin['nombre']}'>{$admin['nombre']}</option>";
endforeach; ?>
</select>
</div>
<input type="number" id="installerId" class="form-control" readonly style="margin: 10px 0" placeholder="ID Usuario">
<input type="text" id="installerName" class="form-control" readonly style="margin: 10px 0" placeholder="Nombre">
<input type="text" id="installerWhatsApp" class="form-control" required style="margin: 10px 0" placeholder="WhatsApp (52...)">
<div style="display:flex; justify-content:flex-end; gap:10px; margin-top:20px;">
<button type="button" class="btn btn-secondary" onclick="document.getElementById('modalOverlay').style.display='none'">Cancelar</button>
<button type="submit" class="btn btn-primary">Guardar</button>
</div>
</form>
</div>
</div>
<!-- STRIPE RESULT MODAL -->
<div id="stripeResultModal" class="modal-overlay" style="z-index: 3500;">
<div class="modal">
<h2>Referencia Generada</h2>
<div id="stripeResultContent"></div>
<div style="text-align: right; margin-top: 20px;">
<button class="btn btn-primary" onclick="document.getElementById('stripeResultModal').style.display='none'">Cerrar</button>
</div>
</div>
</div>
<div id="toast"></div>
<script>
const store = {
installers: <?php echo json_encode($installersData['instaladores']); ?>,
theme: localStorage.getItem('theme') || 'light',
installers: <?php echo json_encode($installersData['instaladores']); ?>,
theme: localStorage.getItem('theme') || 'light',
crmUrl: '<?php echo $ucrmApiUrl; ?>',
publicUrl: '<?php echo $ucrmPublicUrl; ?>',
defaultStripeAdminId: '<?php echo $defaultStripeAdminId; ?>'
};
let currentClientId = null;
// --- THEME LOGIC (Restored) ---
function toggleTheme() {
const next = store.theme === 'light' ? 'dark' : 'light';
store.theme = next;
document.documentElement.setAttribute('data-theme', next);
localStorage.setItem('theme', next);
updateThemeBtn();
}
function updateThemeBtn() {
const btn = document.getElementById('themeBtn');
const text = document.getElementById('themeText');
if (store.theme === 'dark') {
btn.querySelector('.theme-icon').textContent = '🌙';
text.textContent = 'Modo Claro';
} else {
btn.querySelector('.theme-icon').textContent = '☀️';
text.textContent = 'Modo Oscuro';
}
}
document.documentElement.setAttribute('data-theme', store.theme);
updateThemeBtn();
function showDashboard() {
document.getElementById('mainDashboard').style.display = 'grid';
document.getElementById('moduleView').classList.add('hidden');
document.getElementById('btnBackToMenu').classList.add('hidden');
}
function showModule(id) {
document.getElementById('mainDashboard').style.display = 'none';
document.getElementById('moduleView').classList.remove('hidden');
document.getElementById('btnBackToMenu').classList.remove('hidden');
// Map old module IDs to new tab names (support both English and Spanish IDs)
const moduleMap = {
// Spanish IDs
'instaladores': 'instaladores',
'notificaciones': 'notificaciones',
'stripe': 'pagos-spei',
'oxxo': 'pagos-oxxo',
// English IDs (from dashboard menu)
'installers': 'instaladores',
'notifications': 'notificaciones'
};
const tabName = moduleMap[id] || 'instaladores';
switchTab(tabName);
}
function switchTab(tabName) {
// Update tabs visual state
document.querySelectorAll('.tab').forEach(tab => tab.classList.remove('active'));
// Find and activate the clicked tab
const targetTab = Array.from(document.querySelectorAll('.tab')).find(tab => {
return tab.getAttribute('onclick').includes(`'${tabName}'`);
});
if (targetTab) {
targetTab.classList.add('active');
}
// Update sections visibility
document.querySelectorAll('.section-view').forEach(section => section.classList.remove('active'));
const targetSection = document.getElementById(`section-${tabName}`);
if (targetSection) {
targetSection.classList.add('active');
}
// Initialize module if needed
if (tabName === 'notificaciones' && !window.notificacionesInitialized) {
// Load clients for notifications module
loadClients();
window.notificacionesInitialized = true;
}
}
function showToast(msg, err = false) {
const t = document.getElementById('toast');
t.textContent = msg;
t.style.background = err ? '#ef4444' : '#333';
t.classList.add('show');
setTimeout(() => t.classList.remove('show'), 3000);
}
// --- SEARCH LOGIC (UNIFIED) ---
function highlightMatch(text, query) {
if (!query) return text;
const regex = new RegExp(`(${query})`, 'gi');
return text.replace(regex, '<span class="highlight">$1</span>');
}
function renderRichSearchResults(container, data, query, callback) {
container.innerHTML = '';
// Error Handling Display
if (data.error) {
container.innerHTML = `<div class="search-item" style="color:red">Error: ${data.error}</div>`;
container.style.display = 'block';
return;
}
if (!Array.isArray(data) || data.length === 0) {
container.innerHTML = '<div class="search-item">No se encontraron resultados</div>';
container.style.display = 'block';
return;
}
// Limit results to 8 for performance
data.slice(0, 8).forEach(client => {
const isSuspended = client.isSuspended || false;
const name = client.clientType === 2 ? client.companyName : `${client.firstName} ${client.lastName}`;
const address = client.fullAddress || client.street1 || (client.city ? `(${client.city})` : '');
let email = client.email || '';
let phone = '';
if (client.contacts && Array.isArray(client.contacts) && client.contacts.length > 0) {
email = client.contacts[0].email || email;
phone = client.contacts[0].phone || '';
}
const item = document.createElement('div');
item.className = 'search-item';
item.innerHTML = `
<div class="status-dot ${isSuspended ? 'suspended' : 'active'}"></div>
<div class="client-info">
<div class="client-header">
<span class="client-name">${highlightMatch(name, query)}</span>
${isSuspended ? '<span class="badge-suspended">SUSPENDIDO</span>' : ''}
</div>
<div class="client-details">
ID: ${client.id} · ${email} ${phone ? '· '+phone : ''} <br>
${address}
</div>
</div>
`;
item.onclick = () => {
container.style.display = 'none';
callback(client);
};
container.appendChild(item);
});
container.style.display = 'block';
}
function setupSearch(inputId, resultId, action, onSelect) {
console.log(`[DEBUG] setupSearch initialized for ${inputId}`);
const input = document.getElementById(inputId);
const results = document.getElementById(resultId);
let timeout;
if (!input) console.error(`[DEBUG] Input ${inputId} NOT FOUND`);
if (!results) console.error(`[DEBUG] Results ${resultId} NOT FOUND`);
input.oninput = (e) => {
const q = e.target.value.trim();
console.log(`[DEBUG] oninput: '${q}'`);
clearTimeout(timeout);
if (q.length < 2) {
results.style.display = 'none';
return;
}
timeout = setTimeout(async () => {
console.log(`[DEBUG] Fetching ${action} with q=${q}`);
try {
const res = await fetch(`?action=${action}&q=${encodeURIComponent(q)}`);
console.log(`[DEBUG] Response Status: ${res.status}`);
if (!res.ok) throw new Error(`Server Error: ${res.status}`);
const data = await res.json();
console.log(`[DEBUG] Data Received:`, data);
renderRichSearchResults(results, data, q, (client) => {
input.value = '';
onSelect(client);
});
} catch (e) {
console.error('[DEBUG] Fetch Error:', e);
renderRichSearchResults(results, {
error: e.message
}, q, null);
}
}, 300);
};
document.addEventListener('click', e => {
if (!input.contains(e.target) && !results.contains(e.target)) results.style.display = 'none';
});
}
// 1. NOTIFICATIONS SEARCH
setupSearch('clientSearch', 'searchResults', 'search_clients', (client) => {
currentClientId = client.id;
const name = client.clientType === 2 ? client.companyName : `${client.firstName} ${client.lastName}`;
document.getElementById('selectedClientName').textContent = `Pagos de ${name}`;
document.getElementById('btnNotifCrm').href = `${store.publicUrl}/client/${client.id}`;
document.getElementById('paymentsContainer').style.display = 'block';
loadPayments(client.id);
});
async function loadPayments(id) {
const tbody = document.querySelector('#paymentsTable tbody');
tbody.innerHTML = '<tr><td colspan="5" style="text-align:center">Cargando...</td></tr>';
try {
const res = await fetch(`?action=get_payments&clientId=${id}`);
const payments = await res.json();
if (payments.length === 0) tbody.innerHTML = '<tr><td colspan="5" style="text-align:center">Sin pagos recientes</td></tr>';
else {
tbody.innerHTML = payments.map(p => `
<tr>
<td>#${p.id}</td>
<td>${new Date(p.createdDate).toLocaleString()}</td>
<td>$${p.amount} ${p.currencyCode}</td>
<td>${p.methodName}</td>
<td><button class="btn btn-whatsapp" onclick="resendPayment(${p.id})">Re-enviar</button></td>
</tr>
`).join('');
}
} catch (e) {
tbody.innerHTML = '<tr><td colspan="5">Error</td></tr>';
}
}
function refreshClientPayments() {
if (currentClientId) loadPayments(currentClientId);
else showToast("Busca un cliente primero", true);
}
async function resendPayment(id) {
if (!confirm('¿Re-enviar notificación?')) return;
const fd = new FormData();
fd.append('action', 'resend_payment');
fd.append('paymentId', id);
const res = await fetch('?', {
method: 'POST',
body: fd
});
const d = await res.json();
showToast(d.message, !d.success);
}
// 2. STRIPE SEARCH
let selectedStripeClient = null;
setupSearch('stripeSearch', 'stripeResults', 'search_stripe', async (partialClient) => {
const res = await fetch(`?action=get_stripe_details&id=${partialClient.id}`);
const data = await res.json();
selectedStripeClient = data;
document.getElementById('stripeClientName').textContent = data.fullName;
document.getElementById('stripeClientIdDisplay').textContent = `ID: #${data.id}`;
document.getElementById('stripeBalanceBadge').textContent = `Saldo: $${parseFloat(data.accountOutstanding||0).toFixed(2)}`;
document.getElementById('stripeCustomerIdDisplay').textContent = data.stripeCustomerId || 'No disponible';
document.getElementById('stripeClabeDisplay').textContent = data.clabeInterbancaria || 'No disponible';
document.getElementById('stripeAmount').value = data.accountOutstanding > 0 ? data.accountOutstanding : '';
document.getElementById('btnVerEnCrm').href = `${store.publicUrl}/client/${data.id}`;
document.getElementById('stripeDetailContainer').style.display = 'block';
});
document.getElementById('btnCreateIntent').onclick = async () => {
if (!selectedStripeClient?.stripeCustomerId) return showToast('Error: Cliente sin Stripe ID', true);
const amt = parseFloat(document.getElementById('stripeAmount').value);
if (!amt || amt < 10) return showToast('Mínimo 10 MXN', true);
const btn = document.getElementById('btnCreateIntent');
btn.disabled = true;
btn.textContent = 'Procesando...';
const fd = new FormData();
fd.append('action', 'create_intent');
fd.append('clientId', selectedStripeClient.id);
fd.append('amount', amt);
fd.append('stripeCustomerId', selectedStripeClient.stripeCustomerId);
fd.append('adminId', document.getElementById('stripeAdminSelect').value || store.defaultStripeAdminId);
try {
const res = await fetch('?', {
method: 'POST',
body: fd
});
const d = await res.json();
if (d.success) showStripeResult(d);
else showToast(d.error, true);
} catch (e) {
showToast('Error de conexión', true);
}
btn.disabled = false;
btn.textContent = 'Generar Referencia SPEI';
};
function showStripeResult(data) {
const c = document.getElementById('stripeResultContent');
c.innerHTML = `<h3 style="color:var(--success);text-align:center">¡Referencia Creada!</h3><p style="text-align:center">Monto: $${data.amount}</p>`;
if (data.next_action?.display_bank_transfer_instructions) {
const i = data.next_action.display_bank_transfer_instructions.financial_addresses[0].spei;
c.innerHTML += `<div style="background:#f1f5f9;padding:15px;border-radius:8px;margin-top:10px"><p><strong>Banco:</strong> ${i.bank_name}</p><p><strong>CLABE:</strong> ${i.clabe}</p></div>`;
}
document.getElementById('stripeResultModal').style.display = 'flex';
}
// 3. OXXO SEARCH
let selectedOxxoClient = null;
setupSearch('oxxoSearch', 'oxxoResults', 'search_stripe', async (partialClient) => {
const res = await fetch(`?action=get_stripe_details&id=${partialClient.id}`);
const data = await res.json();
selectedOxxoClient = data;
document.getElementById('oxxoClientName').textContent = data.fullName;
document.getElementById('oxxoClientIdDisplay').textContent = `ID: #${data.id}`;
document.getElementById('oxxoBalanceBadge').textContent = `Saldo: $${parseFloat(data.accountOutstanding||0).toFixed(2)}`;
document.getElementById('oxxoAmount').value = data.accountOutstanding > 0 ? data.accountOutstanding : '';
document.getElementById('btnOxxoCrm').href = `${store.publicUrl}/client/${data.id}`;
document.getElementById('oxxoDetailContainer').style.display = 'block';
});
document.getElementById('btnCreateOxxoIntent').onclick = async () => {
if (!selectedOxxoClient) return;
const amt = parseFloat(document.getElementById('oxxoAmount').value);
if (!amt || amt < 10) return showToast('Mínimo 10 MXN', true);
const btn = document.getElementById('btnCreateOxxoIntent');
const original = btn.innerHTML;
btn.disabled = true;
btn.textContent = 'Procesando...';
const fd = new FormData();
fd.append('action', 'create_oxxo_intent');
fd.append('clientId', selectedOxxoClient.id);
fd.append('amount', amt);
try {
const res = await fetch('?', {
method: 'POST',
body: fd
});
const d = await res.json();
if (d.success) {
const url = d.data.voucher_image_url || `?action=image&file=${d.data.voucher_filename}`;
const resDiv = document.getElementById('oxxoInlineResult');
resDiv.style.display = 'block';
resDiv.innerHTML = `<div class="card" style="text-align:center;border:1px solid #22c55e;"><h3 style="color:#15803d">¡Ficha Generada!</h3><p style="font-size:1.5rem;font-weight:bold">${d.data.oxxo_reference}</p><img src="${url}" style="max-width:100%; height:auto; margin:10px 0; border:1px solid #eee; border-radius:8px;"><br><a href="${url}" target="_blank" class="btn btn-primary">Descargar Ficha</a></div>`;
} else showToast(d.error, true);
} catch (e) {
showToast('Error conexión', true);
}
btn.disabled = false;
btn.innerHTML = original;
};
// --- INSTALLER MODAL LOGIC ---
function renderTable() {
const tbody = document.querySelector('#installersTable tbody');
tbody.innerHTML = store.installers.map((inst, i) => `<tr><td>#${inst.id}</td><td>${inst.nombre}</td><td>${inst.whatsapp}</td><td><button class="btn btn-secondary" onclick="editInstaller(${i})">✎</button> <button class="btn btn-secondary" style="color:red" onclick="deleteInstaller(${i})">🗑</button></td></tr>`).join('');
}
renderTable();
function openInstallerModal() {
document.getElementById('modalOverlay').style.display = 'flex';
document.getElementById('installerForm').reset();
document.getElementById('editIndex').value = '';
}
function fillInstallerData(sel) {
document.getElementById('installerId').value = sel.value;
document.getElementById('installerName').value = sel.options[sel.selectedIndex].getAttribute('data-name');
}
document.getElementById('installerForm').onsubmit = async (e) => {
e.preventDefault();
const id = document.getElementById('installerId').value;
const name = document.getElementById('installerName').value;
const wa = document.getElementById('installerWhatsApp').value;
const idx = document.getElementById('editIndex').value;
if (idx !== '') store.installers[idx] = {
id,
nombre: name,
whatsapp: wa
};
else store.installers.push({
id,
nombre: name,
whatsapp: wa
});
const fd = new FormData();
fd.append('action', 'save_installers');
fd.append('installers_data', JSON.stringify({
instaladores: store.installers
}));
await fetch('?action=save_installers', {
method: 'POST',
body: fd
});
renderTable();
document.getElementById('modalOverlay').style.display = 'none';
};
</script>
</body>
</html>