<?php
declare(strict_types=1);

if (isset($_GET["app_image"])) {
    $file = dirname(__DIR__) . "/api/img/qrcode.png";
    if (!is_file($file)) {
        http_response_code(404);
        exit;
    }
    header("Content-Type: image/png");
    header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
    readfile($file);
    exit;
}

session_start();
if (!isset($_SESSION['panel_user'])) {
    header('Location: index.php');
    exit;
}
if (($_SESSION['tipo_user'] ?? '') !== 'admin') {
    header('Location: dashboard.php');
    exit;
}

require_once dirname(__DIR__) . '/api/_auth_common.php';

$db = new PDO('sqlite:' . dirname(__DIR__) . '/api/db.db');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
auth_ensure_schema($db);

function qr_has_column(PDO $db, string $column): bool {
    $st = $db->query('PRAGMA table_info(app_config)');
    foreach (($st ? $st->fetchAll(PDO::FETCH_ASSOC) : []) as $col) {
        if (($col['name'] ?? '') === $column) {
            return true;
        }
    }
    return false;
}

function qr_ensure_columns(PDO $db): void {
    if (!qr_has_column($db, 'qrcode_app_enabled')) {
        $db->exec("ALTER TABLE app_config ADD COLUMN qrcode_app_enabled INTEGER DEFAULT 1");
    }
    if (!qr_has_column($db, 'updated_at')) {
        $db->exec("ALTER TABLE app_config ADD COLUMN updated_at DATETIME");
    }
    if (!qr_has_column($db, 'qrcode_whatsapp')) {
        $db->exec("ALTER TABLE app_config ADD COLUMN qrcode_whatsapp TEXT DEFAULT ''");
    }
    if (!qr_has_column($db, 'qrcode_url')) {
        $db->exec("ALTER TABLE app_config ADD COLUMN qrcode_url TEXT DEFAULT ''");
    }
}

function qr_build_whatsapp_url(string $number): string {
    $digits = preg_replace('/\D+/', '', $number) ?: '';
    if ($digits === '') {
        return '';
    }
    return 'https://wa.me/' . $digits;
}

function qr_download_png(string $payload, string $target): bool {
    if ($payload === '') {
        return false;
    }
    $scheme = extension_loaded('openssl') ? 'https' : 'http';
    $url = $scheme . '://api.qrserver.com/v1/create-qr-code/?size=600x600&margin=20&data=' . rawurlencode($payload);
    $bytes = false;
    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_CONNECTTIMEOUT => 8,
            CURLOPT_TIMEOUT => 20,
            CURLOPT_SSL_VERIFYPEER => $scheme === 'https',
        ]);
        $bytes = curl_exec($ch);
        $code = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        curl_close($ch);
        if ($code < 200 || $code >= 300) {
            $bytes = false;
        }
    }
    if ($bytes === false) {
        $ctx = stream_context_create([
            'http' => ['timeout' => 20],
            'ssl' => ['verify_peer' => true, 'verify_peer_name' => true],
        ]);
        $bytes = @file_get_contents($url, false, $ctx);
    }
    if (!is_string($bytes) || strlen($bytes) < 100) {
        return false;
    }
    $dir = dirname($target);
    if (!is_dir($dir)) {
        mkdir($dir, 0775, true);
    }
    return file_put_contents($target, $bytes, LOCK_EX) !== false;
}

qr_ensure_columns($db);
if (empty($_SESSION['csrf_qrcode'])) {
    $_SESSION['csrf_qrcode'] = bin2hex(random_bytes(16));
}

$alert = '';
$alertType = 'success';
$qrPath = dirname(__DIR__) . '/api/img/qrcode.png';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $csrf = (string)($_POST['csrf'] ?? '');
    if (!hash_equals((string)$_SESSION['csrf_qrcode'], $csrf)) {
        $alert = 'Sessão expirada. Recarregue a página e tente novamente.';
        $alertType = 'danger';
    } else {
        $enabled = isset($_POST['qrcode_app_enabled']) ? 1 : 0;
        $whatsapp = trim((string)($_POST['qrcode_whatsapp'] ?? ''));
        $link = qr_build_whatsapp_url($whatsapp);
        if ($link === '' && $enabled === 1) {
            $alert = 'Informe um número de WhatsApp válido com DDI e DDD.';
            $alertType = 'danger';
        } elseif ($link !== '' && !qr_download_png($link, $qrPath)) {
            $alert = 'Não foi possível gerar a imagem do QR Code agora. Verifique a internet do servidor.';
            $alertType = 'danger';
        } else {
            $db->prepare("UPDATE app_config SET qrcode_app_enabled=?, qrcode_whatsapp=?, qrcode_url=?, updated_at=datetime('now') WHERE id=1")
                ->execute([$enabled, $whatsapp, $link]);
            $alert = $enabled === 1 ? 'QR Code de suporte ativado e atualizado com sucesso.' : 'QR Code de suporte desativado no aplicativo.';
        }
    }
}

$cfg = $db->query('SELECT qrcode_app_enabled, qrcode_whatsapp, qrcode_url FROM app_config WHERE id=1 LIMIT 1')->fetch(PDO::FETCH_ASSOC) ?: [
    'qrcode_app_enabled' => 1,
    'qrcode_whatsapp' => '',
    'qrcode_url' => '',
];

include './includes/header.php';
?>
<div class="card radius-10">
    <div class="card-body">
        <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-3">
            <div>
                <h4 class="mb-1">QR Code do WhatsApp</h4>
                <p class="text-muted mb-0">A imagem gerada fica em <code>/api/img/qrcode.png</code> e é usada pelos apps.</p>
            </div>
            <?php if (is_file($qrPath)): ?>
                <img src="api/img/qrcode.png?v=<?= time() ?>" alt="QR Code" style="width:96px;height:96px;border-radius:16px;background:#fff;padding:6px;">
            <?php endif; ?>
        </div>

        <?php if ($alert): ?>
            <div class="alert alert-<?= htmlspecialchars($alertType) ?>"><?= htmlspecialchars($alert) ?></div>
        <?php endif; ?>

        <form method="post" class="row g-3">
            <input type="hidden" name="csrf" value="<?= htmlspecialchars((string)$_SESSION['csrf_qrcode']) ?>">
            <div class="col-12 col-lg-7">
                <label class="form-label" for="qrcode_whatsapp">Número do WhatsApp</label>
                <input
                    class="form-control"
                    id="qrcode_whatsapp"
                    name="qrcode_whatsapp"
                    placeholder="Ex: 5511999999999"
                    value="<?= htmlspecialchars((string)($cfg['qrcode_whatsapp'] ?? '')) ?>"
                    inputmode="tel"
                    autocomplete="tel">
            </div>
            <div class="col-12 col-lg-5">
                <label class="form-label">Link atual</label>
                <input class="form-control" value="<?= htmlspecialchars((string)($cfg['qrcode_url'] ?? '')) ?>" readonly>
            </div>
            <div class="col-12">
                <div class="form-check form-switch">
                    <input class="form-check-input" type="checkbox" name="qrcode_app_enabled" id="qr" <?= ((int)($cfg['qrcode_app_enabled'] ?? 1) === 1) ? 'checked' : '' ?>>
                    <label for="qr" class="form-check-label">Ativar QR Code de suporte no aplicativo</label>
                </div>
            </div>
            <div class="col-12">
                <button class="btn btn-primary" type="submit">Salvar e gerar QR Code</button>
            </div>
        </form>
    </div>
</div>
<?php include './includes/footer.php'; ?>
