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

$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 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_nome = trim((string)($_POST["novo_nome"] ?? ""));
    $senha_atual = trim((string)($_POST["senha_atual"] ?? ""));
    $nova_senha = trim((string)($_POST["nova_senha"] ?? ""));
    $confirmar_senha = trim((string)($_POST["confirmar_senha"] ?? ""));

    if ($novo_nome === "" || $senha_atual === "" || $nova_senha === "" || $confirmar_senha === "") {
        $errorMsg = "Preencha todos os campos.";
    } elseif (strlen($novo_nome) < 3) {
        $errorMsg = "Nome muito curto.";
    } elseif (strlen($novo_nome) > 60) {
        $errorMsg = "Nome muito longo.";
    } 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 revendedores WHERE id=? LIMIT 1");
        $st->execute([$panel_id]);
        $revRow = $st->fetch();

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

            if (!checkPasswordCompat($senha_atual, $senha_banco)) {
                $errorMsg = "Senha atual incorreta.";
            } else {
                $stCheck = $db->prepare("SELECT id FROM revendedores WHERE lower(username)=lower(?) AND id<>? LIMIT 1");
                $stCheck->execute([$novo_nome, $panel_id]);
                $exists = $stCheck->fetch();

                if ($exists) {
                    $errorMsg = "Esse nome já está em uso.";
                } else {
                    $novaHash = password_hash($nova_senha, PASSWORD_DEFAULT);
                    $up = $db->prepare("UPDATE revendedores SET username=?, password=? WHERE id=?");

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

include "./includes/header.php";
?>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">

<style>
.dns-wrap{
    width:100%;
    max-width:none;
    margin:0;
    padding:0 18px;
}
.dns-card{
    border-radius:18px;
    overflow:hidden;
    width:100%;
    margin-bottom:18px;
}
.dns-header{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:14px;
    padding:18px 22px;
}
.dns-title{
    display:flex;
    align-items:center;
    gap:14px;
}
.dns-title .ic{
    width:44px;
    height:44px;
    min-width:44px;
    border-radius:14px;
    background:rgba(25,135,84,.10);
    border:1px solid rgba(25,135,84,.20);
    display:flex;
    align-items:center;
    justify-content:center;
}
.dns-title .ic i{
    font-size:24px;
    color:#198754;
}
.dns-title h5{
    margin:0;
    font-weight:900;
}
.dns-title span{
    display:block;
    margin-top:3px;
    font-size:13px;
    color:rgba(255,255,255,.55);
}
.badge-soft{
    display:inline-flex;
    align-items:center;
    gap:7px;
    padding:8px 12px;
    border-radius:999px;
    background:rgba(25,135,84,.10);
    border:1px solid rgba(25,135,84,.20);
    color:#198754;
    font-weight:900;
    white-space:nowrap;
}
.input-radius{
    border-radius:14px !important;
    min-height:48px;
}
.save-btn{
    border-radius:14px;
    min-height:46px;
    font-weight:900;
    padding-left:22px;
    padding-right:22px;
}
.back-btn{
    border-radius:14px;
    min-height:46px;
    font-weight:900;
    padding-left:22px;
    padding-right:22px;
}
.logo-preview-box{
    display:flex;
    align-items:center;
    gap:14px;
    padding:14px;
    border-radius:16px;
    background:rgba(0,0,0,.03);
    border:1px solid rgba(0,0,0,.08);
    margin-bottom:16px;
}
.logo-preview-box img{
    width:72px;
    height:72px;
    min-width:72px;
    object-fit:cover;
    border-radius:18px;
    border:1px solid rgba(255,255,255,.25);
    background:rgba(255,255,255,.08);
}
.logo-preview-box .name{
    font-weight:900;
    font-size:16px;
}
.logo-preview-box .desc{
    font-size:13px;
    color:rgba(255,255,255,.55);
}
.alert{
    border-radius:14px;
}
.form-actions{
    display:flex;
    align-items:center;
    justify-content:flex-end;
    gap:10px;
    flex-wrap:wrap;
    margin-top:4px;
}
@media(max-width:575px){
    .dns-wrap{
        padding:0 8px;
    }
    .dns-header{
        align-items:flex-start;
        padding:16px;
    }
    .dns-title .ic{
        width:40px;
        height:40px;
        min-width:40px;
    }
    .dns-title .ic i{
        font-size:22px;
    }
    .dns-title h5{
        font-size:18px;
    }
    .badge-soft{
        padding:7px 10px;
        font-size:12px;
    }
    .save-btn,
    .back-btn{
        width:100%;
    }
    .form-actions{
        display:block;
    }
    .form-actions .btn{
        margin-top:8px;
    }
    .logo-preview-box{
        align-items:flex-start;
    }
}
</style>

<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" style="font-weight: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" style="font-weight: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 seu nome 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" style="font-weight: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" style="font-weight: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" style="font-weight: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" style="font-weight:900;">Meu nome (login)</label>
                        <input type="text" name="novo_nome" class="form-control input-radius" value="<?= htmlspecialchars($name_header, ENT_QUOTES, "UTF-8") ?>" required>
                    </div>

                    <div class="col-lg-3 col-md-6 col-12">
                        <label class="form-label" style="font-weight:900;">Senha atual</label>
                        <input type="password" name="senha_atual" class="form-control input-radius" required>
                    </div>

                    <div class="col-lg-3 col-md-6 col-12">
                        <label class="form-label" style="font-weight:900;">Nova senha</label>
                        <input type="password" name="nova_senha" class="form-control input-radius" required>
                    </div>

                    <div class="col-lg-3 col-md-6 col-12">
                        <label class="form-label" style="font-weight: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 alterações
                            </button>
                        </div>
                    </div>
                </form>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php include "./includes/footer.php"; ?>