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

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

$currentUser = $_SESSION['name'];
$role = $_SESSION['role'];

if (!in_array($role, ['master','super-reseller','reseller'], true)) {
    die("Acceso denegado");
}

$dbFile = __DIR__ . '/api/.db.db';
ensure_codes_schema($dbFile);

$me = $db->select('menualuser', 'credits', 'username = :u', '', [':u' => $currentUser]);
$myCredits = ($role === 'master') ? -1 : ($me[0]['credits'] ?? 0);
$myUnlimited = ($role === 'master') ? true : is_unlimited_credits($myCredits);

function generateCode() {
    return str_pad((string)random_int(0, 999999), 6, '0', STR_PAD_LEFT);
}

$showModal = false;
$newCode = '';
$newClient = '';
$newPhone = '';
$newExpire = '';
$newType = 'paid';
$usedCredits = 0;
$downloadUrl = (string) settings_get($db, 'app_download_url', '');
$downloaderCode = (string) settings_get($db, 'app_downloader_code', '');

if (isset($_POST['submit'])) {
    $client = trim($_POST['client_name'] ?? '');
    $phone  = trim($_POST['client_whatsapp'] ?? '');
    $creationType = $_POST['creation_type'] ?? 'paid';
    $months = max(1, (int)($_POST['months'] ?? 1));
    $demoHours = (int)($_POST['demo_hours'] ?? 4);

    $allowedDemoHours = [2, 4, 24];
    if (!in_array($demoHours, $allowedDemoHours, true)) {
        $demoHours = 4;
    }

    $isFreeDemo = ($creationType === 'free_demo');
    $usedCredits = $isFreeDemo ? 0 : $months;

    if ($client === '' || $phone === '') {
        echo "<script>alert('Completa todos los campos');</script>";
    } elseif (!$myUnlimited && $role !== 'master' && $usedCredits > (int)$myCredits) {
        echo "<script>alert('Créditos insuficientes');</script>";
    } else {
        $expire = $isFreeDemo
            ? date('Y-m-d H:i:s', strtotime("+{$demoHours} hours"))
            : date('Y-m-d', strtotime('+' . ($months * 30) . ' days'));

        $code = '';
        for ($i = 0; $i < 50; $i++) {
            $candidate = generateCode();
            $exist = $db->select('codes', 'id', 'code = :c', '', [':c' => $candidate]);
            if (!$exist) {
                $code = $candidate;
                break;
            }
        }

        if ($code !== '') {
            $sqlite = new SQLite3($dbFile);
            $stmt = $sqlite->prepare("INSERT INTO codes
                (code, expires_at, owner, client_name, client_whatsapp, created_at, is_free_trial, trial_hours, status)
                VALUES
                (:code, :expire, :owner, :client, :phone, :created, :is_free_trial, :trial_hours, :status)");

            $stmt->bindValue(':code', $code);
            $stmt->bindValue(':expire', $expire);
            $stmt->bindValue(':owner', $currentUser);
            $stmt->bindValue(':client', $client);
            $stmt->bindValue(':phone', $phone);
            $stmt->bindValue(':created', date('Y-m-d H:i:s'));
            $stmt->bindValue(':is_free_trial', $isFreeDemo ? 1 : 0, SQLITE3_INTEGER);
            $stmt->bindValue(':trial_hours', $isFreeDemo ? $demoHours : 0, SQLITE3_INTEGER);
            $stmt->bindValue(':status', 'active');
            $stmt->execute();

            if ($role !== 'master' && !$myUnlimited && $usedCredits > 0) {
                $db->update('menualuser', ['credits' => ((int)$myCredits - $usedCredits)], 'username = :u', [':u' => $currentUser]);
            }

            $showModal = true;
            $newCode = $code;
            $newClient = $client;
            $newPhone = $phone;
            $newExpire = $expire;
            $newType = $isFreeDemo ? 'free_demo' : 'paid';
        }
    }
}
?>

<div class="col-md-8 mx-auto">
<div class="card text-white ctluser-main">
<div class="card-header text-center">
<h2><i class="fa fa-key"></i> Crear Código</h2>
</div>

<div class="card-body">
<form method="post">
<div class="form-group">
<label>Cliente</label>
<input type="text" name="client_name" class="form-control" required>
</div>

<div class="form-group">
<label>WhatsApp</label>
<input type="text" name="client_whatsapp" class="form-control" placeholder="593xxxxxxxxx" required>
</div>

<div class="form-group">
<label>Tipo de creación</label>
<select name="creation_type" id="creation_type" class="form-control" onchange="toggleCreationType()">
    <option value="paid">Usuario con créditos</option>
    <option value="free_demo">Demo gratis</option>
</select>
<small class="text-muted">La demo gratis no descuenta créditos.</small>
</div>

<div class="form-group" id="paid_block">
<label>Meses</label>
<select name="months" class="form-control">
<?php for($i=1;$i<=12;$i++): ?>
<option value="<?=$i?>"><?=$i?> mes<?=$i>1?'es':''?></option>
<?php endfor; ?>
</select>
<?php if($role !== 'master'): ?>
<small>Créditos disponibles: <b><?=credits_display($myCredits)?></b></small>
<?php endif; ?>
</div>

<div class="form-group" id="demo_block" style="display:none;">
<label>Duración demo gratis</label>
<select name="demo_hours" class="form-control">
    <option value="2">2 horas</option>
    <option value="4" selected>4 horas</option>
    <option value="24">24 horas</option>
</select>
<small class="text-muted">Las pruebas gratis no descuentan créditos del panel.</small>
</div>

<button type="submit" name="submit" class="btn btn-info">
<i class="fa fa-check"></i> Crear Código
</button>
</form>
</div>
</div>
</div>


<?php if ($showModal): ?>
<script>
const generatedClientData = {
    name: <?=json_encode($newClient, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)?>,
    phone: <?=json_encode($newPhone, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)?>,
    code: <?=json_encode($newCode, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)?>,
    expire: <?=json_encode($newExpire, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)?>,
    downloadUrl: <?=json_encode($downloadUrl, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)?>,
    downloaderCode: <?=json_encode($downloaderCode, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)?>
};
function buildGeneratedMessage() {
    var parts = [];
    parts.push('Hola ' + generatedClientData.name + ', aquí tienes tus datos de acceso:');
    parts.push('Codigo de acceso: ' + generatedClientData.code);
    parts.push('Fecha de expiracion: ' + generatedClientData.expire);
    if (generatedClientData.downloadUrl) parts.push('Link de descarga: ' + generatedClientData.downloadUrl);
    if (generatedClientData.downloaderCode) parts.push('Codigo downloader: ' + generatedClientData.downloaderCode);
    return parts.join('\n');
}
function copyGeneratedCode() {
    navigator.clipboard.writeText(generatedClientData.code).then(function() {
        alert('Código copiado: ' + generatedClientData.code);
    });
}
function shareGeneratedWhatsApp() {
    var text = buildGeneratedMessage();
    openWhatsApp(buildWhatsAppUrl(generatedClientData.phone, text), text);
}
</script>
<div class="modal fade show" tabindex="-1" role="dialog" style="display:block;background:rgba(0,0,0,.65)">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content bg-dark text-white border-info">
      <div class="modal-header border-secondary">
        <h5 class="modal-title"><i class="fa fa-check-circle text-success"></i> Código generado</h5>
        <a href="addclient.php" class="close text-white"><span>&times;</span></a>
      </div>
      <div class="modal-body text-center">
        <p class="mb-2">Cliente: <strong><?=htmlspecialchars($newClient)?></strong></p>
        <p class="mb-2">WhatsApp: <strong><?=htmlspecialchars($newPhone)?></strong></p>
        <div class="display-4 text-info font-weight-bold mb-3"><?=htmlspecialchars($newCode)?></div>
        <p>Expira: <strong><?=htmlspecialchars($newExpire)?></strong></p>
        <?php if ($downloadUrl || $downloaderCode): ?>
        <div class="alert alert-secondary text-left mt-3 mb-0">
          <?php if ($downloadUrl): ?><div><strong>Link de descarga:</strong> <span class="text-break"><?=htmlspecialchars($downloadUrl)?></span></div><?php endif; ?>
          <?php if ($downloaderCode): ?><div class="mt-1"><strong>Código downloader:</strong> <?=htmlspecialchars($downloaderCode)?></div><?php endif; ?>
        </div>
        <?php endif; ?>
        <p class="text-muted mt-3 mb-0"><?= $newType === 'free_demo' ? 'Demo gratis sin consumo de créditos.' : 'Código descontado del saldo del usuario.' ?></p>
      </div>
      <div class="modal-footer border-secondary d-flex flex-wrap justify-content-center">
        <button type="button" class="btn btn-outline-light" onclick="copyGeneratedCode()">Copiar código</button>
        <button type="button" class="btn btn-success" onclick="shareGeneratedWhatsApp()"><i class="fa fa-whatsapp"></i> Compartir por WhatsApp</button>
        <a href="addclient.php" class="btn btn-info">Cerrar</a>
      </div>
    </div>
  </div>
</div>
<?php endif; ?>

<script>
function toggleCreationType(){
    var type = document.getElementById('creation_type').value;
    document.getElementById('paid_block').style.display = (type === 'paid') ? 'block' : 'none';
    document.getElementById('demo_block').style.display = (type === 'free_demo') ? 'block' : 'none';
}
function buildWhatsAppUrl(phone, text) {
    var cleanPhone = String(phone || '').replace(/\D+/g, '');
    var encoded = encodeURIComponent(text);
    if (cleanPhone.length >= 10) {
        return 'https://wa.me/' + cleanPhone + '?text=' + encoded;
    }
    return 'https://wa.me/?text=' + encoded;
}
function openWhatsApp(url, fallbackText) {
    var popup = window.open(url, '_blank');
    if (!popup || popup.closed || typeof popup.closed === 'undefined') {
        if (navigator.clipboard && fallbackText) {
            navigator.clipboard.writeText(fallbackText).then(function(){
                alert('No se pudo abrir WhatsApp automáticamente. El mensaje fue copiado.');
            }).catch(function(){
                alert('No se pudo abrir WhatsApp automáticamente.');
            });
        } else {
            alert('No se pudo abrir WhatsApp automáticamente.');
        }
    }
}
toggleCreationType();
</script>

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