<?php
require_once __DIR__ . '/includes/header.php';

/* =======================
   SECURITY
======================= */
if (!isset($_SESSION['loggedin'], $_SESSION['name'], $_SESSION['role'])) {
    header("Location: index.php");
    exit;
}

$currentUser = $_SESSION['name']; // Nombre de usuario actual (ej: "admin")
$role = $_SESSION['role'];

if ($role !== 'master') {
    die('❌ Acceso denegado. Solo el Master puede gestionar trials.');
}

/* =======================
   CSRF
======================= */
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_token'];

/* =======================
   PATHS
======================= */
$jsonFile = __DIR__ . '/api/trial_cadastros.json';
$dbFile   = __DIR__ . '/api/.db.db';

/* =======================
   HELPERS
======================= */
function h($s): string { 
    return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); 
}

function only_digits(string $s): string {
    $r = preg_replace('/\D+/', '', $s);
    return $r ?: '';
}

function fmt_phone(string $digits): string {
    $d = only_digits($digits);
    if (strlen($d) >= 11) {
        $dd = substr($d, 0, 2);
        $p1 = substr($d, 2, 5);
        $p2 = substr($d, 7, 4);
        return "($dd) $p1-$p2";
    }
    if (strlen($d) === 10) {
        $dd = substr($d, 0, 2);
        $p1 = substr($d, 2, 4);
        $p2 = substr($d, 6, 4);
        return "($dd) $p1-$p2";
    }
    return $digits;
}

function make_row_id(array $row): string {
    $phone = (string)($row['phone'] ?? '');
    $ip = (string)($row['ip'] ?? '');
    $code = (string)($row['code'] ?? '');
    $cts  = (string)($row['created_ts'] ?? $row['created_at'] ?? '');
    return sha1($phone . '|' . $ip . '|' . $code . '|' . $cts);
}

function load_json_list(string $file): array {
    $fp = @fopen($file, 'c+');
    if (!$fp) return [];
    flock($fp, LOCK_SH);
    $size = filesize($file);
    $raw = $size > 0 ? fread($fp, $size) : '';
    flock($fp, LOCK_UN);
    fclose($fp);

    if (!$raw) return [];
    $data = json_decode($raw, true);
    return is_array($data) ? $data : [];
}

function save_json_list(string $file, array $list): bool {
    $fp = @fopen($file, 'c+');
    if (!$fp) return false;
    if (!flock($fp, LOCK_EX)) {
        fclose($fp);
        return false;
    }

    rewind($fp);
    ftruncate($fp, 0);

    $json = json_encode($list, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    $ok = ($json !== false) && (fwrite($fp, $json) !== false);

    fflush($fp);
    flock($fp, LOCK_UN);
    fclose($fp);
    return $ok;
}

function open_db(string $dbFile): ?PDO {
    if (!file_exists($dbFile)) return null;
    try {
        $pdo = new PDO('sqlite:' . $dbFile);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        // Asegurar que la tabla codes tiene todas las columnas necesarias
        $pdo->exec("CREATE TABLE IF NOT EXISTS codes (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            code TEXT NOT NULL,
            expires_at TEXT NOT NULL,
            owner TEXT NOT NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            client_name TEXT,
            client_whatsapp TEXT,
            status TEXT DEFAULT 'active'
        )");
        
        return $pdo;
    } catch (Throwable $e) {
        return null;
    }
}

function get_resellers(PDO $pdo): array {
    try {
        $stmt = $pdo->query("SELECT username, role FROM menualuser WHERE role IN ('super-reseller', 'reseller') ORDER BY username");
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $e) {
        return [];
    }
}

/* =======================
   ACTIONS
======================= */
$msgOk = '';
$msgErr = '';

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
    $token = (string)($_POST['csrf'] ?? '');
    if (!hash_equals($_SESSION['csrf_token'], $token)) {
        $msgErr = '❌ CSRF inválido. Recarregue a página.';
    } else {
        $action = (string)($_POST['action'] ?? '');
        $pdo = open_db($dbFile);

        if (!$pdo) {
            $msgErr = '❌ No se pudo conectar a la base de datos.';
        } else {
            $list = load_json_list($jsonFile);

            // ============================================
            // CONVERTIR TRIAL A CLIENTE
            // ============================================
            if ($action === 'convert_to_client') {
                $trialId = (string)($_POST['trial_id'] ?? '');
                $months = (int)($_POST['months'] ?? 1);
                $resellerInput = (string)($_POST['reseller'] ?? '');
                $clientName = trim((string)($_POST['client_name'] ?? ''));
                $clientWhatsapp = only_digits((string)($_POST['client_whatsapp'] ?? ''));

                // Si el reseller es "master", usar el nombre de usuario actual del master
                $reseller = ($resellerInput === 'master') ? $currentUser : $resellerInput;

                if ($months < 1 || $months > 12) {
                    $msgErr = '❌ Los meses deben estar entre 1 y 12.';
                } elseif (empty($clientName)) {
                    $msgErr = '❌ El nombre del cliente es obligatorio.';
                } elseif (strlen($clientWhatsapp) < 10) {
                    $msgErr = '❌ El WhatsApp debe tener al menos 10 dígitos.';
                } else {
                    // Buscar el trial en el JSON
                    $trialData = null;
                    $trialIndex = -1;
                    
                    foreach ($list as $idx => $row) {
                        if (!is_array($row)) continue;
                        $rid = make_row_id($row);
                        if ($rid === $trialId) {
                            $trialData = $row;
                            $trialIndex = $idx;
                            break;
                        }
                    }

                    if (!$trialData) {
                        $msgErr = '❌ Trial no encontrado.';
                    } else {
                        $oldCode = (string)($trialData['code'] ?? '');
                        
                        // Calcular nueva fecha de expiración
                        $newExpiry = date('Y-m-d H:i:s', strtotime("+{$months} months"));
                        
                        try {
                            $pdo->beginTransaction();
                            
                            // 1. Actualizar el código existente en la tabla codes
                            $stmt = $pdo->prepare("
                                UPDATE codes 
                                SET owner = :owner,
                                    expires_at = :expires,
                                    client_name = :name,
                                    client_whatsapp = :whatsapp,
                                    status = 'active'
                                WHERE code = :code AND owner = 'trial'
                            ");
                            
                            $updated = $stmt->execute([
                                ':owner' => $reseller,
                                ':expires' => $newExpiry,
                                ':name' => $clientName,
                                ':whatsapp' => $clientWhatsapp,
                                ':code' => $oldCode
                            ]);

                            if (!$updated || $stmt->rowCount() === 0) {
                                throw new Exception('No se pudo actualizar el código en la base de datos.');
                            }

                            // 2. Eliminar del JSON de trials
                            array_splice($list, $trialIndex, 1);
                            
                            if (!save_json_list($jsonFile, $list)) {
                                throw new Exception('No se pudo actualizar el archivo JSON.');
                            }

                            $pdo->commit();
                            
                            $msgOk = "✅ Trial convertido exitosamente a cliente!<br>" .
                                    "📋 Código: <strong>{$oldCode}</strong><br>" .
                                    "👤 Cliente: <strong>{$clientName}</strong><br>" .
                                    "📅 Válido por: <strong>{$months} mes(es)</strong><br>" .
                                    "🏢 Asignado a: <strong>{$reseller}</strong>";
                            
                        } catch (Throwable $e) {
                            $pdo->rollBack();
                            $msgErr = '❌ Error al convertir: ' . $e->getMessage();
                        }
                    }
                }
            }
            
            // ============================================
            // ELIMINAR TRIAL
            // ============================================
            elseif ($action === 'delete_trial') {
                $trialId = (string)($_POST['trial_id'] ?? '');
                
                $trialIndex = -1;
                $trialCode = null;
                
                foreach ($list as $idx => $row) {
                    if (!is_array($row)) continue;
                    $rid = make_row_id($row);
                    if ($rid === $trialId) {
                        $trialCode = (string)($row['code'] ?? '');
                        $trialIndex = $idx;
                        break;
                    }
                }

                if ($trialIndex === -1) {
                    $msgErr = '❌ Trial no encontrado.';
                } else {
                    try {
                        // Eliminar del JSON
                        array_splice($list, $trialIndex, 1);
                        
                        if (!save_json_list($jsonFile, $list)) {
                            throw new Exception('No se pudo actualizar el archivo JSON.');
                        }

                        // Eliminar de la base de datos
                        if ($trialCode) {
                            $stmt = $pdo->prepare("DELETE FROM codes WHERE code = :code AND owner = 'trial'");
                            $stmt->execute([':code' => $trialCode]);
                        }

                        $msgOk = '✅ Trial eliminado exitosamente.';
                        
                    } catch (Throwable $e) {
                        $msgErr = '❌ Error al eliminar: ' . $e->getMessage();
                    }
                }
            }
            
            // ============================================
            // ELIMINAR EXPIRADOS
            // ============================================
            elseif ($action === 'delete_expired') {
                $now = time();
                $newList = [];
                $deletedCodes = [];
                $deletedCount = 0;

                foreach ($list as $row) {
                    if (!is_array($row)) continue;
                    $exp = (string)($row['expires_at'] ?? '');
                    $expTs = strtotime($exp);
                    
                    if ($expTs && $expTs < $now) {
                        $deletedCount++;
                        if (!empty($row['code'])) {
                            $deletedCodes[] = (string)$row['code'];
                        }
                        continue;
                    }
                    $newList[] = $row;
                }

                if ($deletedCount === 0) {
                    $msgErr = 'ℹ️ No hay trials expirados para eliminar.';
                } else {
                    if (!save_json_list($jsonFile, $newList)) {
                        $msgErr = '❌ Error al guardar el archivo JSON.';
                    } else {
                        // Eliminar códigos de la base de datos
                        if ($deletedCodes) {
                            $placeholders = implode(',', array_fill(0, count($deletedCodes), '?'));
                            $stmt = $pdo->prepare("DELETE FROM codes WHERE owner='trial' AND code IN ($placeholders)");
                            $stmt->execute($deletedCodes);
                        }
                        
                        $msgOk = "✅ Se eliminaron {$deletedCount} trial(s) expirado(s).";
                    }
                }
            }
            
            // ============================================
            // ELIMINAR TODOS
            // ============================================
            elseif ($action === 'delete_all') {
                if (!save_json_list($jsonFile, [])) {
                    $msgErr = '❌ Error al limpiar el archivo JSON.';
                } else {
                    $pdo->exec("DELETE FROM codes WHERE owner='trial'");
                    $msgOk = '✅ Todos los trials fueron eliminados.';
                }
            }
        }
    }
}

/* =======================
   LOAD DATA
======================= */
$pdo = open_db($dbFile);
$resellers = $pdo ? get_resellers($pdo) : [];
$list = load_json_list($jsonFile);

if (!is_array($list)) $list = [];

// Ordenar por fecha de creación (más reciente primero)
usort($list, function($a, $b){
    $ta = is_array($a) ? (int)($a['created_ts'] ?? 0) : 0;
    $tb = is_array($b) ? (int)($b['created_ts'] ?? 0) : 0;
    return $tb <=> $ta;
});

// Filtros
$q = trim((string)($_GET['q'] ?? ''));
$filterStatus = (string)($_GET['status'] ?? '');

$filtered = [];
$now = time();

foreach ($list as $row) {
    if (!is_array($row)) continue;

    $name  = (string)($row['name'] ?? '');
    $phone = (string)($row['phone'] ?? '');
    $code  = (string)($row['code'] ?? '');
    $exp   = (string)($row['expires_at'] ?? '');
    $expTs = strtotime($exp);
    
    $isExpired = ($expTs && $expTs < $now);
    $isActive = !$isExpired;

    // Filtro por estado
    if ($filterStatus === 'active' && !$isActive) continue;
    if ($filterStatus === 'expired' && !$isExpired) continue;

    // Filtro por búsqueda
    if ($q !== '') {
        $qDigits = only_digits($q);
        $hay = mb_strtolower($name . ' ' . $phone . ' ' . $code);
        
        $match = false;
        if ($qDigits !== '' && strpos(only_digits($phone), $qDigits) !== false) {
            $match = true;
        }
        if (!$match && strpos($hay, mb_strtolower($q)) !== false) {
            $match = true;
        }
        
        if (!$match) continue;
    }

    $filtered[] = $row;
}

// Estadísticas
$total = count($list);
$active = 0;
$expired = 0;

foreach ($list as $row) {
    if (!is_array($row)) continue;
    $expTs = strtotime((string)($row['expires_at'] ?? ''));
    if ($expTs && $expTs >= $now) {
        $active++;
    } else {
        $expired++;
    }
}
?>

<div class="col-md-12 mx-auto">
    <div class="card text-white" style="background:#1a1a1a;">
        <div class="card-header d-flex align-items-center justify-content-between flex-wrap">
            <div>
                <h3 class="mb-0">
                    <i class="fa fa-user-clock"></i> GESTIÓN DE TRIALS
                </h3>
                <small>Convierte trials en clientes o elimínalos</small>
            </div>
            <div class="mt-2 mt-md-0">
                <a href="config_teste.php" class="btn btn-sm btn-outline-info">
                    <i class="fa fa-cog"></i> Configurar Trials
                </a>
            </div>
        </div>

        <div class="card-body">
            <?php if ($msgOk): ?>
                <div class="alert alert-success alert-dismissible fade show">
                    <?=$msgOk?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <?php if ($msgErr): ?>
                <div class="alert alert-danger alert-dismissible fade show">
                    <?=$msgErr?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <!-- Estadísticas -->
            <div class="row mb-4">
                <div class="col-md-4">
                    <div class="card bg-dark border-info">
                        <div class="card-body text-center">
                            <h3 class="text-info mb-0"><?=$total?></h3>
                            <small class="text-muted">Total Trials</small>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card bg-dark border-success">
                        <div class="card-body text-center">
                            <h3 class="text-success mb-0"><?=$active?></h3>
                            <small class="text-muted">Activos</small>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card bg-dark border-danger">
                        <div class="card-body text-center">
                            <h3 class="text-danger mb-0"><?=$expired?></h3>
                            <small class="text-muted">Expirados</small>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Acciones masivas -->
            <div class="alert alert-dark border-secondary">
                <div class="d-flex flex-wrap gap-3 justify-content-between align-items-center">
                    <div>
                        <strong>Acciones masivas:</strong>
                    </div>
                    <div class="d-flex gap-2 flex-wrap">
                        <form method="post" onsubmit="return confirm('¿Eliminar TODOS los trials expirados?');" class="m-0">
                            <input type="hidden" name="csrf" value="<?=h($csrf)?>">
                            <input type="hidden" name="action" value="delete_expired">
                            <button class="btn btn-sm btn-outline-warning">
                                <i class="fa fa-trash"></i> Eliminar Expirados (<?=$expired?>)
                            </button>
                        </form>

                        <form method="post" onsubmit="return confirm('⚠️ ADVERTENCIA: Esto eliminará TODOS los trials. ¿Continuar?');" class="m-0">
                            <input type="hidden" name="csrf" value="<?=h($csrf)?>">
                            <input type="hidden" name="action" value="delete_all">
                            <button class="btn btn-sm btn-outline-danger">
                                <i class="fa fa-times-circle"></i> Eliminar Todos
                            </button>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Filtros -->
            <form method="get" class="mb-3">
                <div class="row g-2">
                    <div class="col-md-8">
                        <input type="text" name="q" class="form-control" 
                               placeholder="🔍 Buscar por nombre, teléfono o código..."
                               value="<?=h($q)?>">
                    </div>
                    <div class="col-md-2">
                        <select name="status" class="form-control">
                            <option value="">Todos</option>
                            <option value="active" <?=$filterStatus==='active'?'selected':''?>>Activos</option>
                            <option value="expired" <?=$filterStatus==='expired'?'selected':''?>>Expirados</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <button class="btn btn-info w-100" type="submit">
                            <i class="fa fa-search"></i> Buscar
                        </button>
                    </div>
                </div>
            </form>

            <!-- Tabla de trials -->
            <div class="table-responsive">
                <table class="table table-dark table-hover">
                    <thead>
                        <tr>
                            <th><i class="fa fa-user"></i> Cliente</th>
                            <th><i class="fa fa-phone"></i> Teléfono</th>
                            <th><i class="fa fa-key"></i> Código</th>
                            <th><i class="fa fa-calendar"></i> Expira</th>
                            <th><i class="fa fa-info-circle"></i> Estado</th>
                            <th><i class="fa fa-cog"></i> Acciones</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php if (!$filtered): ?>
                        <tr>
                            <td colspan="6" class="text-center py-5">
                                <i class="fa fa-inbox fa-3x text-muted mb-3"></i>
                                <p class="text-muted">No hay trials para mostrar</p>
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($filtered as $row): 
                            $id = make_row_id($row);
                            $name = (string)($row['name'] ?? 'Sin nombre');
                            $phone = (string)($row['phone'] ?? '');
                            $phoneFormatted = fmt_phone($phone);
                            $code = (string)($row['code'] ?? '-');
                            $created = (string)($row['created_at'] ?? '-');
                            $exp = (string)($row['expires_at'] ?? '-');
                            $expTs = strtotime($exp);
                            $isExpired = ($expTs && $expTs < $now);
                            
                            $daysLeft = 0;
                            if ($expTs) {
                                $daysLeft = floor(($expTs - $now) / 86400);
                            }
                        ?>
                        <tr>
                            <td>
                                <strong><?=h($name)?></strong><br>
                                <small class="text-muted">
                                    <i class="fa fa-clock"></i> <?=h($created)?>
                                </small>
                            </td>
                            <td>
                                <?php if ($phone): ?>
                                    <a href="https://wa.me/<?=h($phone)?>" target="_blank" class="text-success">
                                        <i class="fab fa-whatsapp"></i> <?=h($phoneFormatted)?>
                                    </a>
                                <?php else: ?>
                                    <span class="text-muted">Sin teléfono</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <span class="badge bg-info"><?=h($code)?></span>
                            </td>
                            <td>
                                <?=h($exp)?><br>
                                <?php if ($isExpired): ?>
                                    <span class="badge bg-danger">
                                        <i class="fa fa-times-circle"></i> Expirado
                                    </span>
                                <?php else: ?>
                                    <?php if ($daysLeft > 0): ?>
                                        <span class="badge bg-success">
                                            <i class="fa fa-check-circle"></i> <?=$daysLeft?> día(s)
                                        </span>
                                    <?php else: ?>
                                        <span class="badge bg-warning">
                                            <i class="fa fa-clock"></i> Hoy
                                        </span>
                                    <?php endif; ?>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($isExpired): ?>
                                    <span class="badge bg-danger">Expirado</span>
                                <?php else: ?>
                                    <span class="badge bg-success">Activo</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="btn-group" role="group">
                                    <!-- Convertir a Cliente -->
                                    <button class="btn btn-sm btn-success" 
                                            onclick="showConvertModal('<?=h($id)?>', '<?=h($name)?>', '<?=h($phone)?>', '<?=h($code)?>')"
                                            title="Convertir a cliente">
                                        <i class="fa fa-user-plus"></i>
                                    </button>
                                    
                                    <!-- Eliminar -->
                                    <form method="post" class="d-inline" 
                                          onsubmit="return confirm('¿Eliminar este trial?');">
                                        <input type="hidden" name="csrf" value="<?=h($csrf)?>">
                                        <input type="hidden" name="action" value="delete_trial">
                                        <input type="hidden" name="trial_id" value="<?=h($id)?>">
                                        <button class="btn btn-sm btn-danger" title="Eliminar">
                                            <i class="fa fa-trash"></i>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <?php if ($filtered): ?>
            <div class="text-muted small mt-3">
                <i class="fa fa-info-circle"></i> 
                Mostrando <?=count($filtered)?> de <?=$total?> trial(s).
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Modal para convertir trial a cliente -->
<div class="modal fade" id="convertModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content bg-dark text-white">
            <form method="post" id="convertForm">
                <input type="hidden" name="csrf" value="<?=h($csrf)?>">
                <input type="hidden" name="action" value="convert_to_client">
                <input type="hidden" name="trial_id" id="modal_trial_id">
                
                <div class="modal-header border-secondary">
                    <h5 class="modal-title">
                        <i class="fa fa-user-plus"></i> Convertir Trial a Cliente
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                
                <div class="modal-body">
                    <div class="alert alert-info">
                        <i class="fa fa-info-circle"></i>
                        <strong>Código actual:</strong> <span id="modal_code">-</span>
                    </div>

                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">
                                <i class="fa fa-user"></i> Nombre del Cliente *
                            </label>
                            <input type="text" name="client_name" id="modal_name" 
                                   class="form-control" required minlength="2" maxlength="100">
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">
                                <i class="fa fa-phone"></i> WhatsApp *
                            </label>
                            <input type="tel" name="client_whatsapp" id="modal_phone" 
                                   class="form-control" required minlength="10" maxlength="20"
                                   placeholder="11999999999">
                            <small class="text-muted">Solo números</small>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">
                                <i class="fa fa-calendar"></i> Plan (Meses) *
                            </label>
                            <select name="months" class="form-control" required>
                                <option value="1">1 mes</option>
                                <option value="2">2 meses</option>
                                <option value="3" selected>3 meses</option>
                                <option value="6">6 meses</option>
                                <option value="12">12 meses (1 año)</option>
                            </select>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">
                                <i class="fa fa-user-tie"></i> Asignar a Reseller *
                            </label>
                            <select name="reseller" class="form-control" required>
                                <option value="master">Master (<?=h($currentUser)?>)</option>
                                <?php foreach ($resellers as $r): ?>
                                    <option value="<?=h($r['username'])?>">
                                        <?=h($r['username'])?> (<?=h($r['role'])?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="alert alert-warning mt-3">
                        <i class="fa fa-exclamation-triangle"></i>
                        <strong>Importante:</strong> El código trial se convertirá en un código de cliente permanente.
                        El trial será eliminado de la lista de pruebas.
                    </div>
                </div>
                
                <div class="modal-footer border-secondary">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fa fa-times"></i> Cancelar
                    </button>
                    <button type="submit" class="btn btn-success">
                        <i class="fa fa-check"></i> Convertir a Cliente
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function showConvertModal(trialId, name, phone, code) {
    document.getElementById('modal_trial_id').value = trialId;
    document.getElementById('modal_name').value = name;
    document.getElementById('modal_phone').value = phone;
    document.getElementById('modal_code').textContent = code;
    
    const modal = new bootstrap.Modal(document.getElementById('convertModal'));
    modal.show();
}

// Validación del formulario
document.getElementById('convertForm').addEventListener('submit', function(e) {
    const name = document.getElementById('modal_name').value.trim();
    const phone = document.getElementById('modal_phone').value.replace(/\D/g, '');
    
    if (name.length < 2) {
        e.preventDefault();
        alert('El nombre debe tener al menos 2 caracteres.');
        return false;
    }
    
    if (phone.length < 10) {
        e.preventDefault();
        alert('El WhatsApp debe tener al menos 10 dígitos.');
        return false;
    }
    
    return confirm('¿Confirmar la conversión de este trial a cliente?');
});

// Auto-cerrar alertas después de 5 segundos
setTimeout(function() {
    const alerts = document.querySelectorAll('.alert-dismissible');
    alerts.forEach(function(alert) {
        const bsAlert = new bootstrap.Alert(alert);
        bsAlert.close();
    });
}, 5000);
</script>

<style>
.btn-group {
    display: flex;
    gap: 2px;
}

.btn-group .btn {
    border-radius: 4px !important;
}

.table-hover tbody tr:hover {
    background-color: rgba(255, 255, 255, 0.05);
}

.modal-content {
    border: 1px solid rgba(255, 255, 255, 0.1);
}

.form-control:focus {
    background-color: rgba(255, 255, 255, 0.1);
    border-color: #0d6efd;
    color: white;
}

.form-control {
    background-color: rgba(255, 255, 255, 0.05);
    border-color: rgba(255, 255, 255, 0.2);
    color: white;
}

.form-control::placeholder {
    color: rgba(255, 255, 255, 0.4);
}

@media (max-width: 768px) {
    .btn-group {
        flex-direction: column;
    }
    
    .table-responsive {
        font-size: 0.85rem;
    }
}
</style>

<?php require_once __DIR__ . '/includes/footer.php'; ?>