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

if (isset($_GET["app_config"])) {
    header('Content-Type: application/json; charset=utf-8');
    try {
        require_once dirname(__DIR__) . '/api/_auth_common.php';
        require_once dirname(__DIR__) . '/includes/revenda_schema.php';
        $dbQr = new PDO('sqlite:' . dirname(__DIR__) . '/api/db.db');
        $dbQr->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $dbQr->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        auth_ensure_schema($dbQr);
        revenda_ensure_schema($dbQr);
        foreach ([
            'qrcode_app_enabled' => 'INTEGER DEFAULT 1',
            'qrcode_whatsapp' => "TEXT DEFAULT ''",
            'qrcode_url' => "TEXT DEFAULT ''",
            'updated_at' => 'DATETIME',
        ] as $col => $type) {
            $cols = $dbQr->query('PRAGMA table_info(app_config)')->fetchAll(PDO::FETCH_ASSOC);
            $has = false;
            foreach ($cols as $c) { if (($c['name'] ?? '') === $col) { $has = true; break; } }
            if (!$has) $dbQr->exec("ALTER TABLE app_config ADD COLUMN {$col} {$type}");
        }
        $ownerId = max(0, (int)($_GET['owner_id'] ?? $_GET['revendedor_id'] ?? 0));
        $cfg = $dbQr->query('SELECT qrcode_app_enabled, qrcode_whatsapp, qrcode_url FROM app_config WHERE id=1 LIMIT 1')->fetch(PDO::FETCH_ASSOC) ?: [];
        $whats = '';
        if ($ownerId > 0) {
            $st = $dbQr->prepare('SELECT whatsapp FROM revendedores WHERE id=? LIMIT 1');
            $st->execute([$ownerId]);
            $rw = $st->fetch(PDO::FETCH_ASSOC) ?: [];
            $whats = preg_replace('/\D+/', '', (string)($rw['whatsapp'] ?? '')) ?: '';
        }
        if ($whats === '') {
            $whats = preg_replace('/\D+/', '', (string)($cfg['qrcode_whatsapp'] ?? '')) ?: '';
        }
        if ($whats === '') {
            $rw = $dbQr->query("SELECT whatsapp FROM revendedores WHERE trim(COALESCE(whatsapp,''))<>'' ORDER BY id ASC LIMIT 1")->fetch(PDO::FETCH_ASSOC) ?: [];
            $whats = preg_replace('/\D+/', '', (string)($rw['whatsapp'] ?? '')) ?: '';
        }
        $payload = $whats !== '' ? 'https://wa.me/' . $whats : trim((string)($cfg['qrcode_url'] ?? ''));
        echo json_encode([
            'status' => 'ok',
            'enabled' => ((int)($cfg['qrcode_app_enabled'] ?? 1) === 1),
            'whatsapp' => $whats,
            'qrcode_url' => trim((string)($cfg['qrcode_url'] ?? '')),
            'qrcode_payload' => $payload,
            'owner_id' => $ownerId,
        ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    } catch (Throwable $e) {
        echo json_encode(['status'=>'error','enabled'=>false,'message'=>'qrcode_config_error'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    }
    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_first_registered_whatsapp(PDO $db): string {
    try {
        $row = $db->query("SELECT qrcode_whatsapp FROM app_config WHERE id=1 LIMIT 1")->fetch(PDO::FETCH_ASSOC) ?: [];
        $digits = preg_replace('/\D+/', '', (string)($row['qrcode_whatsapp'] ?? '')) ?: '';
        if ($digits !== '') return $digits;
        $row = $db->query("SELECT whatsapp FROM revendedores WHERE trim(COALESCE(whatsapp,''))<>'' ORDER BY id ASC LIMIT 1")->fetch(PDO::FETCH_ASSOC) ?: [];
        $digits = preg_replace('/\D+/', '', (string)($row['whatsapp'] ?? '')) ?: '';
        return $digits;
    } catch (Throwable $e) { return ''; }
}

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'] ?? ''));
        if ($whatsapp === '') $whatsapp = qr_first_registered_whatsapp($db);
        $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';
        } else {
            $imageGenerated = true;
            if ($link !== '') {
                $imageGenerated = qr_download_png($link, $qrPath);
            }
            $db->prepare("UPDATE app_config SET qrcode_app_enabled=?, qrcode_whatsapp=?, qrcode_url=?, updated_at=datetime('now') WHERE id=1")
                ->execute([$enabled, $whatsapp, $link]);
            if ($enabled === 1 && !$imageGenerated) {
                $alert = 'Número salvo com sucesso. O app vai gerar o QR Code localmente; só a imagem api/img/qrcode.png não pôde ser recriada agora no servidor.';
                $alertType = 'warning';
            } else {
                $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' => '',
];
$cfgFallbackWhatsapp = qr_first_registered_whatsapp($db);
if (trim((string)($cfg['qrcode_whatsapp'] ?? '')) === '' && $cfgFallbackWhatsapp !== '') {
    $cfg['qrcode_whatsapp'] = $cfgFallbackWhatsapp;
    $cfg['qrcode_url'] = qr_build_whatsapp_url($cfgFallbackWhatsapp);
}

require_once __DIR__ . '/../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>
               
            </div>
            <?php if (is_file($qrPath)): ?>
                <img src="api/img/qrcode.png?v=<?= time() ?>" alt="QR Code" class="qrcode-preview">
            <?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 require_once __DIR__ . '/../includes/footer.php'; ?>
