<?php
declare(strict_types=1);

session_start();
date_default_timezone_set('America/Sao_Paulo');

if (empty($_SESSION["panel_user"]) || !is_string($_SESSION["panel_user"])) {
    header("Location: index.php");
    exit;
}

$dbPath = dirname(__DIR__) . "/api/db.db";

if (!is_file($dbPath)) {
    session_destroy();
    header("Location: index.php");
    exit;
}

try {
    $db = new PDO("sqlite:" . $dbPath, null, null, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]);
} catch (Throwable $e) {
    session_destroy();
    header("Location: index.php");
    exit;
}

require_once dirname(__DIR__) . "/includes/revenda_schema.php";
revenda_ensure_schema($db);

$usernameSess = trim((string)($_SESSION["panel_user"] ?? ""));
$tipoUser = trim((string)($_SESSION["tipo_user"] ?? ""));

if ($usernameSess === "" || strlen($usernameSess) > 80) {
    session_destroy();
    header("Location: index.php");
    exit;
}

$isAdmin = ($tipoUser === "admin");
$isRev = ($tipoUser === "revendedor");

$success = false;
$errorMsg = "";

$identityMsg = "";
$identitySuccess = false;
$panelIdentityPath = dirname(__DIR__) . "/api/panel_identity.json";
$panelLogoPath = dirname(__DIR__) . "/api/img/logo.png";
$panelNameConfig = "THEFULL TV";

if (is_file($panelIdentityPath)) {
    $panelIdentityRaw = @file_get_contents($panelIdentityPath);
    $panelIdentity = json_decode((string)$panelIdentityRaw, true);

    if (is_array($panelIdentity) && isset($panelIdentity["name"])) {
        $candidatePanelName = trim((string)$panelIdentity["name"]);
        if ($candidatePanelName !== "") {
            $panelNameConfig = $candidatePanelName;
        }
    }
}

$panel_id = 0;
$name_header = $usernameSess;
$user = null;

if ($isAdmin) {
    $stmt = $db->prepare("SELECT id, username, password FROM panel_users WHERE username = ? LIMIT 1");
    $stmt->execute([$usernameSess]);
    $user = $stmt->fetch();

    if (!$user) {
        session_destroy();
        header("Location: index.php");
        exit;
    }

    $panel_id = (int)($user["id"] ?? 0);
    $name_header = (string)($user["username"] ?? $usernameSess);
}

if ($isRev) {
    $stmt = $db->prepare("SELECT id, username, password, status, nome, whatsapp FROM revendedores WHERE username = ? LIMIT 1");
    $stmt->execute([$usernameSess]);
    $user = $stmt->fetch();

    if (!$user) {
        session_destroy();
        header("Location: index.php");
        exit;
    }

    $status = trim((string)($user["status"] ?? ""));
    if ($status !== "" && $status !== "ativo") {
        session_destroy();
        header("Location: index.php");
        exit;
    }

    $panel_id = (int)($user["id"] ?? 0);
    $name_header = (string)($user["username"] ?? $usernameSess);
}

if (!$isAdmin && !$isRev) {
    session_destroy();
    header("Location: index.php");
    exit;
}

function checkPasswordCompat(string $senhaInformada, string $senhaBanco): bool
{
    $senhaBanco = (string)$senhaBanco;

    if ($senhaBanco === "") {
        return false;
    }

    $info = password_get_info($senhaBanco);

    if (!empty($info["algo"]) && (int)$info["algo"] !== 0) {
        return password_verify($senhaInformada, $senhaBanco);
    }

    if (strlen($senhaBanco) === 32 && ctype_xdigit($senhaBanco)) {
        return hash_equals(strtolower($senhaBanco), md5($senhaInformada));
    }

    return hash_equals($senhaBanco, $senhaInformada);
}

if ($isAdmin && $_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["save_panel_identity"])) {
    $novoNomePainel = trim((string)($_POST["panel_name"] ?? ""));

    if ($novoNomePainel === "") {
        $identityMsg = "Informe o nome do painel.";
    } elseif (strlen($novoNomePainel) > 80) {
        $identityMsg = "Nome do painel muito longo.";
    } else {
        $logoOk = true;

        if (isset($_FILES["panel_logo"]) && is_array($_FILES["panel_logo"]) && (int)($_FILES["panel_logo"]["error"] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE) {
            if ((int)$_FILES["panel_logo"]["error"] !== UPLOAD_ERR_OK) {
                $logoOk = false;
                $identityMsg = "Erro ao enviar a logotipo.";
            } else {
                $ext = strtolower(pathinfo((string)($_FILES["panel_logo"]["name"] ?? ""), PATHINFO_EXTENSION));
                $allowed = ["png", "jpg", "jpeg", "webp", "gif"];
                $tmp = (string)($_FILES["panel_logo"]["tmp_name"] ?? "");

                if (!in_array($ext, $allowed, true) || $tmp === "" || !is_uploaded_file($tmp)) {
                    $logoOk = false;
                    $identityMsg = "Formato de logotipo inválido.";
                } else {
                    if (!is_dir(dirname($panelLogoPath))) {
                        @mkdir(dirname($panelLogoPath), 0755, true);
                    }

                    if (!move_uploaded_file($tmp, $panelLogoPath)) {
                        $logoOk = false;
                        $identityMsg = "Não foi possível salvar a logotipo.";
                    }
                }
            }
        }

        if ($logoOk) {
            if (!is_dir(dirname($panelIdentityPath))) {
                @mkdir(dirname($panelIdentityPath), 0755, true);
            }

            $payloadIdentity = [
                "name" => $novoNomePainel,
                "updated_at" => time()
            ];

            if (@file_put_contents($panelIdentityPath, json_encode($payloadIdentity, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)) !== false) {
                $panelNameConfig = $novoNomePainel;
                $identitySuccess = true;
                $identityMsg = "Identidade do painel salva com sucesso.";
            } else {
                $identityMsg = "Não foi possível salvar o nome do painel.";
            }
        }
    }
}

if ($isAdmin && $_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["save_admin_pass"])) {
    $senha_atual = trim((string)($_POST["senha_atual"] ?? ""));
    $nova_senha = trim((string)($_POST["nova_senha"] ?? ""));
    $confirmar_senha = trim((string)($_POST["confirmar_senha"] ?? ""));

    if ($senha_atual === "" || $nova_senha === "" || $confirmar_senha === "") {
        $errorMsg = "Preencha todos os campos.";
    } elseif (strlen($nova_senha) < 4) {
        $errorMsg = "Senha muito curta.";
    } elseif ($nova_senha !== $confirmar_senha) {
        $errorMsg = "As senhas não coincidem.";
    } else {
        $st = $db->prepare("SELECT id, username, password FROM panel_users WHERE id=? LIMIT 1");
        $st->execute([$panel_id]);
        $adminRow = $st->fetch();

        if (!$adminRow) {
            $errorMsg = "Conta não encontrada.";
        } else {
            $senha_banco = (string)($adminRow["password"] ?? "");

            if (!checkPasswordCompat($senha_atual, $senha_banco)) {
                $errorMsg = "Senha atual incorreta.";
            } else {
                $novaHash = password_hash($nova_senha, PASSWORD_DEFAULT);
                $up = $db->prepare("UPDATE panel_users SET password=? WHERE id=?");

                if ($up->execute([$novaHash, $panel_id])) {
                    $success = true;
                } else {
                    $errorMsg = "Erro ao salvar.";
                }
            }
        }
    }
}

if ($isRev && $_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["save_rev_pass"])) {
    $novo_login = trim((string)($_POST["novo_login"] ?? ""));
    $novo_nome = trim((string)($_POST["novo_nome"] ?? ""));
    $novo_whatsapp = preg_replace('/\D+/', '', (string)($_POST["novo_whatsapp"] ?? ""));
    $senha_atual = trim((string)($_POST["senha_atual"] ?? ""));
    $nova_senha = trim((string)($_POST["nova_senha"] ?? ""));
    $confirmar_senha = trim((string)($_POST["confirmar_senha"] ?? ""));

    if ($novo_login === "" || $novo_nome === "") {
        $errorMsg = "Informe login e nome.";
    } elseif (!preg_match('/^[A-Za-z0-9_.-]{3,60}$/', $novo_login)) {
        $errorMsg = "Login inválido. Use letras, números, ponto, hífen ou underline.";
    } elseif (strlen($novo_nome) > 80) {
        $errorMsg = "Nome muito longo.";
    } elseif (($nova_senha !== "" || $confirmar_senha !== "" || $senha_atual !== "") && $nova_senha !== $confirmar_senha) {
        $errorMsg = "As senhas não coincidem.";
    } elseif ($nova_senha !== "" && strlen($nova_senha) < 4) {
        $errorMsg = "Senha muito curta.";
    } else {
        $st = $db->prepare("SELECT id, username, password FROM revendedores WHERE id=? LIMIT 1");
        $st->execute([$panel_id]);
        $revRow = $st->fetch();

        if (!$revRow) {
            $errorMsg = "Conta não encontrada.";
        } else {
            $stCheck = $db->prepare("SELECT id FROM revendedores WHERE lower(username)=lower(?) AND id<>? LIMIT 1");
            $stCheck->execute([$novo_login, $panel_id]);
            $exists = $stCheck->fetch();

            if ($exists) {
                $errorMsg = "Esse login já está em uso.";
            } else {
                $senhaSql = "";
                $params = [$novo_login, $novo_nome, $novo_whatsapp, $panel_id];

                if ($nova_senha !== "") {
                    if ($senha_atual === "") {
                        $errorMsg = "Informe a senha atual para trocar a senha.";
                    } elseif (!checkPasswordCompat($senha_atual, (string)($revRow["password"] ?? ""))) {
                        $errorMsg = "Senha atual incorreta.";
                    } else {
                        $senhaSql = ", password=?";
                        $params = [$novo_login, $novo_nome, $novo_whatsapp, password_hash($nova_senha, PASSWORD_DEFAULT), $panel_id];
                    }
                }

                if ($errorMsg === "") {
                    $sql = "UPDATE revendedores SET username=?, nome=?, whatsapp=?" . $senhaSql . ", updated_at=strftime('%s','now') WHERE id=?";
                    $up = $db->prepare($sql);
                    if ($up->execute($params)) {
                        $_SESSION["panel_user"] = $novo_login;
                        $success = true;
                        $name_header = $novo_login;
                        $user["username"] = $novo_login;
                        $user["nome"] = $novo_nome;
                        $user["whatsapp"] = $novo_whatsapp;
                    } else {
                        $errorMsg = "Erro ao salvar.";
                    }
                }
            }
        }
    }
}

require_once __DIR__ . '/../includes/header.php';
?>
<div class="dns-wrap">
    <?php if ($isAdmin): ?>
        <div class="card radius-10 dns-card">
            <div class="card-header bg-transparent dns-header">
                <div class="dns-title">
                    <div class="ic"><i class="bi bi-tv-fill"></i></div>
                    <div>
                        <h5>Nome e logotipo do painel</h5>
                        <span>Esse nome e essa logotipo aparecem no menu e na tela de login</span>
                    </div>
                </div>

                <div class="dns-actions">
                    <span class="badge-soft"><i class="bi bi-palette-fill"></i> Identidade</span>
                </div>
            </div>

            <div class="card-body">
                <?php if ($identityMsg !== ""): ?>
                    <div class="alert <?= $identitySuccess ? "alert-success" : "alert-danger" ?> d-flex align-items-center gap-2">
                        <i class="bi <?= $identitySuccess ? "bi-check-circle-fill" : "bi-x-circle-fill" ?>"></i>
                        <div><?= htmlspecialchars($identityMsg, ENT_QUOTES, "UTF-8") ?></div>
                    </div>
                <?php endif; ?>

                <div class="logo-preview-box">
                    <img src="api/img/logo.png?v=<?= time() ?>" alt="Logo do painel">
                    <div>
                        <div class="name"><?= htmlspecialchars($panelNameConfig, ENT_QUOTES, "UTF-8") ?></div>
                        <div class="desc">Identidade atual do painel</div>
                    </div>
                </div>

                <form method="post" enctype="multipart/form-data" autocomplete="off" class="row g-3">
                    <input type="hidden" name="save_panel_identity" value="1">

                    <div class="col-lg-6 col-md-6 col-12">
                        <label class="form-label fw-900">Nome do painel</label>
                        <input type="text" name="panel_name" class="form-control input-radius" value="<?= htmlspecialchars($panelNameConfig, ENT_QUOTES, "UTF-8") ?>" maxlength="40" required>
                    </div>

                    <div class="col-lg-6 col-md-6 col-12">
                        <label class="form-label fw-900">Logotipo do painel</label>
                        <input type="file" name="panel_logo" class="form-control input-radius" accept=".png,.jpg,.jpeg,.webp,.gif">
                    </div>

                    <div class="col-12">
                        <div class="form-actions">
                            <button type="submit" class="btn btn-success save-btn">
                                <i class="bi bi-save2"></i> Salvar painel
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    <?php endif; ?>

    <div class="card radius-10 dns-card">
        <div class="card-header bg-transparent dns-header">
            <div class="dns-title">
                <div class="ic"><i class="bi bi-shield-lock-fill"></i></div>
                <div>
                    <h5><?= $isRev ? "Minha Conta (Revenda)" : "Editar senha do Admin" ?></h5>
                    <span><?= $isRev ? "Atualize login, nome, WhatsApp e senha de acesso" : "Altere com segurança a senha do painel" ?></span>
                </div>
            </div>

            <div class="dns-actions">
                <span class="badge-soft"><i class="bi bi-lock-fill"></i> Seguro</span>
            </div>
        </div>

        <div class="card-body">
            <?php if ($success): ?>
                <div class="alert alert-success d-flex align-items-center gap-2">
                    <i class="bi bi-check-circle-fill"></i>
                    <div>Alterações salvas com sucesso.</div>
                </div>
            <?php elseif (!empty($errorMsg)): ?>
                <div class="alert alert-danger d-flex align-items-center gap-2">
                    <i class="bi bi-x-circle-fill"></i>
                    <div><?= htmlspecialchars($errorMsg, ENT_QUOTES, "UTF-8") ?></div>
                </div>
            <?php endif; ?>

            <?php if ($isAdmin): ?>
                <form method="post" autocomplete="off" class="row g-3">
                    <input type="hidden" name="save_admin_pass" value="1">

                    <div class="col-lg-4 col-md-4 col-12">
                        <label class="form-label fw-900">Senha atual</label>
                        <input type="password" name="senha_atual" class="form-control input-radius" required>
                    </div>

                    <div class="col-lg-4 col-md-4 col-12">
                        <label class="form-label fw-900">Nova senha</label>
                        <input type="password" name="nova_senha" class="form-control input-radius" required>
                    </div>

                    <div class="col-lg-4 col-md-4 col-12">
                        <label class="form-label fw-900">Confirmar nova senha</label>
                        <input type="password" name="confirmar_senha" class="form-control input-radius" required>
                    </div>

                    <div class="col-12">
                        <div class="form-actions">
                            <a href="dashboard.php" class="btn btn-secondary back-btn">
                                <i class="bi bi-arrow-left"></i> Voltar
                            </a>

                            <button type="submit" class="btn btn-success save-btn">
                                <i class="bi bi-save2"></i> Salvar senha
                            </button>
                        </div>
                    </div>
                </form>
            <?php endif; ?>

            <?php if ($isRev): ?>
                <form method="post" autocomplete="off" class="row g-3">
                    <input type="hidden" name="save_rev_pass" value="1">

                    <div class="col-lg-3 col-md-6 col-12">
                        <label class="form-label fw-900">Login</label>
                        <input type="text" name="novo_login" class="form-control input-radius" value="<?= htmlspecialchars((string)($user['username'] ?? $name_header), ENT_QUOTES, "UTF-8") ?>" required>
                    </div>

                    <div class="col-lg-3 col-md-6 col-12">
                        <label class="form-label fw-900">Nome</label>
                        <input type="text" name="novo_nome" class="form-control input-radius" value="<?= htmlspecialchars((string)($user['nome'] ?? ''), ENT_QUOTES, "UTF-8") ?>" required>
                    </div>

                    <div class="col-lg-3 col-md-6 col-12">
                        <label class="form-label fw-900">WhatsApp</label>
                        <input type="text" name="novo_whatsapp" class="form-control input-radius" value="<?= htmlspecialchars((string)($user['whatsapp'] ?? ''), ENT_QUOTES, "UTF-8") ?>" placeholder="5511999999999">
                    </div>

                    <div class="col-lg-3 col-md-6 col-12">
                        <label class="form-label fw-900">Senha atual</label>
                        <input type="password" name="senha_atual" class="form-control input-radius" placeholder="Só se trocar senha">
                    </div>

                    <div class="col-lg-6 col-md-6 col-12">
                        <label class="form-label fw-900">Nova senha</label>
                        <input type="password" name="nova_senha" class="form-control input-radius" placeholder="Opcional">
                    </div>

                    <div class="col-lg-6 col-md-6 col-12">
                        <label class="form-label fw-900">Confirmar nova senha</label>
                        <input type="password" name="confirmar_senha" class="form-control input-radius" placeholder="Opcional">
                    </div>

                    <div class="col-12">
                        <div class="form-actions">
                            <a href="dashboard.php" class="btn btn-secondary back-btn">
                                <i class="bi bi-arrow-left"></i> Voltar
                            </a>

                            <button type="submit" class="btn btn-success save-btn">
                                <i class="bi bi-save2"></i> Salvar alterações
                            </button>
                        </div>
                    </div>
                </form>
            <?php endif; ?>
        </div>
    </div>
</div>

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