<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

$title = 'Consultas';
require_once __DIR__ . '/../templates/header.php';
require_role('client');
require_once __DIR__ . '/../includes/imap_lib.php';
csrf_check();

$user_id = $_SESSION['uid'] ?? 0;
$latestResult = null;
$error = null;
$accountOriginal = '';
$platform_id = 0;
$minutes = 10;
$platformName = '';

// Obtener plataformas asignadas
$platsStmt = pdo()->prepare(
    'SELECT DISTINCT p.* FROM platforms p
    INNER JOIN assigned_accounts aa ON p.id = aa.platform_id
    WHERE aa.client_id = :client_id
    ORDER BY p.name'
);
$platsStmt->execute(['client_id' => $user_id]);
$plats = $platsStmt->fetchAll();

function get_all_parts($stream, $uid, $structure, $prefix = '') {
    $result = '';
    if (!isset($structure->parts)) {
        $partNum = $prefix ? $prefix : '1';
        $body = imap_fetchbody($stream, $uid, $partNum, FT_UID);
        switch ($structure->encoding) {
            case 3: $body = base64_decode($body); break;
            case 4: $body = quoted_printable_decode($body); break;
        }
        $result .= $body;
    } else {
        foreach ($structure->parts as $i => $s) {
            $pfx = $prefix ? "$prefix." . ($i + 1) : strval($i + 1);
            $result .= get_all_parts($stream, $uid, $s, $pfx);
        }
    }
    return $result;
}

function decode_subject($subjectRaw) {
    $subjectParts = imap_mime_header_decode($subjectRaw);
    $subject = '';
    foreach ($subjectParts as $part) {
        $text = $part->text;
        if ($part->charset && $part->charset != 'default') {
            $text = iconv($part->charset, 'UTF-8//TRANSLIT', $text);
        }
        $subject .= $text;
    }
    return $subject;
}

function buscar_codigo_otp_netflix($htmlBody) {
    if (!$htmlBody) return null;
    if (preg_match('/\b(\d{4,6})\b/', strip_tags($htmlBody), $matches)) {
        return $matches[1];
    }
    return null;
}
function buscar_codigo_otp_disneyplus($htmlBody) {
    if (!$htmlBody) return null;
    if (preg_match('/<td[^>]*font-size\s*:\s*28px[^>]*>\s*(\d{6})\s*<\/td>/i', $htmlBody, $matches)) {
        return $matches[1];
    }
    if (preg_match('/(?:passcode|c[oó]digo)[^0-9]{0,15}([0-9]{6})/i', $htmlBody, $matches)) {
        return $matches[1];
    }
    if (preg_match_all('/\b(\d{6})\b/', strip_tags($htmlBody), $matches) && count($matches[1]) === 1) {
        return $matches[1][0];
    }
    return null;
}
function buscar_codigo_otp_prime($htmlBody) {
    if (!$htmlBody) return null;
    $text = strip_tags($htmlBody);
    if (preg_match('/(?:your\s+code|c[oó]digo|verification\s+code|passcode)[^0-9]{0,15}(\d{6})/i', $text, $matches)) {
        return $matches[1];
    }
    if (preg_match_all('/\b(\d{6})\b/', $text, $matches) && count($matches[1]) === 1) {
        return $matches[1][0];
    }
    return null;
}
function buscar_codigo_otp_hbo($htmlBody) {
    if (!$htmlBody) return null;
    if (preg_match('/\b(\d{6})\b/', strip_tags($htmlBody), $matches)) {
        return $matches[1];
    }
    return null;
}

function extraer_url_boton_restaurar($html) {
    if (preg_match('~<a[^>]+href=["\']([^"\']+)["\'][^>]*>\s*Restablecer contraseña\s*</a>~i', $html, $matches)) {
        $url = $matches[1];
        $url = html_entity_decode($url);
        $url = urldecode($url);
        return $url;
    }
    return null;
}

function buscar_codigo_netflix_por_email($stream, $uids, $email_consultado) {
    foreach ($uids as $uid) {
        $overview = @imap_fetch_overview($stream, $uid, FT_UID)[0] ?? null;
        if (!$overview) continue;
        if (!preg_match('/netflix\.com/i', $overview->from ?? '')) continue;
        $headerInfo = imap_headerinfo($stream, imap_msgno($stream, $uid));
        $toEmail = strtolower(trim($headerInfo->to[0]->mailbox . '@' . $headerInfo->to[0]->host));
        if ($toEmail !== strtolower(trim($email_consultado))) continue;
        $subject = decode_subject($overview->subject ?? '');
        if (preg_match('/restablecimiento de contraseña|password reset/i', $subject)) {
            $structure = imap_fetchstructure($stream, $uid, FT_UID);
            $fullBody = get_all_parts($stream, $uid, $structure);
            $url = extraer_url_boton_restaurar($fullBody);
            if (!$url) $url = 'https://www.netflix.com/password';
            $button_html = '<a href="' . htmlspecialchars($url) . '" target="_blank" rel="noopener noreferrer" style="
                background:#e50914;color:#fff;padding:10px 24px;border-radius:7px;
                text-decoration:none;display:inline-block;font-size:15px;font-weight:600;border:none;">
                Restablecer contraseña
            </a>';
            return ['action'=>'reset_link','subject'=>$subject,'button_html'=>$button_html];
        }
        $structure = imap_fetchstructure($stream, $uid, FT_UID);
        $fullBody = get_all_parts($stream, $uid, $structure);
        $code = buscar_codigo_otp_netflix($fullBody);
        if ($code) return ['code'=>$code,'subject'=>$subject];
    }
    return null;
}

function buscar_codigo_disney_por_email($stream, $uids, $email_consultado) {
    foreach ($uids as $uid) {
        $overview = @imap_fetch_overview($stream, $uid, FT_UID)[0] ?? null;
        if (!$overview) continue;
        if (!preg_match('/disneyplus\.com|disney\.com/i', $overview->from ?? '')) continue;
        $headerInfo = imap_headerinfo($stream, imap_msgno($stream, $uid));
        $toEmail = strtolower(trim($headerInfo->to[0]->mailbox . '@' . $headerInfo->to[0]->host));
        if ($toEmail !== strtolower(trim($email_consultado))) continue;
        $structure = imap_fetchstructure($stream, $uid, FT_UID);
        $fullBody = get_all_parts($stream, $uid, $structure);
        $code = buscar_codigo_otp_disneyplus($fullBody);
        if ($code) return ['code' => $code, 'subject' => decode_subject($overview->subject ?? '')];
    }
    return null;
}

function buscar_codigo_prime_por_email($stream, $uids, $email_consultado) {
    foreach ($uids as $uid) {
        $overview = @imap_fetch_overview($stream, $uid, FT_UID)[0] ?? null;
        if (!$overview) continue;
        if (!preg_match('/amazon\.com|primevideo\.com/i', $overview->from ?? '')) continue;
        $headerInfo = imap_headerinfo($stream, imap_msgno($stream, $uid));
        $toEmail = strtolower(trim($headerInfo->to[0]->mailbox . '@' . $headerInfo->to[0]->host));
        if ($toEmail !== strtolower(trim($email_consultado))) continue;
        $structure = imap_fetchstructure($stream, $uid, FT_UID);
        $fullBody = get_all_parts($stream, $uid, $structure);
        $code = buscar_codigo_otp_prime($fullBody);
        if ($code) {
            if (preg_match('/recuperaci[oó]n|restablecimiento|reset|cambio|cambiar.*contrase(?:ñ|n)a/i', strip_tags($fullBody))) {
                return ['action'=>'reset_link','subject'=>decode_subject($overview->subject ?? ''),'button_html'=>'<a href="https://www.amazon.com/ap/password" target="_blank" style="background:#e50914;color:#fff;padding:8px 16px;border-radius:5px;text-decoration:none;">Restablecer contraseña</a>'];
            }
            return ['code'=>$code,'subject'=>decode_subject($overview->subject ?? '')];
        }
    }
    return null;
}

function extraer_url_boton_restaurar_hbo($html) {
    if (preg_match('~<a[^>]+href=["\'](https://auth\.hbomax\.com/set-new-password\?passwordResetToken=[^"\']+)["\'][^>]*>.*?restablecer\s*contrase(?:ñ|n)a.*?</a>~is', $html, $matches)) {
        $url = html_entity_decode($matches[1]);
        $url = urldecode($url);
        return $url;
    }
    return null;
}

function buscar_codigo_hbo_por_email($stream, $uids, $email_consultado) {
    foreach ($uids as $uid) {
        $overview = @imap_fetch_overview($stream, $uid, FT_UID)[0] ?? null;
        if (!$overview) continue;
        $from = strtolower($overview->from ?? '');
        if (strpos($from, 'hbo max') === false && strpos($from, 'hbomax.com') === false) continue;
        $headerInfo = imap_headerinfo($stream, imap_msgno($stream, $uid));
        $toEmail = strtolower(trim($headerInfo->to[0]->mailbox . '@' . $headerInfo->to[0]->host));
        if ($toEmail !== strtolower(trim($email_consultado))) continue;

        $subject = decode_subject($overview->subject ?? '');
        $structure = imap_fetchstructure($stream, $uid, FT_UID);
        $fullBody = get_all_parts($stream, $uid, $structure);

        $url = extraer_url_boton_restaurar_hbo($fullBody);
        if ($url) {
            $button_html = '<a href="' . htmlspecialchars($url) . '" target="_blank" rel="noopener noreferrer" 
                style="background:#3d6a99;color:#fff;padding:13px 50px 10px;border-radius:30px;
                text-decoration:none;display:inline-block;font-size:16px;font-weight:bold;
                font-family:helvetica, arial, sans-serif;border:none;">
                RESTABLECER CONTRASEÑA
            </a>';
            return ['action' => 'reset_link', 'subject' => $subject, 'button_html' => $button_html, 'url' => $url];
        }

        $code = buscar_codigo_otp_hbo($fullBody);
        if ($code) return ['code' => $code, 'subject' => $subject];
    }
    return null;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $platform_id = (int)($_POST['platform_id'] ?? 0);
    $accountOriginal = trim($_POST['account'] ?? '');
    $minutes = (int)($_POST['minutes'] ?? 10);
    $latestResult = null;
    $error = null;
    $platformName = '';

    if ($platform_id && $accountOriginal) {
        try {
            $stmt = pdo()->prepare('SELECT expiration_date FROM assigned_accounts WHERE email = ? AND platform_id = ? LIMIT 1');
            $stmt->execute([$accountOriginal, $platform_id]);
            $expiracion = $stmt->fetchColumn();

            if ($expiracion === false || $expiracion === null) {
                $error = "Esta cuenta no la tienes asignada";
            } else {
                $hoy = new DateTime();
                $fechaExp = new DateTime($expiracion);
                if ($fechaExp < $hoy) {
                    $error = "La cuenta está caducada desde " . $fechaExp->format('Y-m-d') . ". Por favor, renueva con el administrador.";
                }
            }

            if (!$error) {
                $stmtImap = pdo()->prepare('SELECT * FROM imap_accounts WHERE username = ? AND enabled = 1');
                $stmtImap->execute(['info@carviznet.net']);
                $imapData = $stmtImap->fetch();

                if (!$imapData) {
                    $error = "No hay cuenta IMAP habilitada para la cuenta principal.";
                } else {
                    $mbox = "{" . $imapData['host'] . ":" . $imapData['port'] . "/" . $imapData['encryption'] . "}INBOX";
                    $pass = decrypt_text($imapData['password_enc']);
                    $stream = @imap_open($mbox, $imapData['username'], $pass);

                    if (!$stream) {
                        $error = "Error conectando IMAP: " . imap_last_error();
                    } else {
                        $sinceDate = date('d-M-Y');
                        $uids = @imap_search($stream, 'SINCE "' . $sinceDate . '" UNDELETED', SE_UID) ?: [];
                        $uids = array_reverse($uids);

                        $filteredUids = [];
                        $limite = strtotime("-{$minutes} minutes");
                        foreach ($uids as $uid) {
                            $overview = @imap_fetch_overview($stream, $uid, FT_UID)[0] ?? null;
                            if (!$overview) continue;
                            $messageTime = strtotime($overview->date);
                            if ($messageTime < $limite) continue;
                            $filteredUids[] = $uid;
                        }

                        foreach ($plats as $p) {
                            if ($p['id'] === $platform_id) {
                                $platformName = strtolower($p['name']);
                                break;
                            }
                        }

                        if (strpos($platformName, 'netflix') !== false) {
                            $latestResult = buscar_codigo_netflix_por_email($stream, $filteredUids, $accountOriginal);
                            if ($latestResult === null) {
                                $error = "No se encontró código para la cuenta $accountOriginal en Netflix.";
                            }
                        } elseif (strpos($platformName, 'disney') !== false) {
                            $latestResult = buscar_codigo_disney_por_email($stream, $filteredUids, $accountOriginal);
                            if ($latestResult === null) {
                                $error = "No se encontró código para la cuenta $accountOriginal en Disney+.";
                            }
                        } elseif (strpos($platformName, 'prime') !== false || strpos($platformName, 'amazon') !== false) {
                            $latestResult = buscar_codigo_prime_por_email($stream, $filteredUids, $accountOriginal);
                            if ($latestResult === null) {
                                $error = "No se encontró código para la cuenta $accountOriginal en Amazon Prime.";
                            }
                        } elseif (strpos($platformName, 'hbo') !== false) {
                            $latestResult = buscar_codigo_hbo_por_email($stream, $filteredUids, $accountOriginal);
                            if ($latestResult === null) {
                                $error = "No se encontró código para la cuenta $accountOriginal en HBO Max.";
                            }
                        } else {
                            $error = "Plataforma no soportada.";
                        }

                        imap_close($stream);
                    }
                }
            }
        } catch (Exception $ex) {
            $error = $ex->getMessage();
        }
    } else {
        $error = "Selecciona plataforma y escribe el correo de la cuenta.";
    }
}
?>

<div class="card card-body mb-3">
    <h3>Panel de Consultas</h3>
    <form method="post" class="row g-2">
        <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
        <div class="col-md-3">
            <label class="form-label">Plataforma</label>
            <select class="form-select" name="platform_id" required>
                <option value="">Seleccione...</option>
                <?php foreach ($plats as $p): ?>
                    <option value="<?= e($p['id']) ?>" <?= $platform_id === $p['id'] ? 'selected' : '' ?>>
                        <?= e($p['name']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-5">
            <label class="form-label">Cuenta de email</label>
            <input class="form-control" name="account" value="<?= e($accountOriginal) ?>" placeholder="ej: usuario@correo.com" required>
        </div>
        <div class="col-md-2">
            <label class="form-label">Últimos (min)</label>
            <input class="form-control" type="number" min="1" max="60" name="minutes" value="<?= e($minutes) ?>">
        </div>
        <div class="col-md-2 d-flex align-items-end">
              <!-- <button class="btn btn-primary w-100" id="consultar-btn" disabled>Espere (00:45)</button>-->
              <button class="btn btn-primary w-100" id="consultar-btn"></button>
        </div>
    </form>
</div>

<?php if ($error): ?>
    <div class="alert alert-danger"><?= e($error) ?></div>
<?php elseif ($latestResult): ?>
    <?php if (isset($latestResult['code'])): ?>
        <div class="alert alert-success d-flex align-items-center gap-2">
            <strong>
                <?php
                if (strpos($platformName, 'netflix') !== false) {
                    echo "Código Netflix: ";
                } elseif (strpos($platformName, 'disney') !== false) {
                    echo "Código Disney+: ";
                } elseif (strpos($platformName, 'prime') !== false || strpos($platformName, 'amazon') !== false) {
                    echo "Código Amazon Prime: ";
                } elseif (strpos($platformName, 'hbo') !== false) {
                    echo "Código HBO Max: ";
                } else {
                    echo "Código: ";
                }
                ?>
            </strong>
            <span id="codigo-copiable" style="cursor:pointer; user-select:all; font-weight: bold;">
                <?= e($latestResult['code']) ?>
            </span>
            <small id="mensaje-copiado" class="text-success" style="opacity: 0; transition: opacity 0.3s;">¡Código copiado!</small>
        </div>
    <?php elseif (isset($latestResult['action']) && $latestResult['action'] === 'reset_link'): ?>
        <div class="alert alert-info" style="background:#eafaff; padding:15px; border-radius:8px;">
            <?= $latestResult['button_html'] ?>
        </div>
    <?php endif; ?>
<?php endif; ?>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const copiable = document.getElementById('codigo-copiable');
    if (copiable) {
        copiable.onclick = function () {
            const codigo = this.textContent.trim();
            navigator.clipboard.writeText(codigo).then(() => {
                const mensaje = document.getElementById('mensaje-copiado');
                if (mensaje) {
                    mensaje.style.opacity = '1';
                    setTimeout(() => {
                        mensaje.style.opacity = '0';
                    }, 2000);
                }
            });
        };
    }

    const btn = document.getElementById('consultar-btn');
    if (btn) {
        let segundosRestantes = 0;
        function formatTime(s) {
            const m = Math.floor(s / 60);
            const ss = s % 60;
            return `Espere (${m.toString().padStart(2, '0')}:${ss.toString().padStart(2, '0')})`;
        }
        btn.disabled = true;
        btn.innerText = formatTime(segundosRestantes);
        const interval = setInterval(function () {
            segundosRestantes--;
            if (segundosRestantes > 0) {
                btn.innerText = formatTime(segundosRestantes);
            } else {
                clearInterval(interval);
                btn.innerText = 'Consultar';
                btn.disabled = false;
            }
        }, 1000);
    }
});
</script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

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