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

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

$currentUser = $_SESSION['name'];
$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
======================= */
$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 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);
        $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        
        // Crear tabla codes si no existe
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS codes (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                code TEXT UNIQUE 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'
            )
        ");
        
        // Crear tabla trialspublic (exclusiva para trials públicos)
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS trialspublic (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                phone TEXT NOT NULL,
                ip TEXT NOT NULL,
                name TEXT NOT NULL,
                code TEXT NOT NULL UNIQUE,
                created_ts INTEGER NOT NULL,
                expires_at TEXT NOT NULL,
                block_until_ts INTEGER DEFAULT 0,
                converted INTEGER DEFAULT 0,
                converted_at DATETIME,
                converted_to_owner TEXT
            )
        ");
        
        // Crear índices
        $pdo->exec("CREATE INDEX IF NOT EXISTS idx_trialspublic_code ON trialspublic(code)");
        $pdo->exec("CREATE INDEX IF NOT EXISTS idx_trialspublic_converted ON trialspublic(converted)");
        
        return $pdo;
    } catch (Throwable $e) {
        error_log("DB Error: " . $e->getMessage());
        return null;
    }
}

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

function get_trials_from_db(PDO $pdo): array {
    try {
        $stmt = $pdo->prepare("
            SELECT 
                t.id,
                t.phone,
                t.ip,
                t.name,
                t.code,
                t.created_ts,
                t.expires_at,
                t.block_until_ts,
                t.converted,
                t.converted_at,
                t.converted_to_owner,
                datetime(t.created_ts, 'unixepoch') as created_at
            FROM trialspublic t
            WHERE t.converted = 0
            ORDER BY t.created_ts DESC
        ");
        $stmt->execute();
        $results = $stmt->fetchAll();
        
        error_log("Trials públicos encontrados: " . count($results));
        
        return $results;
    } catch (Throwable $e) {
        error_log("Error getting trials: " . $e->getMessage());
        return [];
    }
}

function get_manual_demos_from_db(PDO $pdo): array {
    try {
        $stmt = $pdo->prepare("
            SELECT 
                id,
                client_whatsapp AS phone,
                '' AS ip,
                client_name AS name,
                code,
                strftime('%s', created_at) AS created_ts,
                expires_at,
                0 AS block_until_ts,
                0 AS converted,
                NULL AS converted_at,
                owner AS converted_to_owner,
                created_at,
                demo_hours,
                max_devices,
                'manual_demo' AS source
            FROM codes
            WHERE COALESCE(is_demo, 0) = 1
            ORDER BY created_at DESC
        ");
        $stmt->execute();
        return $stmt->fetchAll();
    } catch (Throwable $e) {
        error_log("Error getting manual demos: " . $e->getMessage());
        return [];
    }
}

function delete_trial_from_db(PDO $pdo, string $code): bool {
    try {
        $pdo->beginTransaction();
        
        // Eliminar de trialspublic
        $stmt = $pdo->prepare("DELETE FROM trialspublic WHERE code = :code AND converted = 0");
        $stmt->execute([':code' => $code]);
        
        // Eliminar de codes si existe: trial público o demo manual
        $stmt = $pdo->prepare("DELETE FROM codes WHERE code = :code AND (owner = 'trial' OR COALESCE(is_demo,0) = 1)");
        $stmt->execute([':code' => $code]);
        
        $pdo->commit();
        return true;
    } catch (Throwable $e) {
        $pdo->rollBack();
        error_log("Error deleting trial: " . $e->getMessage());
        return false;
    }
}

function delete_expired_trials_from_db(PDO $pdo): int {
    try {
        $now = date('Y-m-d H:i:s');
        
        $stmt = $pdo->prepare("
            DELETE FROM trialspublic 
            WHERE expires_at < :now 
            AND converted = 0
        ");
        $stmt->execute([':now' => $now]);
        
        $deletedCount = $stmt->rowCount();
        
        // También eliminar códigos huérfanos en codes
        $stmt = $pdo->prepare("
            DELETE FROM codes 
            WHERE (owner = 'trial' OR COALESCE(is_demo,0) = 1) 
            AND expires_at < :now
        ");
        $stmt->execute([':now' => $now]);
        
        return $deletedCount;
    } catch (Throwable $e) {
        error_log("Error deleting expired trials: " . $e->getMessage());
        return 0;
    }
}

function delete_all_trials_from_db(PDO $pdo): bool {
    try {
        $pdo->beginTransaction();
        
        // Eliminar todos los trials no convertidos
        $pdo->exec("DELETE FROM trialspublic WHERE converted = 0");
        
        // Eliminar todos los códigos trial
        $pdo->exec("DELETE FROM codes WHERE owner = 'trial' OR COALESCE(is_demo,0) = 1");
        
        $pdo->commit();
        return true;
    } catch (Throwable $e) {
        $pdo->rollBack();
        error_log("Error deleting all trials: " . $e->getMessage());
        return false;
    }
}

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

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

        if (!$pdo) {
            $msgErr = '❌ No se pudo conectar a la base de datos.';
        } else {
            // ============================================
            // CONVERTIR TRIAL A CLIENTE
            // ============================================
            if ($action === 'convert_to_client') {
                $trialCode = (string)($_POST['trial_code'] ?? '');
                $months = (int)($_POST['months'] ?? 1);
                $resellerInput = (string)($_POST['reseller'] ?? '');
                $clientName = trim((string)($_POST['client_name'] ?? ''));
                $clientWhatsapp = only_digits((string)($_POST['client_whatsapp'] ?? ''));

                $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 {
                    try {
                        $pdo->beginTransaction();
                        
                        // Verificar que el trial existe y no está convertido
                        $stmt = $pdo->prepare("
                            SELECT * FROM trialspublic 
                            WHERE code = :code AND converted = 0
                        ");
                        $stmt->execute([':code' => $trialCode]);
                        $trial = $stmt->fetch(PDO::FETCH_ASSOC);
                        
                        if (!$trial) {
                            $stmtManual = $pdo->prepare("SELECT * FROM codes WHERE code = :code AND COALESCE(is_demo,0) = 1 LIMIT 1");
                            $stmtManual->execute([':code' => $trialCode]);
                            $trial = $stmtManual->fetch(PDO::FETCH_ASSOC);
                        }

                        if (!$trial) {
                            throw new Exception('Trial o demo no encontrado, o ya fue convertido.');
                        }
                        
                        // Calcular nueva fecha de expiración
                        $newExpiry = date('Y-m-d H:i:s', strtotime("+{$months} months"));
                        
                        // 1. ACTUALIZAR el código en la tabla codes (cambiar de trial a cliente)
                        $stmt = $pdo->prepare("
                            UPDATE codes 
                            SET owner = :owner,
                                expires_at = :expires,
                                client_name = :name,
                                client_whatsapp = :whatsapp,
                                status = 'active',
                                is_demo = 0,
                                demo_hours = 0
                            WHERE code = :code AND (owner = 'trial' OR COALESCE(is_demo,0) = 1)
                        ");
                        
                        $stmt->execute([
                            ':owner' => $reseller,
                            ':expires' => $newExpiry,
                            ':name' => $clientName,
                            ':whatsapp' => $clientWhatsapp,
                            ':code' => $trialCode
                        ]);

                        // Si no existe en codes, crearlo
                        if ($stmt->rowCount() === 0) {
                            $stmt = $pdo->prepare("
                                INSERT INTO codes (code, expires_at, owner, client_name, client_whatsapp, status, created_at)
                                VALUES (:code, :expires, :owner, :name, :whatsapp, 'active', :created_at)
                            ");
                            $stmt->execute([
                                ':code' => $trialCode,
                                ':expires' => $newExpiry,
                                ':owner' => $reseller,
                                ':name' => $clientName,
                                ':whatsapp' => $clientWhatsapp,
                                ':created_at' => date('Y-m-d H:i:s')
                            ]);
                        }

                        // 2. Marcar el trial como convertido en trialspublic
                        $stmt = $pdo->prepare("
                            UPDATE trialspublic 
                            SET converted = 1,
                                converted_at = :converted_at,
                                converted_to_owner = :owner
                            WHERE code = :code
                        ");
                        
                        $stmt->execute([
                            ':converted_at' => date('Y-m-d H:i:s'),
                            ':owner' => $reseller,
                            ':code' => $trialCode
                        ]);

                        $pdo->commit();
                        
                        $msgOk = "✅ Trial convertido exitosamente a cliente!<br>" .
                                "📋 Código: <strong>{$trialCode}</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') {
                $trialCode = (string)($_POST['trial_code'] ?? '');
                
                if (delete_trial_from_db($pdo, $trialCode)) {
                    $msgOk = '✅ Trial eliminado exitosamente.';
                } else {
                    $msgErr = '❌ Error al eliminar el trial.';
                }
            }
            
            // ============================================
            // ELIMINAR EXPIRADOS
            // ============================================
            elseif ($action === 'delete_expired') {
                $deletedCount = delete_expired_trials_from_db($pdo);
                
                if ($deletedCount === 0) {
                    $msgErr = 'ℹ️ No hay trials expirados para eliminar.';
                } else {
                    $msgOk = "✅ Se eliminaron {$deletedCount} trial(s) expirado(s).";
                }
            }
            
            // ============================================
            // ELIMINAR TODOS
            // ============================================
            elseif ($action === 'delete_all') {
                if (delete_all_trials_from_db($pdo)) {
                    $msgOk = '✅ Todos los trials fueron eliminados.';
                } else {
                    $msgErr = '❌ Error al limpiar los trials.';
                }
            }
        }
    }
}

/* =======================
   LOAD DATA
======================= */
$pdo = open_db($dbFile);
$resellers = $pdo ? get_resellers($pdo) : [];
$trials = $pdo ? array_merge(get_trials_from_db($pdo), get_manual_demos_from_db($pdo)) : [];
usort($trials, function($a, $b){ return (int)($b['created_ts'] ?? 0) <=> (int)($a['created_ts'] ?? 0); });

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

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

foreach ($trials as $trial) {
    $name = (string)($trial['name'] ?? '');
    $phone = (string)($trial['phone'] ?? '');
    $code = (string)($trial['code'] ?? '');
    $exp = (string)($trial['expires_at'] ?? '');
    $expTs = strtotime($exp);
    $created = (string)($trial['created_at'] ?? date('Y-m-d H:i:s', $trial['created_ts']));
    
    $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;
    }

    // Añadir created_at al array para mostrarlo
    $trial['created_at'] = $created;
    $filtered[] = $trial;
}

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

foreach ($trials as $trial) {
    $expTs = strtotime((string)($trial['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 PRUEBAS / DEMOS
                </h3>
                <small>Pruebas públicas y demos creadas desde el panel - Convertir a clientes</small>
            </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> Creado</th>
                            <th><i class="fa fa-hourglass"></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 (empty($filtered)): ?>
                        <tr>
                            <td colspan="7" 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): 
                            $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 && !$isExpired) {
                                $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>
                                <?php if(($row['source'] ?? '') === 'manual_demo'): ?>
                                    <br><span class="badge bg-warning mt-1">Demo panel <?=h($row['demo_hours'] ?? '')?>h</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?=h($created)?>
                            </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">
                                    <?php if (!$isExpired): ?>
                                        <!-- Convertir a Cliente -->
                                        <button class="btn btn-sm btn-success" 
                                                onclick="showConvertModal('<?=h($code)?>', '<?=h($name)?>', '<?=h($phone)?>', '<?=h($code)?>')"
                                                title="Convertir a cliente">
                                            <i class="fa fa-user-plus"></i> Convertir
                                        </button>
                                    <?php endif; ?>
                                    
                                    <!-- 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_code" value="<?=h($code)?>">
                                        <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 -->
<div id="convertModal" class="custom-modal">
    <div class="custom-modal-content">
        
        <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_code" id="modal_trial_code">

            <!-- HEADER -->
            <div class="custom-modal-header">
                <h3>👤 Convertir Trial a Cliente</h3>
                <span class="close-btn" onclick="closeModal()">&times;</span>
            </div>

            <!-- BODY -->
            <div class="custom-modal-body">

                <div class="alert info">
                    <strong>Código:</strong> <span id="modal_code">-</span>
                </div>

                <div class="grid">
                    <div>
                        <label>Nombre del Cliente *</label>
                        <input type="text" name="client_name" id="modal_name" required>
                    </div>

                    <div>
                        <label>WhatsApp *</label>
                        <input type="tel" name="client_whatsapp" id="modal_phone" required>
                        <small>Solo números, sin espacios</small>
                    </div>

                    <div>
                        <label>Plan (meses)</label>
                        <select name="months">
                            <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>
                        <label>Asignar a Reseller</label>
                        <select name="reseller">
                            <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 warning">
                    ⚠️ Al convertir, el trial pasará a ser un cliente permanente con el plan seleccionado.
                </div>

            </div>

            <!-- FOOTER -->
            <div class="custom-modal-footer">
                <button type="button" class="btn cancel" onclick="closeModal()">Cancelar</button>
                <button type="submit" class="btn success">Convertir a Cliente</button>
            </div>

        </form>
    </div>
</div>

<script>
function showConvertModal(code, name, phone, trialCode) {
    document.getElementById('modal_trial_code').value = code;
    document.getElementById('modal_name').value = name;
    document.getElementById('modal_phone').value = phone;
    document.getElementById('modal_code').textContent = code;

    document.getElementById('convertModal').style.display = 'block';
}

function closeModal() {
    document.getElementById('convertModal').style.display = 'none';
}

// Cerrar modal al hacer clic fuera
window.onclick = function(e) {
    const modal = document.getElementById('convertModal');
    if (e.target === modal) {
        closeModal();
    }
};

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

    if (phone.length < 10) {
        e.preventDefault();
        alert('❌ El WhatsApp debe tener al menos 10 dígitos');
        return;
    }

    if (!confirm('¿Estás seguro de convertir este trial a cliente?')) {
        e.preventDefault();
    }
});
</script>

<style>
.custom-modal {
    display: none;
    position: fixed;
    z-index: 9999;
    inset: 0;
    background: rgba(0,0,0,0.7);
    backdrop-filter: blur(5px);
}

.custom-modal-content {
    background: #1e1e2f;
    color: #fff;
    width: 90%;
    max-width: 700px;
    margin: 5% auto;
    border-radius: 10px;
    overflow: hidden;
    animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
    from {transform: scale(0.9); opacity: 0;}
    to {transform: scale(1); opacity: 1;}
}

.custom-modal-header,
.custom-modal-footer {
    padding: 15px 20px;
    border-bottom: 1px solid #333;
}

.custom-modal-footer {
    border-top: 1px solid #333;
    border-bottom: none;
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

.custom-modal-body {
    padding: 20px;
}

.close-btn {
    float: right;
    cursor: pointer;
    font-size: 24px;
    font-weight: bold;
}

.close-btn:hover {
    color: #ff4444;
}

.grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 15px;
}

input, select {
    width: 100%;
    padding: 10px;
    background: #2a2a3d;
    border: 1px solid #444;
    color: #fff;
    border-radius: 5px;
}

input:focus, select:focus {
    outline: none;
    border-color: #0d6efd;
}

.alert {
    padding: 12px;
    border-radius: 5px;
    margin-bottom: 15px;
}

.alert.info {
    background: #0d6efd33;
    border-left: 3px solid #0d6efd;
}

.alert.warning {
    background: #ffc10733;
    border-left: 3px solid #ffc107;
}

.btn {
    padding: 8px 20px;
    border: none;
    cursor: pointer;
    border-radius: 5px;
    font-weight: 500;
    transition: all 0.3s;
}

.btn.success {
    background: #28a745;
    color: white;
}

.btn.success:hover {
    background: #218838;
}

.btn.cancel {
    background: #6c757d;
    color: white;
}

.btn.cancel:hover {
    background: #5a6268;
}

@media (max-width: 768px) {
    .grid {
        grid-template-columns: 1fr;
    }
    
    .custom-modal-content {
        margin: 10% auto;
        width: 95%;
    }
}
</style>

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