:root {
    color-scheme: light;
    --bg: #f5f7f6;
    --surface: #ffffff;
    --surface-strong: #e7f0ef;
    --text: #17211f;
    --muted: #667370;
    --line: #d9e2df;
    --primary: #116466;
    --primary-dark: #0b4c4d;
    --accent: #c88a32;
    --danger: #b34040;
    --success-bg: #edf8f1;
    --warning-bg: #fff8e9;
    --danger-bg: #fff1f1;
    --shadow: 0 12px 30px rgba(17, 100, 102, 0.13);
}

* {
    box-sizing: border-box;
}

body {
    margin: 0;
    min-height: 100vh;
    background: var(--bg);
    color: var(--text);
    font-family: Arial, Helvetica, sans-serif;
}

button {
    border: 1px solid var(--line);
    border-radius: 8px;
    background: var(--surface);
    color: var(--primary-dark);
    cursor: pointer;
    font: inherit;
    font-size: 13px;
    font-weight: 700;
    min-height: 34px;
    padding: 0 12px;
}

select,
input,
textarea {
    width: 100%;
    border: 1px solid var(--line);
    border-radius: 8px;
    background: var(--surface);
    color: var(--text);
    font: inherit;
    font-size: 13px;
    min-height: 36px;
    padding: 8px 10px;
}

a {
    color: inherit;
    text-decoration: none;
}

.admin-shell {
    display: grid;
    grid-template-columns: 200px minmax(0, 1fr);
    min-height: 100vh;
}

.admin-sidebar {
    position: sticky;
    top: 0;
    height: 100vh;
    display: flex;
    flex-direction: column;
    gap: 10px;
    border-right: 1px solid var(--line);
    background: var(--surface);
    padding: 12px 10px;
}

.admin-brand {
    display: grid;
    gap: 2px;
    padding: 2px 6px 8px;
}

.admin-brand span,
.admin-topbar span,
.panel-head span {
    color: var(--primary);
    font-size: 11px;
    font-weight: 800;
    letter-spacing: 0;
}

.admin-brand strong {
    color: var(--text);
    font-size: 18px;
    line-height: 1.05;
}

.admin-nav {
    display: grid;
    gap: 2px;
}

.admin-nav a {
    display: grid;
    grid-template-columns: 20px minmax(0, 1fr);
    align-items: center;
    gap: 8px;
    border-radius: 8px;
    color: var(--muted);
    font-size: 13px;
    font-weight: 700;
    min-height: 36px;
    padding: 0 10px;
}

.admin-nav a.is-active,
.admin-nav a:hover {
    background: var(--surface-strong);
    color: var(--primary-dark);
}

.admin-nav svg {
    width: 17px;
    height: 17px;
    justify-self: center;
    fill: none;
    stroke: currentColor;
    stroke-linecap: round;
    stroke-linejoin: round;
    stroke-width: 2;
}

.empty-state svg {
    width: 20px;
    height: 20px;
    fill: none;
    stroke: currentColor;
    stroke-linecap: round;
    stroke-linejoin: round;
    stroke-width: 2;
}

.admin-sidebar-footer {
    margin-top: auto;
    display: grid;
    gap: 6px;
    border-top: 1px solid var(--line);
    padding-top: 8px;
}

.admin-sidebar-footer form {
    display: grid;
}

.admin-logout-button {
    width: 100%;
    border-color: #fecaca;
    background: #fff1f2;
    color: #991b1b;
}

.admin-main {
    min-width: 0;
    padding: 14px;
}

.admin-topbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 16px;
    margin-bottom: 14px;
}

.admin-topbar h1,
.panel-head h2 {
    margin: 2px 0 0;
}

.admin-topbar h1 {
    font-size: 22px;
}

.admin-topbar-actions {
    display: flex;
    gap: 8px;
}

.primary-action {
    border-color: var(--primary);
    background: var(--primary);
    color: #fff;
}

.admin-grid {
    display: grid;
    grid-template-columns: repeat(4, minmax(0, 1fr));
    gap: 10px;
    margin-bottom: 12px;
}

.metric-card,
.admin-panel {
    border: 1px solid var(--line);
    border-radius: 8px;
    background: var(--surface);
    box-shadow: var(--shadow);
}

.metric-card {
    display: grid;
    gap: 4px;
    min-height: 84px;
    padding: 12px;
}

.metric-card.warning {
    background: var(--warning-bg);
}

.metric-card.danger {
    background: var(--danger-bg);
}

.metric-card span,
.metric-card small,
.timeline-item small,
.empty-state span,
.setting-list span,
.admin-help-text,
.update-status-card p,
.admin-form-field span {
    color: var(--muted);
}

.metric-card strong {
    font-size: 24px;
    line-height: 1;
}

.admin-content {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 12px;
}

.admin-section-hidden {
    display: none !important;
}

.admin-content[data-admin-tabs] > .admin-panel:not(.admin-section-hidden) {
    grid-column: 1 / -1;
}

.admin-panel {
    min-width: 0;
    padding: 12px;
}

.admin-panel.wide {
    grid-column: 1 / -1;
}

.panel-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
    margin-bottom: 10px;
}

.panel-head h2 {
    font-size: 16px;
}

.admin-table {
    display: grid;
    border: 1px solid var(--line);
    border-radius: 8px;
    overflow: hidden;
    font-size: 13px;
}

.admin-table-row {
    display: grid;
    grid-template-columns: 1.4fr 1fr 0.8fr 0.9fr;
    gap: 8px;
    min-height: 38px;
    align-items: center;
    padding: 0 10px;
}

.admin-table-row + .admin-table-row {
    border-top: 1px solid var(--line);
}

.admin-table-row.head {
    background: var(--surface-strong);
    color: var(--primary-dark);
    font-weight: 800;
}

.muted-row {
    color: var(--muted);
}

.timeline-list,
.setting-list {
    display: grid;
    gap: 8px;
}

.timeline-item {
    display: grid;
    grid-template-columns: auto minmax(0, 1fr);
    gap: 10px;
    align-items: start;
    border: 1px solid var(--line);
    border-radius: 8px;
    padding: 10px;
    font-size: 13px;
}

.status-dot {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    background: var(--accent);
    margin-top: 4px;
}

.status-dot.muted {
    background: var(--line);
}

.timeline-item div {
    display: grid;
    gap: 4px;
}

.empty-state {
    display: grid;
    place-items: center;
    gap: 6px;
    min-height: 130px;
    border: 1px dashed var(--line);
    border-radius: 8px;
    color: var(--muted);
    text-align: center;
    padding: 16px;
    font-size: 13px;
}

.empty-state strong {
    color: var(--text);
}

.setting-list div {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
    border: 1px solid var(--line);
    border-radius: 8px;
    min-height: 40px;
    padding: 0 10px;
    font-size: 13px;
}

.update-panel {
    display: grid;
    gap: 10px;
}

.admin-help-text {
    margin: 0;
    font-size: 12px;
    line-height: 1.5;
}

.update-status-card {
    display: grid;
    gap: 6px;
    border: 1px solid var(--line);
    border-radius: 8px;
    background: #fbfdfc;
    padding: 10px 12px;
}

.update-notice {
    display: grid;
    gap: 4px;
    border: 1px solid #b8dfc8;
    border-radius: 8px;
    background: #edf8f1;
    color: #14532d;
    padding: 10px 12px;
}

.update-notice.is-error {
    border-color: #fecaca;
    background: #fff1f2;
    color: #991b1b;
}

.update-notice span {
    font-size: 12px;
    line-height: 1.45;
}

.update-status-card p {
    margin: 0;
    font-size: 12px;
    line-height: 1.5;
}

.update-status-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
}

.status-badge {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-height: 22px;
    border-radius: 999px;
    background: var(--surface-strong);
    color: var(--primary-dark);
    font-size: 11px;
    font-weight: 800;
    padding: 0 10px;
    white-space: nowrap;
}

.update-form {
    display: grid;
    gap: 10px;
}

.admin-form-field {
    display: grid;
    gap: 5px;
}

.admin-form-field span {
    font-size: 12px;
    font-weight: 800;
}

.admin-form-checkbox {
    display: flex !important;
    flex-direction: row;
    align-items: center;
    gap: 8px;
}

.admin-form-checkbox input {
    width: auto;
    min-height: auto;
}

.update-checklist {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 6px;
}

.update-checklist div {
    display: flex;
    align-items: center;
    gap: 8px;
    border: 1px solid var(--line);
    border-radius: 8px;
    min-height: 36px;
    padding: 0 10px;
    color: var(--muted);
    font-size: 12px;
    font-weight: 700;
}

.update-actions {
    display: grid;
    grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
    gap: 8px;
}

.admin-login-shell {
    display: grid;
    place-items: center;
    min-height: 100vh;
    padding: 20px;
}

.admin-login-card {
    display: grid;
    gap: 10px;
    width: 100%;
    max-width: 340px;
    border: 1px solid var(--line);
    border-radius: 8px;
    background: var(--surface);
    box-shadow: var(--shadow);
    padding: 22px;
}

.admin-password-wrap {
    position: relative;
}

.admin-password-wrap input {
    width: 100%;
    padding-right: 42px;
}

.admin-password-toggle {
    position: absolute;
    top: 50%;
    right: 6px;
    display: grid;
    width: 30px;
    height: 30px;
    place-items: center;
    transform: translateY(-50%);
    border: 0;
    border-radius: 6px;
    background: transparent;
    color: var(--muted);
    cursor: pointer;
}

.admin-password-toggle.is-active {
    color: var(--primary);
}

.admin-password-toggle svg {
    width: 18px;
    height: 18px;
}

.admin-login-card .eyebrow {
    margin: 0;
    color: var(--primary);
    font-size: 11px;
    font-weight: 800;
}

.admin-login-card h1 {
    margin: 0 0 4px;
    font-size: 20px;
}

@media (max-width: 900px) {
    .admin-shell {
        grid-template-columns: 1fr;
    }

    .admin-sidebar {
        position: static;
        height: auto;
    }

    .admin-nav {
        grid-template-columns: repeat(3, minmax(0, 1fr));
    }

    .admin-sidebar-footer {
        margin-top: 0;
    }

    .admin-grid,
    .admin-content {
        grid-template-columns: repeat(2, minmax(0, 1fr));
    }
}

@media (max-width: 620px) {
    .admin-main,
    .admin-sidebar {
        padding: 14px;
    }

    .admin-topbar,
    .panel-head {
        align-items: stretch;
        flex-direction: column;
    }

    .admin-topbar-actions {
        display: grid;
        grid-template-columns: repeat(2, minmax(0, 1fr));
    }

    .admin-nav,
    .admin-grid,
    .admin-content,
    .update-checklist,
    .update-actions {
        grid-template-columns: 1fr;
    }

    .admin-table-row {
        grid-template-columns: 1fr;
        gap: 4px;
        padding: 10px 12px;
    }
}

/* ---- Planlar / odemeler ---- */
.admin-plan-form {
    display: grid;
    gap: 12px;
    margin-top: 14px;
}

/* Planlar yan yana: genis ekranda 3, orta ekranda 2, dar ekranda 1 sutun */
.admin-plan-list {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 12px;
    align-items: start;
}

.admin-plan-list .admin-plan-form {
    margin-top: 0;
}

@media (max-width: 1100px) {
    .admin-plan-list {
        grid-template-columns: repeat(2, minmax(0, 1fr));
    }
}

@media (max-width: 700px) {
    .admin-plan-list {
        grid-template-columns: minmax(0, 1fr);
    }
}

.admin-plan-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 12px;
}

.admin-plan-grid .admin-plan-wide {
    grid-column: 1 / -1;
}

.admin-plan-checks {
    display: flex;
    flex-wrap: wrap;
    gap: 18px;
}

.admin-payment-row {
    display: grid;
    gap: 8px;
    border-top: 1px solid rgba(0, 0, 0, 0.08);
    padding: 12px 0;
}

.admin-payment-row small {
    display: block;
    margin-top: 3px;
    color: #667370;
    line-height: 1.5;
}

.admin-payment-row input[type="text"] {
    width: 100%;
    box-sizing: border-box;
}

/* Plan ekleme penceresi */
.admin-icon-button {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 34px;
    height: 34px;
    flex: 0 0 34px;
    padding: 0;
    border: 1px solid var(--line);
    border-radius: 8px;
    background: var(--surface);
    color: var(--primary-dark);
    cursor: pointer;
}

.admin-icon-button:hover {
    background: var(--surface-strong);
}

.admin-icon-button svg {
    width: 17px;
    height: 17px;
    fill: none;
    stroke: currentColor;
    stroke-width: 2;
    stroke-linecap: round;
    stroke-linejoin: round;
}

.admin-modal {
    position: fixed;
    inset: 0;
    z-index: 50;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 16px;
    background: rgba(23, 33, 31, 0.45);
}

.admin-modal[hidden] {
    display: none;
}

.admin-modal-panel {
    width: min(520px, 100%);
    max-height: calc(100vh - 32px);
    overflow-y: auto;
    border-radius: 8px;
    background: var(--surface);
    box-shadow: var(--shadow);
}

.admin-modal-panel .admin-plan-modal-form {
    margin: 0;
    border: 0;
}

/* Odeme ayarlari: Havale ve PayTR yan yana */
.admin-payment-settings-form {
    grid-template-columns: repeat(2, minmax(0, 1fr));
    align-items: start;
    gap: 12px;
}

.admin-payment-settings-form .update-actions {
    grid-column: 1 / -1;
}

@media (max-width: 900px) {
    .admin-payment-settings-form {
        grid-template-columns: minmax(0, 1fr);
    }
}

/* Dogrulama sayfasi: Netgsm solda, e-posta (SMTP) sagda */
.admin-verification-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 12px;
    align-items: start;
}

.admin-verification-col {
    display: grid;
    gap: 10px;
    min-width: 0;
}

.admin-mail-row {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 10px;
}

@media (max-width: 900px) {
    .admin-verification-grid {
        grid-template-columns: minmax(0, 1fr);
    }
}

/* Kullanici listesi */
.admin-users-table .admin-table-row {
    grid-template-columns: 1.3fr 1fr 1.4fr 1fr 0.9fr 0.7fr;
    padding-top: 8px;
    padding-bottom: 8px;
}

.admin-users-table .admin-table-row span {
    min-width: 0;
    overflow-wrap: anywhere;
}

.admin-users-table small {
    color: var(--muted);
}

.admin-user-search {
    display: flex;
    gap: 8px;
    align-items: center;
}

.admin-user-search input[type="search"] {
    min-width: 220px;
    min-height: 34px;
    padding: 0 10px;
    border: 1px solid var(--line);
    border-radius: 8px;
    font: inherit;
}

.admin-link-button {
    display: inline-flex;
    align-items: center;
    min-height: 34px;
    padding: 0 12px;
    border: 1px solid var(--line);
    border-radius: 8px;
    background: var(--surface);
    color: var(--primary-dark);
    font-size: 13px;
    font-weight: 700;
    text-decoration: none;
}

.admin-pager {
    display: flex;
    gap: 10px;
    align-items: center;
    justify-content: center;
    margin-top: 12px;
    color: var(--muted);
    font-size: 13px;
}

@media (max-width: 900px) {
    .admin-users-table .admin-table-row {
        grid-template-columns: 1fr;
    }

    .admin-user-search {
        flex-wrap: wrap;
    }
}

/* Ayar ve bakim: sistem kontrolleri */
.check-ok {
    color: var(--primary);
}

.check-warn {
    color: #9a6a00;
}

.check-bad {
    color: var(--danger);
}

.admin-inline-form {
    margin: 0;
}

.admin-subhead {
    margin: 18px 0 8px;
    font-size: 15px;
}

/* Ayar ve bakim: kontroller iki sutun, yedek kayitlari altta tam genislik */
.admin-checks-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 12px;
    align-items: start;
}

.admin-checks-col {
    min-width: 0;
}

.admin-checks-col .admin-subhead {
    margin-top: 10px;
}

.admin-checks-grid .setting-list div strong {
    text-align: right;
}

@media (max-width: 900px) {
    .admin-checks-grid {
        grid-template-columns: minmax(0, 1fr);
    }
}

/* Odemeler: bekleyen havale ve aktif abonelikler yan yana, son odemeler altta tam genislik */
.admin-payments-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 12px;
    align-items: start;
}

.admin-payments-grid > .update-status-card {
    min-width: 0;
}

.admin-payments-grid > .admin-payments-wide {
    grid-column: 1 / -1;
}

@media (max-width: 900px) {
    .admin-payments-grid {
        grid-template-columns: minmax(0, 1fr);
    }
}

/* Reddedilen havale odemesi (bekleyenler listesinde kalir, sonradan onaylanabilir) */
.admin-payment-row.is-rejected {
    opacity: 0.85;
}

.status-badge.is-rejected {
    background: var(--danger-bg);
    color: var(--danger);
}

/* Aktif abonelik satiri: bilgi solda, sil simgesi sagda */
.admin-sub-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
}

.admin-sub-row > div {
    min-width: 0;
}

.admin-icon-button.is-danger {
    color: var(--danger);
    border-color: rgba(179, 64, 64, 0.35);
}

.admin-icon-button.is-danger:hover {
    background: var(--danger-bg);
}

/* Sayfa ici onay penceresi */
.admin-confirm-panel {
    display: grid;
    gap: 10px;
    padding: 18px;
    width: min(420px, 100%);
}

.admin-confirm-panel h3 {
    margin: 0;
    font-size: 17px;
}

.admin-confirm-panel p {
    margin: 0;
    color: var(--muted);
    line-height: 1.5;
}

/* Bildirim kutusu: gorunup kaybolur */
.update-notice {
    transition: opacity 0.4s ease;
    cursor: pointer;
}

.update-notice.is-leaving {
    opacity: 0;
}

/* Plan formu: her ozellik adi solda, rakam kutusu ayni satirda sagda */
.admin-plan-grid {
    grid-template-columns: minmax(0, 1fr);
    gap: 8px;
}

.admin-plan-grid .admin-form-field:has(input[type="number"]) {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
}

.admin-plan-grid .admin-form-field:has(input[type="number"]) span {
    flex: 1 1 auto;
}

.admin-plan-grid .admin-form-field input[type="number"] {
    flex: 0 0 88px;
    width: 88px;
    text-align: right;
}

.admin-plan-checks {
    flex-direction: column;
    gap: 8px;
}

.admin-plan-team-check {
    display: flex;
    flex: 1 1 auto;
    align-items: center;
    gap: 8px;
    cursor: pointer;
}

.admin-plan-team-check input {
    flex: 0 0 auto;
}

.admin-plan-team-check input[type="checkbox"] {
    flex: 0 0 18px;
    width: 18px;
    min-height: 0;
    height: 18px;
    padding: 0;
    margin: 0;
}

.admin-plan-team-check span {
    flex: 1 1 auto;
}

.admin-plan-no-check {
    padding-left: 26px;
}

.admin-plan-grid .admin-form-field:has(.admin-plan-team-check) {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
}

.admin-plan-grid .admin-plan-wide {
    display: grid !important;
}

/* Plan formlarinda butonlar saga yaslanir; silinemeyen plandaki Sil pasif */
.admin-plan-form .update-actions {
    display: flex;
    justify-content: flex-end;
    gap: 8px;
}

.admin-plan-form .update-actions button {
    width: auto;
    min-width: 92px;
}

.admin-plan-form .update-actions button:disabled {
    opacity: 0.45;
    cursor: not-allowed;
}

.admin-plan-grid .admin-form-field.is-off {
    opacity: 0.5;
}

.admin-plan-grid input.is-off {
    opacity: 0.5;
    background: #f1f4f3;
    cursor: not-allowed;
}

.admin-plan-grid input[type="number"]:disabled {
    opacity: 0.5;
    background: #f1f4f3;
    cursor: not-allowed;
}

/* Aylik ve yillik ucret yan yana (yillik sagda) */
.admin-plan-price-row {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 12px;
}

/* Sira alani Sil / Kaydet satirinin solunda */
.admin-plan-position {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-right: auto;
}

.admin-plan-position span {
    font-size: 12px;
    font-weight: 800;
}

.admin-plan-position input {
    width: 64px;
    text-align: right;
}

.admin-plan-position input:disabled {
    opacity: 0.5;
    background: #f1f4f3;
    cursor: not-allowed;
}

/* Kullanici detay sayfasi */
a.admin-table-row.is-link {
    color: inherit;
    text-decoration: none;
    cursor: pointer;
}

a.admin-table-row.is-link:hover {
    background: rgba(17, 100, 102, 0.06);
}

.admin-detail-grid {
    display: grid;
    gap: 12px;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    align-items: start;
}

.admin-detail-stack {
    display: grid;
    gap: 12px;
}

.admin-detail-card {
    display: grid;
    gap: 10px;
}

.admin-detail-fields {
    display: grid;
    gap: 10px;
}

.admin-detail-actions {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    align-items: center;
    justify-content: flex-end;
}

.admin-detail-row {
    display: flex;
    flex-wrap: wrap;
    gap: 6px 12px;
    align-items: center;
    justify-content: space-between;
    padding: 6px 0;
    border-top: 1px solid var(--line, #d9e2df);
    font-size: 13px;
}

.admin-detail-row small {
    color: var(--muted, #667370);
}

/* Planlar: gorunmez varsayilan kaydet dugmesi (Enter ile gonderimde "Sil" tetiklenmesin) ve tek "Tümünü kaydet" cubugu */
.admin-visually-hidden { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip: rect(0, 0, 0, 0); border: 0; }
.admin-plans-saveall { display: flex; justify-content: flex-end; margin-top: 14px; }

/* Plan formu: ozellik gruplari */
.admin-plan-grid .admin-plan-group {
    grid-column: 1 / -1;
    margin-top: 10px;
    padding-top: 10px;
    border-top: 1px solid var(--line, #d9e2df);
    font-size: 12px;
    font-weight: 700;
    letter-spacing: 0.04em;
    text-transform: uppercase;
    color: var(--primary, #0f766e);
}

/* Yan yana planlar ayni boyda biter; Sira / Sil satiri kartin altinda durur */
.admin-plan-list {
    align-items: stretch;
}

.admin-plan-list .admin-plan-form {
    grid-template-rows: auto 1fr auto;
}

.admin-plan-list .admin-plan-form > .admin-plan-grid {
    align-content: start;
}

/* Iki alan yan yana (dar ekranda alt alta) */
.admin-field-row {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 10px;
}

@media (max-width: 640px) {
    .admin-field-row {
        grid-template-columns: 1fr;
    }
}
urum (ok|warn|bad), ayrinti]
$systemChecks = [];
$formatBytes = static function (float $bytes): string {
    foreach (['B', 'KB', 'MB', 'GB', 'TB'] as $unit) {
        if ($bytes < 1024 || $unit === 'TB') {
            return number_format($bytes, $unit === 'B' ? 0 : 1, ',', '.') . ' ' . $unit;
        }
        $bytes /= 1024;
    }
    return '';
};
try {
    $started = microtime(true);
    $dbVersion = (string)$pdo->query('SELECT VERSION()')->fetchColumn();
    $ms = (int)round((microtime(true) - $started) * 1000);
    $systemChecks[] = ['Veritabanı', 'ok', 'Bağlı · ' . $dbVersion . ' · ' . $ms . ' ms'];
} catch (Throwable $exception) {
    $systemChecks[] = ['Veritabanı', 'bad', 'Bağlanamadı'];
}

$missingExtensions = array_values(array_filter(['pdo_mysql', 'mbstring', 'openssl', 'zip', 'curl'], static fn (string $ext): bool => !extension_loaded($ext)));
// PHP sürümü ve eklentileri tek satirda: "8.2.12 - Tamam"
$systemChecks[] = [
    'PHP',
    ($missingExtensions || version_compare(PHP_VERSION, '8.1.0', '<')) ? 'warn' : 'ok',
    PHP_VERSION . ' - ' . ($missingExtensions ? 'Eksik eklenti: ' . implode(', ', $missingExtensions) : 'Tamam'),
];

foreach (['storage' => BASE_PATH . '/storage', 'storage/logs' => BASE_PATH . '/storage/logs', 'storage/sessions' => BASE_PATH . '/storage/sessions', 'storage/admin-updates' => BASE_PATH . '/storage/admin-updates', 'public/uploads' => BASE_PATH . '/public/uploads'] as $label => $dir) {
    if (!is_dir($dir)) {
        // Bazi klasorler ilk kullanimda otomatik olusturulur.
        $systemChecks[] = ['Dosya izni · ' . $label, $label === 'storage/admin-updates' ? 'ok' : 'warn', $label === 'storage/admin-updates' ? 'İlk yedek / güncellemede oluşturulur' : 'Klasör yok'];
    } elseif (!is_writable($dir)) {
        $systemChecks[] = ['Dosya izni · ' . $label, 'bad', 'Yazılamıyor'];
    } else {
        $systemChecks[] = ['Dosya izni · ' . $label, 'ok', 'Yazılabilir'];
    }
}

$diskFree = @disk_free_space(BASE_PATH);
$diskTotal = @disk_total_space(BASE_PATH);
if ($diskFree !== false && $diskTotal) {
    $freePercent = (int)round($diskFree / $diskTotal * 100);
    $systemChecks[] = ['Sunucu diski', $freePercent < 10 ? 'bad' : ($freePercent < 20 ? 'warn' : 'ok'), $formatBytes((float)$diskFree) . ' boş · %' . $freePercent];
}

$backupFiles = glob(BASE_PATH . '/storage/admin-updates/backups/*.zip') ?: [];
rsort($backupFiles);
if ($backupFiles) {
    $latestBackup = $backupFiles[0];
    $ageDays = (int)floor((time() - (int)filemtime($latestBackup)) / 86400);
    $systemChecks[] = ['Panelden elle alınan son yedek', 'ok', date('d.m.Y H:i', (int)filemtime($latestBackup)) . ' · ' . $formatBytes((float)filesize($latestBackup)) . ' · ' . count($backupFiles) . ' yedek'];
} else {
    $systemChecks[] = ['Panelden elle alınan son yedek', 'ok', 'Elle yedek alınmadı (otomatik yedek aşağıda)'];
}

// Otomatik yedek (bin/contacts-backup.sh) en son sonucunu storage/backup-status.json'a yazar.
$backupStatusFile = BASE_PATH . '/storage/backup-status.json';
$autoBackup = is_file($backupStatusFile) ? json_decode((string)file_get_contents($backupStatusFile), true) : null;
if (!is_array($autoBackup) || empty($autoBackup['time'])) {
    $systemChecks[] = ['Otomatik yedek', 'warn', 'Henüz çalışmadı'];
} else {
    $backupAgeHours = (time() - (int)strtotime((string)$autoBackup['time'])) / 3600;
    $backupLabel = ($autoBackup['mode'] ?? '') === 'weekly' ? 'haftalık' : 'günlük';
    $remoteLabel = match ($autoBackup['remote'] ?? '') {
        'ok' => 'pCloud\'a yüklendi',
        'failed' => 'pCloud\'a yüklenemedi',
        default => 'yalnızca sunucuda',
    };
    $backupState = 'ok';
    if (empty($autoBackup['ok']) || ($autoBackup['remote'] ?? '') === 'failed' || $backupAgeHours > 48) {
        $backupState = 'bad';
    } elseif (($autoBackup['remote'] ?? '') !== 'ok') {
        $backupState = 'warn';
    }
    $systemChecks[] = [
        'Otomatik yedek',
        $backupState,
        date('d.m.Y H:i', (int)strtotime((string)$autoBackup['time'])) . ' · ' . $backupLabel
            . (!empty($autoBackup['size']) ? ' · ' . $formatBytes((float)$autoBackup['size']) : '')
            . ' · ' . $remoteLabel
            . ($backupAgeHours > 48 ? ' · 2 günden eski!' : ''),
    ];
    if (!empty($autoBackup['remote_total'])) {
        $cloudFreePercent = (int)round(((float)($autoBackup['remote_free'] ?? 0)) / (float)$autoBackup['remote_total'] * 100);
        $systemChecks[] = [
            'pCloud alanı (yedekler)',
            $cloudFreePercent < 10 ? 'bad' : ($cloudFreePercent < 20 ? 'warn' : 'ok'),
            $formatBytes((float)($autoBackup['remote_free'] ?? 0)) . ' boş / ' . $formatBytes((float)$autoBackup['remote_total']) . ' · %' . $cloudFreePercent . ' boş',
        ];
    }
}

// pCloud satiri her zaman gorunsun: otomatik yedek henuz calismadiysa bilgi yok yazar.
if (!array_filter($systemChecks, static fn (array $check): bool => str_starts_with($check[0], 'pCloud'))) {
    $systemChecks[] = ['pCloud alanı (yedekler)', 'warn', 'Henüz bilgi yok (ilk otomatik yedekten sonra görünür)'];
}

// Yedek kayitlari: bin/contacts-backup.sh ve kullanici yedegi gece gorevi her calistiginda bir satir ekler.
$backupHistory = [];
$historyFile = BASE_PATH . '/storage/backup-history.jsonl';
if (is_file($historyFile)) {
    foreach (array_slice(array_reverse(file($historyFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: []), 0, 20) as $historyLine) {
        $entry = json_decode($historyLine, true);
        if (is_array($entry) && !empty($entry['time'])) {
            $backupHistory[] = $entry;
        }
    }
}

$currentVersion = '1.0.0';
$latestAndroidRelease = null;
$latestWindowsRelease = null;
try {
    $currentVersion = contacts_admin_update_current_version($pdo);
    $latestAndroidRelease = app_releases_latest($pdo, 'android');
    $latestWindowsRelease = app_releases_latest($pdo, 'windows');
} catch (Throwable $exception) {
    $updateNotice ??= [
        'type' => 'error',
        'title' => 'Veritabanı bağlantısı kurulamadı',
        'message' => $exception->getMessage(),
    ];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $redirectHash = 'settings'; // Guncelleme bolumu Ayarlar sayfasinin altindadir
    $redirectUrl = null;
    $batchFailure = null;
    try {
        if (!admin_check($pdo)) {
            throw new RuntimeException('Bu işlem için yetkiniz yok.');
        }

        if (isset($_POST['admin_download_full_backup'])) {
            // "Ayar ve bakim" sayfasindan basildiysa hata ve donus o sayfada olsun.
            $redirectHash = 'settings';
            $backupPath = contacts_admin_update_create_backup($pdo);
            if (!is_file($backupPath)) {
                throw new RuntimeException('Yedek dosyası oluşturulamadı.');
            }

            header('Content-Type: application/zip');
            header('Content-Disposition: attachment; filename="' . basename($backupPath) . '"');
            header('Content-Length: ' . (string)filesize($backupPath));
            readfile($backupPath);
            exit;
        }

        if (isset($_POST['admin_install_manual_update'])) {
            $result = contacts_admin_update_apply($config, $_FILES['update_zip'] ?? null, (string)($_POST['target_version'] ?? ''));
            $_SESSION['admin_update_notice'] = [
                'type' => 'success',
                'title' => 'Güncelleme tamamlandı',
                'message' => sprintf(
                    '%d dosya uygulandı. Çalışan migration: %d, atlanan migration: %d. Yedek: %s',
                    (int)$result['copied'],
                    count($result['migrations_ran']),
                    count($result['migrations_skipped']),
                    basename((string)$result['backup'])
                ),
            ];
        }

        if (isset($_POST['admin_save_verification'])) {
            $redirectHash = 'verification';
            $enabled = isset($_POST['phone_verification_enabled']);
            $usercode = trim((string)($_POST['netgsm_usercode'] ?? ''));
            $netgsmPassword = trim((string)($_POST['netgsm_password'] ?? ''));
            $msgheader = trim((string)($_POST['netgsm_msgheader'] ?? ''));

            if ($enabled && ($usercode === '' || $netgsmPassword === '' || $msgheader === '')) {
                throw new RuntimeException('Telefon doğrulamasını açmak için Netgsm bilgilerinin tamamı gerekli.');
            }

            app_settings_set($pdo, 'netgsm_usercode', $usercode);
            app_settings_set($pdo, 'netgsm_password', $netgsmPassword);
            app_settings_set($pdo, 'netgsm_msgheader', $msgheader);
            app_settings_set($pdo, 'phone_verification_enabled', $enabled ? '1' : '0');

            $_SESSION['admin_verification_notice'] = [
                'type' => 'success',
                'title' => 'Doğrulama ayarları kaydedildi',
                'message' => $enabled
                    ? 'Telefon doğrulaması AÇIK. Doğrulanmamış kullanıcılara uygulamada uyarı gösterilecek.'
                    : 'Telefon doğrulaması KAPALI. Kullanıcılardan telefon doğrulaması istenmiyor.',
            ];
        }

        if (isset($_POST['admin_save_mail'])) {
            $redirectHash = 'verification';
            $secure = (string)($_POST['smtp_secure'] ?? 'ssl');
            $port = (int)($_POST['smtp_port'] ?? 465);
            $fromEmail = trim((string)($_POST['smtp_from_email'] ?? ''));
            if ($fromEmail !== '' && !filter_var($fromEmail, FILTER_VALIDATE_EMAIL)) {
                throw new RuntimeException('Gönderen e-posta adresi geçerli değil.');
            }
            app_settings_set($pdo, 'smtp_host', trim((string)($_POST['smtp_host'] ?? '')));
            app_settings_set($pdo, 'smtp_port', (string)($port > 0 && $port < 65536 ? $port : 465));
            app_settings_set($pdo, 'smtp_user', trim((string)($_POST['smtp_user'] ?? '')));
            app_settings_set($pdo, 'smtp_pass', (string)($_POST['smtp_pass'] ?? ''));
            app_settings_set($pdo, 'smtp_secure', in_array($secure, ['ssl', 'tls', 'none'], true) ? $secure : 'ssl');
            app_settings_set($pdo, 'smtp_from_email', $fromEmail);

            $_SESSION['admin_verification_notice'] = [
                'type' => 'success',
                'title' => 'E-posta ayarları kaydedildi',
                'message' => 'Doğrulama kodu ve bilgilendirme e-postaları bu ayarlarla gönderilecek. Kontrol için test e-postası gönderebilirsiniz.',
            ];
        }

        if (isset($_POST['admin_save_promo'])) {
            $redirectHash = 'verification';
            $website = trim((string)($_POST['promo_website'] ?? ''));
            if ($website !== '' && !preg_match('#^https?://#i', $website)) {
                $website = 'https://' . $website;
            }
            if ($website !== '' && !filter_var($website, FILTER_VALIDATE_URL)) {
                throw new RuntimeException('Web sitesi adresi geçerli değil.');
            }
            $email = trim((string)($_POST['promo_email'] ?? ''));
            if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                throw new RuntimeException('Tanıtım e-posta adresi geçerli değil.');
            }
            $instagram = ltrim(trim((string)($_POST['promo_instagram'] ?? '')), '@');
            $instagram = preg_replace('#^https?://(www\.)?instagram\.com/#i', '', $instagram) ?? $instagram;
            $instagram = trim($instagram, '/ ');
            if ($instagram !== '' && !preg_match('/^[A-Za-z0-9._]{1,60}$/', $instagram)) {
                throw new RuntimeException('Instagram kullanıcı adı geçerli değil.');
            }
            app_settings_set($pdo, 'promo_about', mb_substr(trim((string)($_POST['promo_about'] ?? '')), 0, 600));
            app_settings_set($pdo, 'promo_website', $website);
            app_settings_set($pdo, 'promo_phone', mb_substr(trim((string)($_POST['promo_phone'] ?? '')), 0, 30));
            app_settings_set($pdo, 'promo_whatsapp', mb_substr(trim((string)($_POST['promo_whatsapp'] ?? '')), 0, 30));
            app_settings_set($pdo, 'promo_email', $email);
            app_settings_set($pdo, 'promo_instagram', $instagram);

            $_SESSION['admin_verification_notice'] = [
                'type' => 'success',
                'title' => 'Tanıtım bilgileri kaydedildi',
                'message' => 'Davet / kayıt özeti sayfasının altındaki "Uygulama hakkında" bölümü bu bilgilerle güncellendi.',
            ];
        }

        if (isset($_POST['admin_test_mail'])) {
            $redirectHash = 'verification';
            $to = trim((string)($_POST['test_email'] ?? ''));
            if (!filter_var($to, FILTER_VALIDATE_EMAIL)) {
                throw new RuntimeException('Test için geçerli bir e-posta adresi girin.');
            }
            $smtp = mail_smtp_config($pdo);
            if ($smtp['host'] === '' || $smtp['user'] === '' || $smtp['pass'] === '') {
                throw new RuntimeException('Önce SMTP sunucu, kullanıcı ve şifre bilgilerini kaydedin.');
            }
            $appName = (string)app_config('app.name', 'MyContacts');
            $ok = smtp_send_mail($smtp, $to, mail_from_email(), $appName, $appName . ' test e-postasi', "Merhaba,\n\nBu bir test e-postasidir. E-posta ayarlariniz calisiyor.");
            if (!$ok) {
                throw new RuntimeException('Test e-postası gönderilemedi. Sunucu, port, güvenlik türü, kullanıcı ve şifreyi kontrol edin.');
            }
            $_SESSION['admin_verification_notice'] = [
                'type' => 'success',
                'title' => 'Test e-postası gönderildi',
                'message' => $to . ' adresine gönderildi. Gelen kutusunu (ve spam klasörünü) kontrol edin.',
            ];
        }

        if (isset($_POST['admin_save_plan'])) {
            $redirectHash = 'plans';
            plans_ensure_tables($pdo);
            $planId = (int)($_POST['plan_id'] ?? 0);
            $name = trim((string)($_POST['name'] ?? ''));
            // Bireysel (sistem) planda ad/fiyat/sira/durum formda pasiftir ve gonderilmez.
            $systemPlanCheck = $pdo->prepare('SELECT COUNT(*) FROM plans WHERE id = :id AND is_system = 1');
            $systemPlanCheck->execute(['id' => $planId]);
            if ((int)$systemPlanCheck->fetchColumn() > 0) {
                $name = 'Bireysel';
            }
            if ($name === '') {
                throw new RuntimeException('Plan adı gerekli.');
            }
            // Fiyat: 4990,00 / 4.990,00 / 4990.00 biciminde girilebilir.
            $parsePrice = static function (string $raw): float {
                $text = str_replace([' ', chr(194) . chr(160)], '', trim($raw));
                if (str_contains($text, ',')) {
                    $text = str_replace('.', '', $text);
                    $text = str_replace(',', '.', $text);
                }
                return is_numeric($text) ? (float)$text : 0.0;
            };
            $price = $parsePrice((string)($_POST['price_monthly'] ?? '0'));
            $priceYearly = max(0, round($parsePrice((string)($_POST['price_yearly'] ?? '0')), 2));
            $teamLimitRaw = trim((string)($_POST['team_limit'] ?? ''));
            $teamLimit = $teamLimitRaw === '' || (int)$teamLimitRaw <= 0 ? null : (int)$teamLimitRaw;
            // Sayi sinirlari: bos = sinirsiz (NULL), 0 = hak yok.
            $limitPost = static function (string $key, int $max): ?int {
                $raw = trim((string)($_POST[$key] ?? ''));

                return $raw === '' ? null : max(0, min($max, (int)$raw));
            };
            $params = [
                'name' => mb_substr($name, 0, 80),
                'description' => trim((string)($_POST['description'] ?? '')) !== '' ? mb_substr(trim((string)$_POST['description']), 0, 255) : null,
                'price' => max(0, round($price, 2)),
                'team_limit' => $teamLimit,
                'feature_team' => isset($_POST['feature_team']) ? 1 : 0,
                'feature_caller' => isset($_POST['feature_caller']) ? 1 : 0,
                'is_active' => (max(0, round($price, 2)) > 0 || $priceYearly > 0) ? 1 : 0, // aylik veya yillik fiyat girilmisse plan satista (aktif)
                'price_yearly' => $priceYearly,
                'position' => (int)($_POST['position'] ?? 0),
                'feature_ref' => isset($_POST['feature_ref']) ? 1 : 0,
                'backup_days' => isset($_POST['feature_backup']) ? max(1, min(365, (int)($_POST['backup_interval_days'] ?? 7))) : 0,
                'backup_keep' => isset($_POST['feature_backup']) ? max(1, min(365, (int)($_POST['backup_keep'] ?? 4))) : max(0, min(365, (int)($_POST['backup_keep'] ?? 0))),
                'limit_cash' => $limitPost('limit_cash', 1000),
                'limit_banks' => $limitPost('limit_banks', 1000),
                'limit_bank_accounts' => $limitPost('limit_bank_accounts', 1000),
                'limit_bank_cards' => $limitPost('limit_bank_cards', 1000),
                'limit_recurring' => $limitPost('limit_recurring', 1000),
                'feature_cash' => isset($_POST['feature_cash']) ? 1 : 0,
                'feature_banks' => isset($_POST['feature_banks']) ? 1 : 0,
                'feature_bank_accounts' => isset($_POST['feature_bank_accounts']) ? 1 : 0,
                'feature_bank_cards' => isset($_POST['feature_bank_cards']) ? 1 : 0,
                'feature_recurring' => isset($_POST['feature_recurring']) ? 1 : 0,
                'feature_import' => isset($_POST['feature_import']) ? 1 : 0,
                'feature_trial' => isset($_POST['feature_trial']) ? 1 : 0,
                'limit_import' => $limitPost('limit_import', 2000),
            ];
            if ($planId > 0) {
                $params['id'] = $planId;
                $isSystemStmt = $pdo->prepare('SELECT is_system FROM plans WHERE id = :id');
                $isSystemStmt->execute(['id' => $planId]);
                if ((int)$isSystemStmt->fetchColumn() === 1) {
                    // Bireysel: ad, fiyat (0), durum (aktif) ve sira sabit; yalnizca ozellikler duzenlenir.
                    $pdo->prepare(
                        'UPDATE plans SET description = :description, team_limit = :team_limit, feature_team = :feature_team,
                                feature_caller = :feature_caller, feature_ref = :feature_ref, backup_interval_days = :backup_days, backup_keep = :backup_keep,
                                limit_cash = :limit_cash, limit_banks = :limit_banks, limit_bank_accounts = :limit_bank_accounts, limit_bank_cards = :limit_bank_cards, limit_recurring = :limit_recurring,
                                feature_cash = :feature_cash, feature_banks = :feature_banks, feature_bank_accounts = :feature_bank_accounts, feature_bank_cards = :feature_bank_cards, feature_recurring = :feature_recurring,
                                feature_import = :feature_import, limit_import = :limit_import WHERE id = :id'
                    )->execute([
                        'description' => $params['description'], 'team_limit' => $params['team_limit'],
                        'feature_team' => $params['feature_team'], 'feature_caller' => $params['feature_caller'], 'feature_ref' => $params['feature_ref'],
                        'backup_days' => $params['backup_days'], 'backup_keep' => $params['backup_keep'], 'id' => $planId,
                        'limit_cash' => $params['limit_cash'], 'limit_banks' => $params['limit_banks'], 'limit_bank_accounts' => $params['limit_bank_accounts'],
                        'limit_bank_cards' => $params['limit_bank_cards'], 'limit_recurring' => $params['limit_recurring'],
                        'feature_cash' => $params['feature_cash'], 'feature_banks' => $params['feature_banks'], 'feature_bank_accounts' => $params['feature_bank_accounts'],
                        'feature_bank_cards' => $params['feature_bank_cards'], 'feature_recurring' => $params['feature_recurring'],
                        'feature_import' => $params['feature_import'], 'limit_import' => $params['limit_import'],
                    ]);
                    $name = 'Bireysel';
                } else {
                    $pdo->prepare(
                        'UPDATE plans SET name = :name, description = :description, price_monthly = :price, price_yearly = :price_yearly, team_limit = :team_limit,
                                feature_team = :feature_team, feature_caller = :feature_caller, feature_ref = :feature_ref, is_active = :is_active, position = :position,
                                backup_interval_days = :backup_days, backup_keep = :backup_keep,
                                limit_cash = :limit_cash, limit_banks = :limit_banks, limit_bank_accounts = :limit_bank_accounts, limit_bank_cards = :limit_bank_cards, limit_recurring = :limit_recurring,
                                feature_cash = :feature_cash, feature_banks = :feature_banks, feature_bank_accounts = :feature_bank_accounts, feature_bank_cards = :feature_bank_cards, feature_recurring = :feature_recurring,
                                feature_import = :feature_import, limit_import = :limit_import, feature_trial = :feature_trial WHERE id = :id'
                    )->execute($params);
                }
            } else {
                $pdo->prepare(
                    'INSERT INTO plans (name, description, price_monthly, price_yearly, team_limit, feature_team, feature_caller, feature_ref, is_active, position, backup_interval_days, backup_keep, limit_cash, limit_banks, limit_bank_accounts, limit_bank_cards, limit_recurring, feature_cash, feature_banks, feature_bank_accounts, feature_bank_cards, feature_recurring, feature_import, limit_import, feature_trial)
                     VALUES (:name, :description, :price, :price_yearly, :team_limit, :feature_team, :feature_caller, :feature_ref, :is_active, :position, :backup_days, :backup_keep, :limit_cash, :limit_banks, :limit_bank_accounts, :limit_bank_cards, :limit_recurring, :feature_cash, :feature_banks, :feature_bank_accounts, :feature_bank_cards, :feature_recurring, :feature_import, :limit_import, :feature_trial)'
                )->execute($params);
            }
            $savedPlanId = $planId > 0 ? $planId : (int)$pdo->lastInsertId();
            if ($savedPlanId > 0) {
                $pdo->prepare('UPDATE plans SET feature_attendance = :value, feature_attachments = :attachments, limit_attachment_mb = :attachment_mb, limit_attendance_tags = :attendance_tags, feature_print_templates = :print_templates, limit_print_templates = :print_template_limit, feature_history = :history, limit_history_days = :history_days, feature_contacts = :contacts, limit_contacts = :contact_limit, feature_contact_accounts = :contact_accounts, limit_contact_accounts = :contact_accounts_limit, feature_message_templates = :message_templates WHERE id = :id')
                    ->execute([
                        'value' => isset($_POST['feature_attendance']) ? 1 : 0,
                        'attachments' => isset($_POST['feature_attachments']) ? 1 : 0,
                        'attachment_mb' => (static function (): ?int {
                            $raw = str_replace(',', '.', trim((string)($_POST['limit_storage_gb'] ?? '')));

                            return $raw === '' ? null : max(0, min(100000 * 1024, (int)round((float)$raw * 1024)));
                        })(),
                        'attendance_tags' => $limitPost('limit_attendance_tags', 100000),
                        'print_templates' => isset($_POST['feature_print_templates']) ? 1 : 0,
                        'print_template_limit' => $limitPost('limit_print_templates', 10000),
                        'history' => isset($_POST['feature_history']) ? 1 : 0,
                        'history_days' => $limitPost('limit_history_days', 3650),
                        'contacts' => isset($_POST['feature_contacts']) ? 1 : 0,
                        'contact_limit' => $limitPost('limit_contacts', 1000000),
                        'contact_accounts' => isset($_POST['feature_contact_accounts']) ? 1 : 0,
                        'message_templates' => isset($_POST['feature_message_templates']) ? 1 : 0,
                        'contact_accounts_limit' => $limitPost('limit_contact_accounts', 1000),
                        'id' => $savedPlanId,
                    ]);
            }
            $_SESSION['admin_plan_notice'] = ['type' => 'success', 'title' => 'Plan kaydedildi', 'message' => $name . ' planı güncellendi.'];
        }

        if (isset($_POST['admin_delete_plan'])) {
            $redirectHash = 'plans';
            plans_ensure_tables($pdo);
            $planId = (int)($_POST['plan_id'] ?? 0);
            $systemCheck = $pdo->prepare('SELECT is_system FROM plans WHERE id = :id');
            $systemCheck->execute(['id' => $planId]);
            if ((int)$systemCheck->fetchColumn() === 1) {
                throw new RuntimeException('Bireysel plan silinemez.');
            }
            $used = $pdo->prepare('SELECT (SELECT COUNT(*) FROM plan_subscriptions WHERE plan_id = :a) + (SELECT COUNT(*) FROM plan_payments WHERE plan_id = :b)');
            $used->execute(['a' => $planId, 'b' => $planId]);
            if ((int)$used->fetchColumn() > 0) {
                $pdo->prepare('UPDATE plans SET is_active = 0 WHERE id = :id')->execute(['id' => $planId]);
                $message = 'Bu planı kullanan abonelik/ödeme kayıtları olduğu için silinmedi, pasif yapıldı.';
            } else {
                $pdo->prepare('DELETE FROM plans WHERE id = :id')->execute(['id' => $planId]);
                $message = 'Plan silindi.';
            }
            $_SESSION['admin_plan_notice'] = ['type' => 'success', 'title' => 'Plan', 'message' => $message];
        }

        if (isset($_POST['admin_payment_approve'])) {
            $redirectHash = 'payments';
            if (!plan_payment_mark_paid($pdo, (int)($_POST['payment_id'] ?? 0), trim((string)($_POST['admin_note'] ?? '')) ?: 'Havale onaylandı')) {
                throw new RuntimeException('Ödeme bulunamadı veya zaten işlenmiş.');
            }
            $_SESSION['admin_plan_notice'] = ['type' => 'success', 'title' => 'Ödeme onaylandı', 'message' => 'Kullanıcının Kurumsal planı etkinleştirildi (30 gün).'];
        }

        if (isset($_POST['admin_payment_reject'])) {
            $redirectHash = 'payments';
            plans_ensure_tables($pdo);
            $pdo->prepare("UPDATE plan_payments SET status = 'rejected', admin_note = :note WHERE id = :id AND status = 'pending'")
                ->execute(['note' => trim((string)($_POST['admin_note'] ?? '')) ?: 'Reddedildi', 'id' => (int)($_POST['payment_id'] ?? 0)]);
            $_SESSION['admin_plan_notice'] = ['type' => 'success', 'title' => 'Ödeme reddedildi', 'message' => 'Ödeme kaydı reddedildi olarak işaretlendi.'];
        }

        if (isset($_POST['admin_grant_plan'])) {
            $redirectHash = 'payments';
            plans_ensure_tables($pdo);
            $phone = normalize_phone(clean_text((string)($_POST['user_phone'] ?? '')));
            $userStmt = $pdo->prepare('SELECT id, name FROM users WHERE phone = :phone LIMIT 1');
            $userStmt->execute(['phone' => $phone]);
            $grantUser = $userStmt->fetch();
            if (!$grantUser) {
                throw new RuntimeException('Bu telefon numarasıyla kayıtlı kullanıcı bulunamadı.');
            }
            $planStmt = $pdo->prepare('SELECT * FROM plans WHERE id = :id LIMIT 1');
            $planStmt->execute(['id' => (int)($_POST['plan_id'] ?? 0)]);
            $grantPlan = $planStmt->fetch();
            if (!$grantPlan) {
                throw new RuntimeException('Plan bulunamadı.');
            }
            $days = max(1, min(3650, (int)($_POST['days'] ?? PLAN_PERIOD_DAYS)));
            plan_activate($pdo, (int)$grantUser['id'], (int)$grantPlan['id'], 'admin', $days);
            $pdo->prepare("INSERT INTO plan_payments (user_id, plan_id, plan_name, amount, method, status, paid_at, admin_note) VALUES (:user_id, :plan_id, :plan_name, 0, 'admin', 'paid', NOW(), :note)")
                ->execute(['user_id' => (int)$grantUser['id'], 'plan_id' => (int)$grantPlan['id'], 'plan_name' => (string)$grantPlan['name'], 'note' => 'Admin tarafından ' . $days . ' gün tanımlandı']);
            $_SESSION['admin_plan_notice'] = ['type' => 'success', 'title' => 'Plan tanımlandı', 'message' => $grantUser['name'] . ' kullanıcısına ' . $grantPlan['name'] . ' planı ' . $days . ' gün için tanımlandı.'];
        }

        if (isset($_POST['admin_revoke_plan'])) {
            $redirectHash = 'payments';
            plans_ensure_tables($pdo);
            $subStmt = $pdo->prepare('SELECT user_id FROM plan_subscriptions WHERE id = :id LIMIT 1');
            $subStmt->execute(['id' => (int)($_POST['subscription_id'] ?? 0)]);
            $revokeUserId = (int)$subStmt->fetchColumn();
            $pdo->prepare("UPDATE plan_subscriptions SET status = 'cancelled' WHERE id = :id")->execute(['id' => (int)($_POST['subscription_id'] ?? 0)]);
            if ($revokeUserId > 0) {
                plan_for_user($pdo, $revokeUserId); // hesap turunu gunceller
            }
            $_SESSION['admin_plan_notice'] = ['type' => 'success', 'title' => 'Plan kaldırıldı', 'message' => 'Kullanıcı Bireysel hesaba döndü.'];
        }

        if (isset($_POST['admin_save_payment_settings'])) {
            $redirectHash = 'paymentsettings';
            plans_ensure_tables($pdo);
            app_settings_set($pdo, 'plan_bank_name', trim((string)($_POST['bank_name'] ?? '')));
            app_settings_set($pdo, 'plan_bank_iban', strtoupper(preg_replace('/\s+/', '', (string)($_POST['bank_iban'] ?? '')) ?? ''));
            app_settings_set($pdo, 'plan_bank_holder', trim((string)($_POST['bank_holder'] ?? '')));
            app_settings_set($pdo, 'plan_bank_note', trim((string)($_POST['bank_note'] ?? '')));
            app_settings_set($pdo, 'paytr_enabled', isset($_POST['paytr_enabled']) ? '1' : '0');
            app_settings_set($pdo, 'paytr_test_mode', isset($_POST['paytr_test_mode']) ? '1' : '0');
            app_settings_set($pdo, 'paytr_merchant_id', trim((string)($_POST['paytr_merchant_id'] ?? '')));
            // Gizli anahtarlar bos birakilirsa mevcut deger korunur.
            foreach (['paytr_merchant_key', 'paytr_merchant_salt'] as $secretKey) {
                $secretValue = trim((string)($_POST[$secretKey] ?? ''));
                if ($secretValue !== '') {
                    app_settings_set($pdo, $secretKey, $secretValue);
                }
            }
            if (isset($_POST['paytr_enabled'])) {
                $check = plan_payment_settings($pdo);
                if (!plan_paytr_available($check)) {
                    app_settings_set($pdo, 'paytr_enabled', '0');
                    throw new RuntimeException('PayTR için Mağaza No, Mağaza Parolası (key) ve Gizli Anahtar (salt) gerekli. Kartla ödeme açılmadı.');
                }
            }
            $_SESSION['admin_plan_notice'] = ['type' => 'success', 'title' => 'Ödeme ayarları kaydedildi', 'message' => 'Havale ve PayTR ayarları güncellendi.'];
        }

        $userActions = ['admin_user_save', 'admin_user_verify', 'admin_user_password', 'admin_user_grant_plan', 'admin_user_revoke_plan'];
        $userAction = null;
        foreach ($userActions as $candidateAction) {
            if (isset($_POST[$candidateAction])) {
                $userAction = $candidateAction;
                break;
            }
        }
        if ($userAction !== null) {
            $redirectHash = 'userdetail';
            $targetId = (int)($_POST['user_id'] ?? 0);
            $redirectUrl = './?user=' . $targetId . '#userdetail';
            plans_ensure_tables($pdo);
            admin_audit_ensure($pdo);
            $targetStmt = $pdo->prepare('SELECT * FROM users WHERE id = :id LIMIT 1');
            $targetStmt->execute(['id' => $targetId]);
            $target = $targetStmt->fetch();
            if (!$target) {
                throw new RuntimeException('Kullanıcı bulunamadı.');
            }
            $notice = static fn (string $title, string $message): array => ['type' => 'success', 'title' => $title, 'message' => $message];

            if ($userAction === 'admin_user_save') {
                $newName = clean_text((string)($_POST['name'] ?? ''));
                if ($newName === '') {
                    throw new RuntimeException('Ad soyad boş olamaz.');
                }
                $newPhone = normalize_phone(clean_text((string)($_POST['phone'] ?? '')));
                if ($newPhone === '' || strlen($newPhone) < 12 || (str_starts_with($newPhone, '+90') && strlen($newPhone) !== 13)) {
                    throw new RuntimeException('Telefon numarası eksik veya geçersiz.');
                }
                $newEmail = clean_text((string)($_POST['email'] ?? ''));
                $newInvoiceEmail = clean_text((string)($_POST['invoice_email'] ?? ''));
                foreach ([$newEmail, $newInvoiceEmail] as $mailCheck) {
                    if ($mailCheck !== '' && !filter_var($mailCheck, FILTER_VALIDATE_EMAIL)) {
                        throw new RuntimeException('E-posta adresi geçerli değil: ' . $mailCheck);
                    }
                }
                $phoneTaken = $pdo->prepare('SELECT id FROM users WHERE phone = :phone AND id <> :id LIMIT 1');
                $phoneTaken->execute(['phone' => $newPhone, 'id' => $targetId]);
                if ($phoneTaken->fetch()) {
                    throw new RuntimeException('Bu telefon numarası başka bir kullanıcıda kayıtlı.');
                }
                if ($newEmail !== '') {
                    $emailTaken = $pdo->prepare('SELECT id FROM users WHERE email = :email AND id <> :id LIMIT 1');
                    $emailTaken->execute(['email' => $newEmail, 'id' => $targetId]);
                    if ($emailTaken->fetch()) {
                        throw new RuntimeException('Bu e-posta adresi başka bir kullanıcıda kayıtlı.');
                    }
                }
                $nullable = static fn (string $key): ?string => ($value = clean_text((string)($_POST[$key] ?? ''))) !== '' ? $value : null;
                $newValues = [
                    'name' => $newName,
                    'phone' => $newPhone,
                    'email' => $newEmail !== '' ? $newEmail : null,
                    'company_name' => $nullable('company_name'),
                    'tax_office' => $nullable('tax_office'),
                    'tax_number' => $nullable('tax_number'),
                    'company_address' => $nullable('company_address'),
                    'invoice_email' => $newInvoiceEmail !== '' ? $newInvoiceEmail : null,
                ];
                $labels = ['name' => 'Ad', 'phone' => 'Telefon', 'email' => 'E-posta', 'company_name' => 'Firma', 'tax_office' => 'Vergi dairesi', 'tax_number' => 'Vergi no', 'company_address' => 'Firma adresi', 'invoice_email' => 'Fatura e-postası'];
                $changes = [];
                foreach ($newValues as $key => $value) {
                    if ((string)($target[$key] ?? '') !== (string)($value ?? '')) {
                        $changes[] = $labels[$key] . ': ' . ((string)($target[$key] ?? '') !== '' ? $target[$key] : '-') . ' → ' . ($value ?? '-');
                    }
                }
                if (!$changes) {
                    throw new RuntimeException('Değişiklik yapılmadı.');
                }
                $sets = [];
                foreach (array_keys($newValues) as $key) {
                    $sets[] = $key . ' = :' . $key;
                }
                // Telefon / e-posta degisirse dogrulama sifirlanir.
                if ($newPhone !== (string)$target['phone']) {
                    $sets[] = 'phone_verified_at = NULL';
                }
                if ((string)($newValues['email'] ?? '') !== (string)($target['email'] ?? '')) {
                    $sets[] = 'email_verified_at = NULL';
                }
                $pdo->prepare('UPDATE users SET ' . implode(', ', $sets) . ' WHERE id = :id')->execute($newValues + ['id' => $targetId]);
                admin_audit_log($pdo, $targetId, 'bilgi', implode('; ', $changes));
                $_SESSION['admin_userdetail_notice'] = $notice('Bilgiler kaydedildi', 'Kullanıcı bilgileri güncellendi.');
            } elseif ($userAction === 'admin_user_verify') {
                $kind = (string)($_POST['kind'] ?? '') === 'email' ? 'email' : 'phone';
                $set = (string)($_POST['mode'] ?? '') === 'set';
                $pdo->prepare('UPDATE users SET ' . $kind . '_verified_at = ' . ($set ? 'NOW()' : 'NULL') . ' WHERE id = :id')->execute(['id' => $targetId]);
                admin_audit_log($pdo, $targetId, 'dogrulama', ($kind === 'email' ? 'E-posta' : 'Telefon') . ($set ? ' doğrulandı olarak işaretlendi' : ' doğrulaması kaldırıldı'));
                $_SESSION['admin_userdetail_notice'] = $notice('Doğrulama güncellendi', ($kind === 'email' ? 'E-posta' : 'Telefon') . ($set ? ' doğrulanmış yapıldı.' : ' doğrulaması kaldırıldı.'));
            } elseif ($userAction === 'admin_user_password') {
                $newPassword = (string)($_POST['new_password'] ?? '');
                if (strlen($newPassword) < 8) {
                    throw new RuntimeException('Yeni şifre en az 8 karakter olmalı.');
                }
                $pdo->prepare('UPDATE users SET password_hash = :hash WHERE id = :id')->execute(['hash' => password_hash($newPassword, PASSWORD_DEFAULT), 'id' => $targetId]);
                admin_audit_log($pdo, $targetId, 'sifre', 'Şifre admin tarafından yenilendi');
                $_SESSION['admin_userdetail_notice'] = $notice('Şifre yenilendi', 'Kullanıcının şifresi güncellendi. Yeni şifreyi kullanıcıya iletmeyi unutmayın.');
            } elseif ($userAction === 'admin_user_grant_plan') {
                $planStmt = $pdo->prepare('SELECT * FROM plans WHERE id = :id AND is_system = 0 LIMIT 1');
                $planStmt->execute(['id' => (int)($_POST['plan_id'] ?? 0)]);
                $grantPlan = $planStmt->fetch();
                if (!$grantPlan) {
                    throw new RuntimeException('Plan bulunamadı.');
                }
                $days = max(1, min(3650, (int)($_POST['days'] ?? PLAN_PERIOD_DAYS)));
                plan_activate($pdo, $targetId, (int)$grantPlan['id'], 'admin', $days);
                $pdo->prepare("INSERT INTO plan_payments (user_id, plan_id, plan_name, amount, method, status, paid_at, admin_note) VALUES (:user_id, :plan_id, :plan_name, 0, 'admin', 'paid', NOW(), :note)")
                    ->execute(['user_id' => $targetId, 'plan_id' => (int)$grantPlan['id'], 'plan_name' => (string)$grantPlan['name'], 'note' => 'Admin tarafından ' . $days . ' gün tanımlandı']);
                admin_audit_log($pdo, $targetId, 'plan', $grantPlan['name'] . ' planı ' . $days . ' gün tanımlandı');
                $_SESSION['admin_userdetail_notice'] = $notice('Plan tanımlandı', $grantPlan['name'] . ' planı ' . $days . ' gün için tanımlandı.');
            } elseif ($userAction === 'admin_user_revoke_plan') {
                $pdo->prepare("UPDATE plan_subscriptions SET status = 'cancelled' WHERE user_id = :id AND status = 'active'")->execute(['id' => $targetId]);
                plan_for_user($pdo, $targetId); // hesap turunu gunceller
                admin_audit_log($pdo, $targetId, 'plan', 'Plan admin tarafından bitirildi');
                $_SESSION['admin_userdetail_notice'] = $notice('Plan bitirildi', 'Kullanıcı Bireysel hesaba döndü.');
            }
        }

        if (isset($_POST['admin_change_password'])) {
            $redirectHash = 'password';
            $currentPassword = (string)($_POST['current_password'] ?? '');
            $newPassword = (string)($_POST['new_password'] ?? '');
            $confirmPassword = (string)($_POST['new_password_confirm'] ?? '');

            if (strlen($newPassword) < 8) {
                throw new RuntimeException('Yeni şifre en az 8 karakter olmalı.');
            }
            if ($newPassword !== $confirmPassword) {
                throw new RuntimeException('Yeni şifreler eşleşmiyor.');
            }

            $current = $pdo->prepare('SELECT password_hash FROM admin_users WHERE id = :id LIMIT 1');
            $current->execute(['id' => admin_current_id()]);
            $currentHash = (string)$current->fetchColumn();

            if ($currentHash === '' || !password_verify($currentPassword, $currentHash)) {
                throw new RuntimeException('Mevcut şifre hatalı.');
            }

            $update = $pdo->prepare('UPDATE admin_users SET password_hash = :hash WHERE id = :id');
            $update->execute([
                'hash' => password_hash($newPassword, PASSWORD_DEFAULT),
                'id' => admin_current_id(),
            ]);

            $_SESSION['admin_password_notice'] = [
                'type' => 'success',
                'title' => 'Şifre güncellendi',
                'message' => 'Yeni admin şifreniz kaydedildi. Bu şifre yalnızca admin paneli için geçerlidir.',
            ];
        }

        if (isset($_POST['admin_publish_android_release'])) {
            $redirectHash = 'android';
            // Surum kodu ve adi APK'nin kendisinden okunur (build.gradle'daki degerler); elle yazilmaz.
            require_once APP_PATH . '/Support/apk_info.php';
            $apkUpload = $_FILES['android_apk'] ?? null;
            $apkInfo = is_array($apkUpload) && !empty($apkUpload['tmp_name']) ? apk_read_version((string)$apkUpload['tmp_name']) : null;
            if ($apkInfo === null) {
                throw new RuntimeException('APK dosyasından sürüm bilgisi okunamadı. Android Studio ile derlenmiş (imzalı) bir APK seçin.');
            }
            $newCode = (int)$apkInfo['code'];
            $latestForCode = app_releases_latest($pdo, 'android');
            contacts_admin_require_newer_code($latestForCode, $newCode);
            // APK'da görünen sürüm yazısı (boş = APK kendi sürümünü yazar); yayınla ile birlikte kaydedilir.
            $displayVersion = trim((string)($_POST['apk_display_version'] ?? ''));
            if (mb_strlen($displayVersion, 'UTF-8') > 60) {
                throw new RuntimeException('Görünen sürüm yazısı en fazla 60 karakter olabilir.');
            }
            $release = app_releases_publish(
                $pdo,
                $apkUpload,
                $newCode,
                $apkInfo['name'] !== '' ? (string)$apkInfo['name'] : contacts_admin_version_name_for($latestForCode, $newCode),
                (string)($_POST['notes'] ?? '')
            );

            $message = sprintf('v%s (kod %d) yayınlandı.', $release['version_name'], (int)$release['version_code']);

            if (isset($_POST['notify_users'])) {
                $stats = app_releases_notify_all_users($pdo, $config, $release);
                $message .= sprintf(' E-posta bildirimi: %d/%d başarılı.', $stats['sent'], $stats['total']);
            }

            if (isset($_POST['notify_bell'])) {
                app_announcements_publish_release($pdo, $release);
                $message .= ' Zil bildirimi tüm kullanıcılara eklendi.';
            }

            $_SESSION['admin_android_notice'] = [
                'type' => 'success',
                'title' => 'Android sürümü yayınlandı',
                'message' => $message,
            ];
        }

        if (isset($_POST['admin_publish_windows_release'])) {
            $redirectHash = 'windows';
            $newCode = (int)($_POST['version_code'] ?? 0);
            $latestForCode = app_releases_latest($pdo, 'windows');
            contacts_admin_require_newer_code($latestForCode, $newCode);
            $release = app_releases_publish_windows(
                $pdo,
                $_FILES['windows_app'] ?? null,
                $newCode,
                contacts_admin_version_name_for($latestForCode, $newCode),
                (string)($_POST['notes'] ?? '')
            );

            $message = sprintf('v%s (kod %d) yayınlandı.', $release['version_name'], (int)$release['version_code']);

            if (isset($_POST['notify_users'])) {
                $stats = app_releases_notify_all_users($pdo, $config, $release, 'windows');
                $message .= sprintf(' E-posta bildirimi: %d/%d başarılı.', $stats['sent'], $stats['total']);
            }

            if (isset($_POST['notify_bell'])) {
                app_announcements_publish_release($pdo, $release, 'windows');
                $message .= ' Zil bildirimi tüm kullanıcılara eklendi.';
            }

            $_SESSION['admin_windows_notice'] = [
                'type' => 'success',
                'title' => 'PC sürümü yayınlandı',
                'message' => $message,
            ];
        }
    } catch (Throwable $exception) {
        $batchFailure = $exception->getMessage();
        $titles = [
            'windows' => 'PC sürümü yayınlanamadı',
            'android' => 'Sürüm yayınlanamadı',
            'password' => 'Şifre değiştirilemedi',
            'verification' => 'Doğrulama ayarları kaydedilemedi',
            'plans' => 'Plan kaydedilemedi',
            'payments' => 'İşlem tamamlanamadı',
            'paymentsettings' => 'Ödeme ayarları kaydedilemedi',
            'update' => 'Güncelleme uygulanamadı',
            'settings' => 'Yedek alınamadı',
            'userdetail' => 'İşlem tamamlanamadı',
        ];
        $sessionKeys = [
            'windows' => 'admin_windows_notice',
            'android' => 'admin_android_notice',
            'password' => 'admin_password_notice',
            'verification' => 'admin_verification_notice',
            'plans' => 'admin_plan_notice',
            'payments' => 'admin_plan_notice',
            'paymentsettings' => 'admin_plan_notice',
            'update' => 'admin_update_notice',
            'userdetail' => 'admin_userdetail_notice',
        ];
        $_SESSION[$sessionKeys[$redirectHash] ?? 'admin_update_notice'] = [
            'type' => 'error',
            'title' => $titles[$redirectHash] ?? 'İşlem tamamlanamadı',
            'message' => $exception->getMessage(),
        ];
    }

    // Planlar sayfasindaki "Tümünü kaydet": her plan ayri istekle kaydedilir; JSON yanit doner, tek bildirim gosterilir.
    $batchMode = (string)($_SERVER['HTTP_X_ADMIN_BATCH'] ?? '');
    if ($batchMode !== '') {
        unset($_SESSION['admin_plan_notice']);
        if ($batchFailure === null && $batchMode === 'last') {
            $_SESSION['admin_plan_notice'] = ['type' => 'success', 'title' => 'Planlar kaydedildi', 'message' => 'Tüm planlar kaydedildi.'];
        }
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['ok' => $batchFailure === null, 'message' => (string)$batchFailure], JSON_UNESCAPED_UNICODE);
        exit;
    }

    header('Location: ' . ($redirectUrl ?? ('./#' . $redirectHash)), true, 303);
    exit;
}

?><!doctype html>
<html lang="tr">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
    <meta name="theme-color" content="#116466">
    <title>MyContacts Admin</title>
    <link rel="icon" href="../assets/icons/icon.svg" type="image/svg+xml">
    <link rel="stylesheet" href="../assets/css/admin.css?v=20261221d">
</head>
<body>
    <div class="admin-shell">
        <aside class="admin-sidebar" aria-label="Admin menüsü">
            <a class="admin-brand" href="./" aria-label="Admin ana sayfa">
                <span>WEBIZA SOFT</span>
                <strong>MyContacts Admin</strong>
            </a>

            <nav class="admin-nav" aria-label="Admin bölümleri">
                <a class="is-active" href="#dashboard">
                    <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 13h7V4H4z"/><path d="M13 20h7V4h-7z"/><path d="M4 20h7v-5H4z"/></svg>
                    Dashboard
                </a>
                <a href="#users">
                    <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
                    Kullanıcılar
                </a>
                <a href="#plans">
                    <svg viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 10h18"/></svg>
                    Planlar
                </a>
                <a href="#payments">
                    <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 1v22"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>
                    Ödemeler
                </a>
                <a href="#paymentsettings">
                    <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 21h18M5 21V9l7-5 7 5v12M9 21v-6h6v6"/></svg>
                    Ödeme Ayarları
                </a>
                <a href="#android">
                    <svg viewBox="0 0 24 24" aria-hidden="true"><rect x="6" y="2" width="12" height="20" rx="2"/><path d="M9 18h6"/></svg>
                    Android Sürümü
                </a>
                <a href="#windows">
                    <svg viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="4" width="18" height="12" rx="2"/><path d="M8 20h8M12 16v4"/></svg>
                    PC Sürümü
                </a>
                <a href="#verification">
                    <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M20 6 9 17l-5-5"/><circle cx="12" cy="12" r="10"/></svg>
                    Doğrulama
                </a>
                <a href="#password">
                    <svg viewBox="0 0 24 24" aria-hidden="true"><rect x="4" y="10" width="16" height="11" rx="2"/><path d="M8 10V7a4 4 0 0 1 8 0v3"/></svg>
                    Şifre Değiştir
                </a>
                <a href="#settings">
                    <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 15.5A3.5 3.5 0 1 0 12 8a3.5 3.5 0 0 0 0 7.5Z"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06A1.65 1.65 0 0 0 15 19.4a1.65 1.65 0 0 0-1 .6 1.65 1.65 0 0 1-3.3 0 1.65 1.65 0 0 0-1-.6 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.6 15a1.65 1.65 0 0 0-.6-1 1.65 1.65 0 0 1 0-3.3 1.65 1.65 0 0 0 .6-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.6a1.65 1.65 0 0 0 1-.6 1.65 1.65 0 0 1 3.3 0 1.65 1.65 0 0 0 1 .6 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9c.38.14.7.36 1 .6a1.65 1.65 0 0 1 0 3.3c-.3.24-.62.46-1 .6Z"/></svg>
                    Ayarlar
                </a>
            </nav>

            <div class="admin-sidebar-footer">
                <form method="post">
                    <button type="submit" name="admin_logout" value="1" class="admin-logout-button">Çıkış Yap</button>
                </form>
            </div>
        </aside>

        <main class="admin-main">
            <header class="admin-topbar">
                <div>
                    <span>ADMIN PANEL</span>
                    <h1>Yönetim Merkezi</h1>
                </div>
            </header>

            <section class="admin-grid" id="dashboard" data-admin-section="dashboard" aria-label="Dashboard">
                <article class="metric-card">
                    <span>Kullanıcılar</span>
                    <strong><?= (int)$adminUserAll ?></strong>
                    <small>Toplam kayıt</small>
                </article>
                <article class="metric-card warning">
                    <span>Bekleyen onay</span>
                    <strong><?= (int)$adminPendingCount ?></strong>
                    <small>Havale ödemesi onay bekliyor</small>
                </article>
                <article class="metric-card">
                    <span>İşlem sayısı</span>
                    <strong><?= (int)$adminTransactionsToday ?></strong>
                    <small>Bugün</small>
                </article>
                <article class="metric-card danger">
                    <span>Sistem uyarısı</span>
                    <strong>0</strong>
                    <small>Aktif hata yok</small>
                </article>
            </section>

            <section class="admin-content" data-admin-tabs>
                <article class="admin-panel wide" id="users" data-admin-section="users">
                    <div class="panel-head">
                        <div>
                            <span>KULLANICILAR</span>
                            <h2>Kullanıcı yönetimi</h2>
                        </div>
                        <form class="admin-user-search" method="get" action="">
                            <input type="search" name="uq" value="<?= contacts_admin_h($userSearch) ?>" placeholder="Ad, telefon veya e-posta ara">
                            <button type="submit">Ara</button>
                            <?php if ($userSearch !== ''): ?><a class="admin-link-button" href="?#users">Temizle</a><?php endif; ?>
                        </form>
                    </div>
                    <p class="admin-help-text"><?= (int)$adminUserTotal ?> kullanıcı<?= $userSearch !== '' ? ' bulundu' : '' ?>.</p>
                    <div class="admin-table admin-users-table">
                        <div class="admin-table-row head">
                            <span>Ad</span>
                            <span>Telefon</span>
                            <span>E-posta</span>
                            <span>Hesap</span>
                            <span>Depolama</span>
                            <span>Kayıt</span>
                        </div>
                        <?php if (!$adminUsers): ?>
                            <div class="admin-table-row muted-row">
                                <span><?= $userSearch !== '' ? 'Aramaya uyan kullanıcı yok.' : 'Henüz kullanıcı yok.' ?></span>
                            </div>
                        <?php endif; ?>
                        <?php foreach ($adminUsers as $adminUser): ?>
                            <a class="admin-table-row is-link" href="?user=<?= (int)$adminUser['id'] ?>#userdetail">
                                <span><strong><?= contacts_admin_h((string)$adminUser['name']) ?></strong><?php if ((string)($adminUser['company_name'] ?? '') !== ''): ?><br><small><?= contacts_admin_h((string)$adminUser['company_name']) ?></small><?php endif; ?></span>
                                <span><?= contacts_admin_h((string)$adminUser['phone']) ?><?= !empty($adminUser['phone_verified_at']) ? ' ✓' : '' ?></span>
                                <span><?= contacts_admin_h((string)($adminUser['email'] ?? '')) ?><?= !empty($adminUser['email_verified_at']) ? ' ✓' : '' ?></span>
                                <span><?php if ($adminUser['plan_name'] !== null): ?><strong><?= contacts_admin_h((string)$adminUser['plan_name']) ?></strong><br><small>Bitiş: <?= contacts_admin_h(date('d.m.Y', strtotime((string)$adminUser['plan_expires_at']))) ?></small><?php else: ?>Bireysel<?php endif; ?></span>
                                <?php
                                $storageQuota = (int)($adminUser['storage_quota'] ?? 0);
                                $storageUsed = (int)($adminUser['storage_used'] ?? 0);
                                $storagePercent = $storageQuota > 0 ? (int)round($storageUsed / $storageQuota * 100) : 0;
                                $storageFmt = static fn (int $b): string => $b >= 1073741824 ? number_format($b / 1073741824, 2, ',', '.') . ' GB' : ($b >= 1048576 ? number_format($b / 1048576, 1, ',', '.') . ' MB' : number_format($b / 1024, 0, ',', '.') . ' KB');
                                ?>
                                <span<?= $storageQuota > 0 && $storagePercent >= 90 ? ' style="color:#b3261e;font-weight:800"' : '' ?>><?= contacts_admin_h($storageFmt($storageUsed)) ?><br><small><?= $storageQuota > 0 ? contacts_admin_h('/ ' . $storageFmt($storageQuota) . ' · %' . $storagePercent) : 'sınırsız' ?></small></span>
                                <span><?= contacts_admin_h(date('d.m.Y', strtotime((string)$adminUser['created_at']))) ?></span>
                            </a>
                        <?php endforeach; ?>
                    </div>
                    <?php if ($userPages > 1): ?>
                        <div class="admin-pager">
                            <?php $pagerBase = '?' . ($userSearch !== '' ? 'uq=' . rawurlencode($userSearch) . '&' : '') . 'up='; ?>
                            <?php if ($userPage > 1): ?><a class="admin-link-button" href="<?= contacts_admin_h($pagerBase . ($userPage - 1)) ?>#users">‹ Önceki</a><?php endif; ?>
                            <span><?= (int)$userPage ?> / <?= (int)$userPages ?></span>
                            <?php if ($userPage < $userPages): ?><a class="admin-link-button" href="<?= contacts_admin_h($pagerBase . ($userPage + 1)) ?>#users">Sonraki ›</a><?php endif; ?>
                        </div>
                    <?php endif; ?>
                </article>

                <?php if ($detailUser): ?>
                <?php $h = 'contacts_admin_h'; $dUid = (int)$detailUser['id']; ?>
                <article class="admin-panel wide update-panel" id="userdetail" data-admin-section="userdetail">
                    <div class="panel-head">
                        <div>
                            <span>KULLANICI</span>
                            <h2><?= $h((string)$detailUser['name']) ?></h2>
                        </div>
                        <a class="admin-link-button" href="./#users">← Kullanıcılar</a>
                    </div>
                    <?php if (is_array($userDetailNotice)): ?>
                        <div class="update-notice <?= ($userDetailNotice['type'] ?? '') === 'success' ? 'is-success' : 'is-error' ?>" role="status">
                            <strong><?= $h((string)($userDetailNotice['title'] ?? 'Bilgi')) ?></strong>
                            <span><?= $h((string)($userDetailNotice['message'] ?? '')) ?></span>
                        </div>
                    <?php endif; ?>

                    <div class="admin-detail-grid">
                        <form class="update-status-card admin-detail-card" method="post" autocomplete="off">
                            <input type="hidden" name="user_id" value="<?= $dUid ?>">
                            <div class="update-status-row"><strong>Hesap bilgileri</strong><span class="status-badge">Kayıt: <?= $h(date('d.m.Y', strtotime((string)$detailUser['created_at']))) ?></span></div>
                            <div class="admin-detail-fields">
                                <label class="admin-form-field"><span>Ad soyad</span><input type="text" name="name" value="<?= $h((string)$detailUser['name']) ?>" required></label>
                                <label class="admin-form-field"><span>Telefon</span><input type="tel" name="phone" value="<?= $h((string)$detailUser['phone']) ?>" inputmode="tel" required></label>
                                <label class="admin-form-field"><span>E-posta</span><input type="email" name="email" value="<?= $h((string)($detailUser['email'] ?? '')) ?>"></label>
                                <label class="admin-form-field"><span>Firma adı</span><input type="text" name="company_name" value="<?= $h((string)($detailUser['company_name'] ?? '')) ?>"></label>
                                <label class="admin-form-field"><span>Vergi dairesi</span><input type="text" name="tax_office" value="<?= $h((string)($detailUser['tax_office'] ?? '')) ?>"></label>
                                <label class="admin-form-field"><span>Vergi no</span><input type="text" name="tax_number" value="<?= $h((string)($detailUser['tax_number'] ?? '')) ?>"></label>
                                <label class="admin-form-field"><span>Firma adresi</span><input type="text" name="company_address" value="<?= $h((string)($detailUser['company_address'] ?? '')) ?>"></label>
                                <label class="admin-form-field"><span>Fatura e-postası</span><input type="email" name="invoice_email" value="<?= $h((string)($detailUser['invoice_email'] ?? '')) ?>"></label>
                            </div>
                            <p class="admin-help-text">Telefon veya e-posta değişirse o alanın doğrulaması sıfırlanır.</p>
                            <div class="admin-detail-actions"><button type="submit" name="admin_user_save" value="1" class="primary-action">Kaydet</button></div>
                        </form>

                        <div class="admin-detail-stack">
                            <section class="update-status-card admin-detail-card">
                                <div class="update-status-row"><strong>Doğrulama</strong></div>
                                <?php foreach (['phone' => ['Telefon', $detailUser['phone_verified_at']], 'email' => ['E-posta', $detailUser['email_verified_at']]] as $verifyKind => [$verifyLabel, $verifiedAt]): ?>
                                    <form class="admin-detail-row" method="post">
                                        <input type="hidden" name="user_id" value="<?= $dUid ?>">
                                        <input type="hidden" name="kind" value="<?= $verifyKind ?>">
                                        <input type="hidden" name="mode" value="<?= $verifiedAt ? 'clear' : 'set' ?>">
                                        <span><strong><?= $verifyLabel ?></strong> · <?= $verifiedAt ? 'Doğrulandı ✓ (' . $h(date('d.m.Y', strtotime((string)$verifiedAt))) . ')' : 'Doğrulanmadı' ?></span>
                                        <button type="submit" name="admin_user_verify" value="1" class="admin-link-button"><?= $verifiedAt ? 'Doğrulamayı kaldır' : 'Doğrulanmış yap' ?></button>
                                    </form>
                                <?php endforeach; ?>
                            </section>

                            <form class="update-status-card admin-detail-card" method="post" autocomplete="off" onsubmit="return confirm('Kullanıcının şifresi değiştirilecek. Devam edilsin mi?');">
                                <input type="hidden" name="user_id" value="<?= $dUid ?>">
                                <div class="update-status-row"><strong>Şifre yenile</strong></div>
                                <label class="admin-form-field"><span>Yeni şifre (en az 8 karakter)</span><input type="text" name="new_password" id="admin-user-new-password" minlength="8" autocomplete="off" required></label>
                                <div class="admin-detail-actions">
                                    <button type="button" class="admin-link-button" id="admin-user-generate-password">Rastgele üret</button>
                                    <button type="submit" name="admin_user_password" value="1" class="primary-action">Şifreyi yenile</button>
                                </div>
                                <p class="admin-help-text">Şifre kullanıcıya otomatik gönderilmez; kaydetmeden önce kopyalayıp ilettiğinizden emin olun.</p>
                            </form>
                        </div>

                        <section class="update-status-card admin-detail-card">
                            <div class="update-status-row"><strong>Plan</strong><span class="status-badge"><?= $detailPlan ? $h((string)$detailPlan['name']) : 'Bireysel' ?></span></div>
                            <?php if ($detailPlan): ?>
                                <p class="admin-help-text">Bitiş: <?= $h(date('d.m.Y H:i', strtotime((string)$detailPlan['expires_at']))) ?></p>
                                <form method="post" class="admin-detail-actions" onsubmit="return confirm('Kullanıcının planı bitirilecek. Devam edilsin mi?');">
                                    <input type="hidden" name="user_id" value="<?= $dUid ?>">
                                    <button type="submit" name="admin_user_revoke_plan" value="1" class="admin-link-button">Planı bitir</button>
                                </form>
                            <?php else: ?>
                                <p class="admin-help-text">Ücretsiz Bireysel hesap.</p>
                            <?php endif; ?>
                            <form method="post" class="admin-detail-fields" autocomplete="off">
                                <input type="hidden" name="user_id" value="<?= $dUid ?>">
                                <label class="admin-form-field"><span>Plan tanımla / süre ekle</span>
                                    <select name="plan_id">
                                        <?php foreach ($adminPlans as $planOption): ?>
                                            <?php if (empty($planOption['is_system'])): ?><option value="<?= (int)$planOption['id'] ?>"><?= $h((string)$planOption['name']) ?></option><?php endif; ?>
                                        <?php endforeach; ?>
                                    </select>
                                </label>
                                <label class="admin-form-field"><span>Gün</span><input type="number" name="days" min="1" max="3650" value="30"></label>
                                <div class="admin-detail-actions"><button type="submit" name="admin_user_grant_plan" value="1" class="primary-action">Plan tanımla</button></div>
                            </form>
                            <div class="update-status-row"><strong>Ödeme geçmişi</strong></div>
                            <?php if (!$detailPayments): ?><p class="admin-help-text">Ödeme kaydı yok.</p><?php endif; ?>
                            <?php foreach ($detailPayments as $payment): ?>
                                <div class="admin-detail-row"><span><?= $h(date('d.m.Y', strtotime((string)($payment['paid_at'] ?: $payment['created_at'])))) ?> · <?= $h((string)$payment['plan_name']) ?> · <?= $h(number_format((float)$payment['amount'], 2, ',', '.')) ?> ₺</span><small><?= $h((string)$payment['method']) ?> · <?= $h((string)$payment['status']) ?></small></div>
                            <?php endforeach; ?>
                        </section>

                        <section class="update-status-card admin-detail-card">
                            <div class="update-status-row"><strong>İşlem kaydı</strong></div>
                            <?php if (!$detailAudit): ?><p class="admin-help-text">Henüz işlem yapılmadı.</p><?php endif; ?>
                            <?php foreach ($detailAudit as $audit): ?>
                                <div class="admin-detail-row"><span><strong><?= $h((string)$audit['action']) ?></strong> · <?= $h((string)($audit['detail'] ?? '')) ?></span><small><?= $h(date('d.m.Y H:i', strtotime((string)$audit['created_at']))) ?><?= !empty($audit['admin_email']) ? ' · ' . $h((string)$audit['admin_email']) : '' ?></small></div>
                            <?php endforeach; ?>
                        </section>
                    </div>
                </article>
                <?php endif; ?>

                <article class="admin-panel wide update-panel" id="verification" data-admin-section="verification">
                    <div class="panel-head">
                        <div>
                            <span>DOĞRULAMA</span>
                            <h2>Doğrulama ve e-posta ayarları</h2>
                        </div>
                    </div>

                    <p class="admin-help-text">E-posta doğrulaması her zaman zorunludur (üyelik kod onaylanmadan tamamlanmaz). Telefon doğrulaması ise yalnızca burada açtığınızda devreye girer: açıldığında doğrulanmamış kullanıcılara uygulamanın üstünde uyarı gösterilir. Netgsm bilgilerini girmeden açmayın.</p>

                    <?php if (is_array($verificationNotice)): ?>
                        <div class="update-notice <?= ($verificationNotice['type'] ?? '') === 'success' ? 'is-success' : 'is-error' ?>" role="status">
                            <strong><?= contacts_admin_h((string)($verificationNotice['title'] ?? 'Bilgi')) ?></strong>
                            <span><?= contacts_admin_h((string)($verificationNotice['message'] ?? '')) ?></span>
                        </div>
                    <?php endif; ?>

                    <div class="admin-verification-grid">
                        <div class="admin-verification-col">
                        <section class="update-status-card">
                            <div class="update-status-row">
                                <strong>Telefon doğrulaması</strong>
                                <span class="status-badge"><?= $phoneVerificationEnabled ? 'AÇIK' : 'KAPALI' ?></span>
                            </div>
                            <p><?= $phoneVerificationEnabled
                                ? 'Kullanıcılardan telefon doğrulaması isteniyor.'
                                : 'Kapalı. Kullanıcılardan telefon doğrulaması istenmiyor.' ?></p>
                        </section>

                        <form class="update-form" method="post" autocomplete="off">
                            <label class="admin-form-field">
                                <span>Netgsm kullanıcı kodu</span>
                                <input type="text" name="netgsm_usercode" value="<?= contacts_admin_h($netgsmSettings['usercode']) ?>" placeholder="8503021234">
                            </label>

                            <label class="admin-form-field">
                                <span>Netgsm şifresi</span>
                                <input type="text" name="netgsm_password" value="<?= contacts_admin_h($netgsmSettings['password']) ?>" placeholder="Netgsm panel şifresi">
                            </label>

                            <label class="admin-form-field">
                                <span>Mesaj başlığı (msgheader)</span>
                                <input type="text" name="netgsm_msgheader" value="<?= contacts_admin_h($netgsmSettings['msgheader']) ?>" placeholder="WEBIZASOFT">
                            </label>

                            <label class="admin-form-field admin-form-checkbox">
                                <input type="checkbox" name="phone_verification_enabled" value="1" <?= $phoneVerificationEnabled ? 'checked' : '' ?>>
                                <span>Telefon doğrulamasını aktif et</span>
                            </label>

                            <div class="update-actions">
                                <button type="submit" name="admin_save_verification" value="1" class="primary-action">Kaydet</button>
                            </div>
                        </form>

                        </div>
                        <div class="admin-verification-col">
                            <section class="update-status-card">
                                <div class="update-status-row">
                                    <strong>E-posta (SMTP)</strong>
                                    <span class="status-badge"><?= ($mailSettings['host'] !== '' && $mailSettings['user'] !== '' && $mailSettings['pass'] !== '') ? 'AYARLI' : 'AYARSIZ' ?></span>
                                </div>
                                <p>Doğrulama kodu, şifre yenileme ve sürüm bildirimi e-postaları buradan gönderilir. Boş bırakılan alanlar için sunucudaki config dosyası kullanılır.</p>
                            </section>

                            <form class="update-form" method="post" autocomplete="off">
                                <label class="admin-form-field"><span>SMTP sunucu</span><input type="text" name="smtp_host" value="<?= contacts_admin_h((string)$mailSettings['host']) ?>" placeholder="mail.alanadiniz.com"></label>
                                <div class="admin-mail-row">
                                    <label class="admin-form-field"><span>Port</span><input type="number" name="smtp_port" min="1" max="65535" value="<?= (int)$mailSettings['port'] ?>"></label>
                                    <label class="admin-form-field"><span>Güvenlik</span>
                                        <select name="smtp_secure">
                                            <option value="ssl" <?= $mailSettings['secure'] === 'ssl' ? 'selected' : '' ?>>SSL (465)</option>
                                            <option value="tls" <?= $mailSettings['secure'] === 'tls' ? 'selected' : '' ?>>TLS / STARTTLS (587)</option>
                                            <option value="none" <?= $mailSettings['secure'] === 'none' ? 'selected' : '' ?>>Yok</option>
                                        </select>
                                    </label>
                                </div>
                                <label class="admin-form-field"><span>Kullanıcı adı</span><input type="text" name="smtp_user" value="<?= contacts_admin_h((string)$mailSettings['user']) ?>" placeholder="no-reply@alanadiniz.com"></label>
                                <label class="admin-form-field"><span>Şifre</span><input type="password" name="smtp_pass" value="<?= contacts_admin_h((string)$mailSettings['pass']) ?>" placeholder="E-posta hesabı şifresi" autocomplete="new-password"></label>
                                <label class="admin-form-field"><span>Gönderen e-posta</span><input type="text" name="smtp_from_email" value="<?= contacts_admin_h((string)($mailSettings['from_email'] ?? '')) ?>" placeholder="no-reply@alanadiniz.com"></label>
                                <div class="update-actions"><button type="submit" name="admin_save_mail" value="1" class="primary-action">Kaydet</button></div>
                            </form>

                            <form class="update-form" method="post" autocomplete="off">
                                <label class="admin-form-field"><span>Test e-postası gönder</span><input type="email" name="test_email" placeholder="ornek@eposta.com" required></label>
                                <div class="update-actions"><button type="submit" name="admin_test_mail" value="1">Test gönder</button></div>
                            </form>

                            <section class="update-status-card">
                                <div class="update-status-row">
                                    <strong>Tanıtım ve iletişim</strong>
                                    <span class="status-badge"><?= $promoSettings['promo_phone'] . $promoSettings['promo_whatsapp'] . $promoSettings['promo_email'] . $promoSettings['promo_instagram'] !== '' ? 'AYARLI' : 'EKSİK' ?></span>
                                </div>
                                <p>Müşterilere gönderilen kayıt özeti (davet) sayfasının altında "Uygulama hakkında" bölümünde gösterilir. Boş bırakılan alan görünmez.</p>
                            </section>

                            <form class="update-form" method="post" autocomplete="off">
                                <label class="admin-form-field"><span>Kısa tanıtım (en fazla 600 karakter)</span><textarea name="promo_about" rows="4" maxlength="600" placeholder="Boş bırakılırsa hazır metin kullanılır"><?= contacts_admin_h($promoSettings['promo_about']) ?></textarea></label>
                                <label class="admin-form-field"><span>Web sitesi</span><input type="text" name="promo_website" value="<?= contacts_admin_h($promoSettings['promo_website']) ?>" placeholder="https://mycontacts.tr"></label>
                                <label class="admin-form-field"><span>Telefon</span><input type="text" name="promo_phone" value="<?= contacts_admin_h($promoSettings['promo_phone']) ?>" placeholder="+90 5xx xxx xx xx"></label>
                                <label class="admin-form-field"><span>WhatsApp numarası</span><input type="text" name="promo_whatsapp" value="<?= contacts_admin_h($promoSettings['promo_whatsapp']) ?>" placeholder="+90 5xx xxx xx xx"></label>
                                <label class="admin-form-field"><span>E-posta</span><input type="text" name="promo_email" value="<?= contacts_admin_h($promoSettings['promo_email']) ?>" placeholder="info@alanadiniz.com"></label>
                                <label class="admin-form-field"><span>Instagram kullanıcı adı</span><input type="text" name="promo_instagram" value="<?= contacts_admin_h($promoSettings['promo_instagram']) ?>" placeholder="kullaniciadi"></label>
                                <div class="update-actions"><button type="submit" name="admin_save_promo" value="1" class="primary-action">Kaydet</button></div>
                            </form>
                        </div>
                    </div>
                </article>

                <article class="admin-panel wide update-panel" id="password" data-admin-section="password">
                    <div class="panel-head">
                        <div>
                            <span>GÜVENLİK</span>
                            <h2>Şifre değiştir</h2>
                        </div>
                    </div>

                    <p class="admin-help-text">Bu şifre yalnızca admin paneli için geçerlidir; MyContacts uygulamasındaki normal hesap şifrenizle ilgisi yoktur.</p>

                    <?php if (is_array($passwordNotice)): ?>
                        <div class="update-notice <?= ($passwordNotice['type'] ?? '') === 'success' ? 'is-success' : 'is-error' ?>" role="status">
                            <strong><?= contacts_admin_h((string)($passwordNotice['title'] ?? 'Bilgi')) ?></strong>
                            <span><?= contacts_admin_h((string)($passwordNotice['message'] ?? '')) ?></span>
                        </div>
                    <?php endif; ?>

                    <form class="update-form" method="post" autocomplete="off">
                        <label class="admin-form-field">
                            <span>Mevcut şifre</span>
                            <input type="password" name="current_password" autocomplete="current-password" required>
                        </label>

                        <label class="admin-form-field">
                            <span>Yeni şifre</span>
                            <input type="password" name="new_password" autocomplete="new-password" minlength="8" placeholder="En az 8 karakter" required>
                        </label>

                        <label class="admin-form-field">
                            <span>Yeni şifre (tekrar)</span>
                            <input type="password" name="new_password_confirm" autocomplete="new-password" minlength="8" required>
                        </label>

                        <div class="update-actions">
                            <button type="submit" name="admin_change_password" value="1" class="primary-action">Şifreyi güncelle</button>
                        </div>
                    </form>
                </article>

<article class="admin-panel wide update-panel" id="plans" data-admin-section="plans">
                    <div class="panel-head">
                        <div>
                            <span>KURUMSAL</span>
                            <h2>Planlar</h2>
                        </div>
                        <button class="admin-icon-button" type="button" data-plan-add aria-label="Plan ekle" title="Plan ekle"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg></button>
                    </div>

                    <p class="admin-help-text">Kullanıcılar Bireysel (ücretsiz) başlar. Burada tanımladığınız planlar aylık ücretle Kurumsal hesap olarak satılır. <strong>Rakam kutusu boş veya 0 ise sınırsız</strong> olur; tik kapalıysa özellik o planda yoktur. Fiyatı 0 olan veya pasif planlar kullanıcılara gösterilmez. Ekip ve Mobil Arayan Tanıma özelliklerini plan bazında açıp kapatabilirsiniz.</p>

                    <?php if (is_array($planNotice)): ?>
                        <div class="update-notice <?= ($planNotice['type'] ?? '') === 'success' ? 'is-success' : 'is-error' ?>" role="status">
                            <strong><?= contacts_admin_h((string)($planNotice['title'] ?? 'Bilgi')) ?></strong>
                            <span><?= contacts_admin_h((string)($planNotice['message'] ?? '')) ?></span>
                        </div>
                    <?php endif; ?>

                    <div class="admin-plan-list">
                    <?php foreach ($adminPlans as $plan): ?>
                        <?php $isSystemPlan = !empty($plan['is_system']); ?>
                        <form class="update-status-card admin-plan-form" method="post" autocomplete="off">
                            <input type="hidden" name="plan_id" value="<?= (int)$plan['id'] ?>">
                            <button type="submit" name="admin_save_plan" value="1" class="admin-visually-hidden" tabindex="-1" aria-hidden="true">Kaydet</button>
                            <?php if ($isSystemPlan): ?><div class="update-status-row"><strong>Ücretsiz plan</strong><span class="status-badge">Sistem</span></div><?php else: ?><div class="update-status-row"><strong>Ücretli plan</strong><span class="status-badge" data-plan-status><?= !empty($plan['is_active']) ? 'Aktif' : 'Pasif' ?></span></div><?php endif; ?>
                            <?php admin_plan_fields($plan, $isSystemPlan, 0); ?>
                            <div class="update-actions">
                                <?php admin_plan_position_field($plan, $isSystemPlan, 0); ?>
                                <?php if (!$isSystemPlan): ?><button type="submit" name="admin_delete_plan" value="1" formnovalidate data-confirm="Bu plan silinsin mi? (Kullanılmışsa yalnızca pasif yapılır.)" data-confirm-title="Plan silinsin mi?">Sil</button><?php else: ?><button type="button" disabled title="Ücretsiz plan silinemez">Sil</button><?php endif; ?>
                            </div>
                        </form>
                    <?php endforeach; ?>

                    </div>
                    <p class="admin-help-text" data-plans-error style="color:#b02a37" hidden></p>
                    <div class="update-actions admin-plans-saveall">
                        <button type="button" class="primary-action" data-plans-save-all>Tümünü kaydet</button>
                    </div>
                </article>

                <div class="admin-modal" data-confirm-modal hidden>
                    <div class="admin-modal-panel admin-confirm-panel" role="alertdialog" aria-modal="true">
                        <h3 data-confirm-title>Onay</h3>
                        <p data-confirm-message></p>
                        <div class="update-actions">
                            <button type="button" data-confirm-cancel>Vazgeç</button>
                            <button type="button" class="primary-action" data-confirm-ok>Evet, devam et</button>
                        </div>
                    </div>
                </div>

                <div class="admin-modal" data-grant-modal hidden>
                    <div class="admin-modal-panel">
                    <form class="update-status-card update-form admin-plan-modal-form" method="post" autocomplete="off">
                        <div class="update-status-row"><strong>Kullanıcıya plan tanımla</strong><button class="admin-icon-button" type="button" data-grant-modal-close aria-label="Kapat" title="Kapat"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M18 6 6 18M6 6l12 12"/></svg></button></div>
                        <p class="admin-help-text">Telefon numarasına göre kullanıcıya ödeme almadan plan verir (test, hediye veya elden tahsilat için). Aynı plan tekrar verilirse süre uzar.</p>
                        <label class="admin-form-field"><span>Kullanıcı telefonu</span><input type="tel" name="user_phone" placeholder="+90 5xx xxx xx xx" required></label>
                        <label class="admin-form-field"><span>Plan</span>
                            <select name="plan_id">
                                <?php foreach ($adminPlans as $plan): ?>
                                    <?php if (!empty($plan['is_system'])) { continue; } ?>
                                    <option value="<?= (int)$plan['id'] ?>"><?= contacts_admin_h((string)$plan['name']) ?><?= empty($plan['is_active']) ? ' (pasif)' : '' ?></option>
                                <?php endforeach; ?>
                            </select>
                        </label>
                        <label class="admin-form-field"><span>Süre (gün)</span><input type="number" name="days" min="1" max="3650" value="30"></label>
                        <div class="update-actions"><button type="submit" name="admin_grant_plan" value="1" class="primary-action">Planı tanımla</button></div>
                    </form>
                    </div>
                </div>

                <div class="admin-modal" data-plan-modal hidden>
                    <div class="admin-modal-panel">
                    <form class="update-status-card admin-plan-form admin-plan-modal-form" method="post" autocomplete="off">
                        <div class="update-status-row"><strong>Yeni plan ekle</strong><button class="admin-icon-button" type="button" data-plan-modal-close aria-label="Kapat" title="Kapat"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M18 6 6 18M6 6l12 12"/></svg></button></div>
                        <input type="hidden" name="plan_id" value="0">
                        <?php admin_plan_fields(null, false, count($adminPlans)); ?>
                        <div class="update-actions">
                            <?php admin_plan_position_field(null, false, count($adminPlans)); ?>
                            <button type="submit" name="admin_save_plan" value="1" class="primary-action">Planı ekle</button>
                        </div>
                    </form>
                    </div>
                </div>


                <article class="admin-panel wide update-panel" id="payments" data-admin-section="payments">
                    <div class="panel-head">
                        <div>
                            <span>KURUMSAL</span>
                            <h2>Ödemeler ve abonelikler</h2>
                        </div>
                        <button class="admin-icon-button" type="button" data-grant-add aria-label="Kullanıcıya plan tanımla" title="Kullanıcıya plan tanımla"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg></button>
                    </div>

                    <?php if (is_array($planNotice)): ?>
                        <div class="update-notice <?= ($planNotice['type'] ?? '') === 'success' ? 'is-success' : 'is-error' ?>" role="status">
                            <strong><?= contacts_admin_h((string)($planNotice['title'] ?? 'Bilgi')) ?></strong>
                            <span><?= contacts_admin_h((string)($planNotice['message'] ?? '')) ?></span>
                        </div>
                    <?php endif; ?>

                    <div class="admin-payments-grid">
                    <section class="update-status-card">
                        <div class="update-status-row"><strong>Bekleyen havale ödemeleri</strong><span class="status-badge"><?= (int)$adminPendingCount ?></span></div>
                        <?php if (!$adminPendingPayments): ?>
                            <p>Bekleyen havale ödemesi yok.</p>
                        <?php endif; ?>
                        <?php foreach ($adminPendingPayments as $payment): ?>
                            <?php $paymentRejected = $payment['status'] === 'rejected'; ?>
                            <form class="admin-payment-row<?= $paymentRejected ? ' is-rejected' : '' ?>" method="post">
                                <input type="hidden" name="payment_id" value="<?= (int)$payment['id'] ?>">
                                <div>
                                    <strong><?= contacts_admin_h((string)$payment['user_name']) ?> · <?= contacts_admin_h((string)$payment['user_phone']) ?><?php if ($paymentRejected): ?> <span class="status-badge is-rejected">Reddedildi</span><?php endif; ?></strong>
                                    <small><?= contacts_admin_h((string)($payment['company_name'] ?? '')) ?> — <?= contacts_admin_h((string)$payment['plan_name']) ?> — <?= contacts_admin_h(number_format((float)$payment['amount'], 2, ',', '.')) ?> ₺ — Açıklama kodu: <b><?= contacts_admin_h((string)$payment['merchant_oid']) ?></b> — <?= contacts_admin_h((string)$payment['created_at']) ?></small>
                                </div>
                                <input type="text" name="admin_note" placeholder="Not (isteğe bağlı)" value="<?= $paymentRejected ? contacts_admin_h((string)($payment['admin_note'] ?? '')) : '' ?>">
                                <div class="update-actions">
                                    <?php if (!$paymentRejected): ?><button type="submit" name="admin_payment_reject" value="1" data-confirm="Bu ödeme reddedilsin mi? Reddedilen ödeme bu listede kalır, hata olduysa sonradan onaylayabilirsiniz." data-confirm-title="Ödeme reddedilsin mi?">Reddet</button><?php endif; ?>
                                    <button type="submit" name="admin_payment_approve" value="1" class="primary-action" <?= $paymentRejected ? 'data-confirm="Reddedilmiş ödeme onaylansın mı? Plan kullanıcıya hemen etkinleştirilir." data-confirm-title="Ödeme onaylansın mı?"' : '' ?>><?= $paymentRejected ? 'Yine de onayla' : 'Ödeme alındı, onayla' ?></button>
                                </div>
                            </form>
                        <?php endforeach; ?>
                    </section>

                    <section class="update-status-card">
                        <div class="update-status-row"><strong>Aktif abonelikler</strong><span class="status-badge"><?= count($adminActiveSubscriptions) ?></span></div>
                        <?php if (!$adminActiveSubscriptions): ?>
                            <p>Aktif Kurumsal abonelik yok.</p>
                        <?php endif; ?>
                        <?php foreach ($adminActiveSubscriptions as $subscription): ?>
                            <form class="admin-payment-row admin-sub-row" method="post">
                                <input type="hidden" name="subscription_id" value="<?= (int)$subscription['id'] ?>">
                                <div>
                                    <strong><?= contacts_admin_h((string)$subscription['user_name']) ?> · <?= contacts_admin_h((string)$subscription['user_phone']) ?></strong>
                                    <small><?= contacts_admin_h((string)($subscription['company_name'] ?? '')) ?> — <?= contacts_admin_h((string)$subscription['plan_name']) ?> — bitiş: <?= contacts_admin_h((string)$subscription['expires_at']) ?> (<?= contacts_admin_h((string)$subscription['source']) ?>)</small>
                                </div>
                                <button class="admin-icon-button is-danger" type="submit" name="admin_revoke_plan" value="1" aria-label="Planı kaldır" title="Planı kaldır" data-confirm="Bu kullanıcının planı kaldırılsın mı? Hesap Bireysel'e döner, verileri silinmez." data-confirm-title="Plan kaldırılsın mı?"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 6h18"/><path d="M8 6V4h8v2"/><path d="M19 6l-1 14H6L5 6"/><path d="M10 11v6M14 11v6"/></svg></button>
                            </form>
                        <?php endforeach; ?>
                    </section>

                    <section class="update-status-card admin-payments-wide">
                        <div class="update-status-row"><strong>Son ödemeler</strong><span class="status-badge">Son 30</span></div>
                        <?php if (!$adminRecentPayments): ?>
                            <p>Henüz kayıt yok.</p>
                        <?php endif; ?>
                        <?php foreach ($adminRecentPayments as $payment): ?>
                            <p><?= contacts_admin_h((string)$payment['created_at']) ?> — <strong><?= contacts_admin_h((string)$payment['user_name']) ?></strong> (<?= contacts_admin_h((string)$payment['user_phone']) ?>) — <?= contacts_admin_h((string)$payment['plan_name']) ?> — <?= contacts_admin_h(number_format((float)$payment['amount'], 2, ',', '.')) ?> ₺ — <?= contacts_admin_h((string)$payment['method']) ?> — <b><?= contacts_admin_h((string)$payment['status']) ?></b><?= !empty($payment['admin_note']) ? ' — ' . contacts_admin_h((string)$payment['admin_note']) : '' ?></p>
                        <?php endforeach; ?>
                    </section>
                    </div>
                </article>

                <article class="admin-panel wide update-panel" id="paymentsettings" data-admin-section="paymentsettings">
                    <div class="panel-head">
                        <div>
                            <span>ÖDEME</span>
                            <h2>Havale ve PayTR ayarları</h2>
                        </div>
                    </div>

                    <p class="admin-help-text">Kullanıcı Kurumsal plan alırken bu seçeneklerden ödeme yapar. IBAN girilirse <strong>Havale</strong> görünür; PayTR bilgileri girilip açılırsa <strong>Kartla ödeme</strong> görünür.</p>

                    <?php if (is_array($planNotice)): ?>
                        <div class="update-notice <?= ($planNotice['type'] ?? '') === 'success' ? 'is-success' : 'is-error' ?>" role="status">
                            <strong><?= contacts_admin_h((string)($planNotice['title'] ?? 'Bilgi')) ?></strong>
                            <span><?= contacts_admin_h((string)($planNotice['message'] ?? '')) ?></span>
                        </div>
                    <?php endif; ?>

                    <form class="update-form admin-payment-settings-form" method="post" autocomplete="off">
                        <section class="update-status-card">
                            <div class="update-status-row"><strong>Havale / EFT</strong><span class="status-badge"><?= $planPaymentSettings['bank_iban'] !== '' ? 'AKTİF' : 'KAPALI' ?></span></div>
                            <label class="admin-form-field"><span>Banka adı</span><input type="text" name="bank_name" value="<?= contacts_admin_h($planPaymentSettings['bank_name']) ?>" placeholder="Örn. Ziraat Bankası"></label>
                            <label class="admin-form-field"><span>Hesap sahibi</span><input type="text" name="bank_holder" value="<?= contacts_admin_h($planPaymentSettings['bank_holder']) ?>"></label>
                            <label class="admin-form-field"><span>IBAN</span><input type="text" name="bank_iban" value="<?= contacts_admin_h($planPaymentSettings['bank_iban']) ?>" placeholder="TR00 0000 0000 0000 0000 0000 00"></label>
                            <label class="admin-form-field"><span>Ödeme notu (kullanıcıya gösterilir)</span><input type="text" name="bank_note" value="<?= contacts_admin_h($planPaymentSettings['bank_note']) ?>" placeholder="Örn. Açıklama kısmına verilen kodu yazınız."></label>
                        </section>

                        <section class="update-status-card">
                            <div class="update-status-row"><strong>PayTR (kartla ödeme)</strong><span class="status-badge"><?= plan_paytr_available($planPaymentSettings) ? 'AKTİF' : 'KAPALI' ?></span></div>
                            <p class="admin-help-text">PayTR mağaza panelinde <strong>Bildirim URL</strong> alanına şu adresi girin: <code><?= contacts_admin_h((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'alanadiniz') . '/api/paytr/callback') ?></code></p>
                            <label class="admin-form-field"><span>Mağaza No (merchant_id)</span><input type="text" name="paytr_merchant_id" value="<?= contacts_admin_h($planPaymentSettings['paytr_merchant_id']) ?>"></label>
                            <label class="admin-form-field"><span>Mağaza Parolası (merchant_key) <?= $planPaymentSettings['paytr_merchant_key'] !== '' ? '— kayıtlı, değiştirmek için yazın' : '' ?></span><input type="password" name="paytr_merchant_key" placeholder="<?= $planPaymentSettings['paytr_merchant_key'] !== '' ? '••••••••' : '' ?>"></label>
                            <label class="admin-form-field"><span>Mağaza Gizli Anahtarı (merchant_salt) <?= $planPaymentSettings['paytr_merchant_salt'] !== '' ? '— kayıtlı, değiştirmek için yazın' : '' ?></span><input type="password" name="paytr_merchant_salt" placeholder="<?= $planPaymentSettings['paytr_merchant_salt'] !== '' ? '••••••••' : '' ?>"></label>
                            <label class="admin-form-field admin-form-checkbox"><input type="checkbox" name="paytr_test_mode" value="1" <?= $planPaymentSettings['paytr_test_mode'] ? 'checked' : '' ?>><span>Test modu (gerçek para çekilmez)</span></label>
                            <label class="admin-form-field admin-form-checkbox"><input type="checkbox" name="paytr_enabled" value="1" <?= $planPaymentSettings['paytr_enabled'] ? 'checked' : '' ?>><span>Kartla ödemeyi aktif et</span></label>
                        </section>

                        <div class="update-actions"><button type="submit" name="admin_save_payment_settings" value="1" class="primary-action">Kaydet</button></div>
                    </form>
                </article>

                <article class="admin-panel wide" id="settings" data-admin-section="settings">
                    <div class="panel-head">
                        <div>
                            <span>SİSTEM</span>
                            <h2>Ayar ve bakım</h2>
                        </div>
                        <form method="post" class="admin-inline-form">
                            <input type="hidden" name="backup_origin" value="settings">
                            <button type="submit" name="admin_download_full_backup" value="1">Yedek al ve indir</button>
                        </form>
                    </div>
                    <?php if (is_array($updateNotice) && ($updateNotice['type'] ?? '') === 'error'): ?>
                        <div class="update-notice is-error" role="status">
                            <strong><?= contacts_admin_h((string)($updateNotice['title'] ?? 'Hata')) ?></strong>
                            <span><?= contacts_admin_h((string)($updateNotice['message'] ?? '')) ?></span>
                        </div>
                    <?php endif; ?>
                    <p class="admin-help-text">Sayfa her açıldığında sistem anlık kontrol edilir. Sürüm yükleme ve geri alma işlemleri için bu sayfanın en altındaki Güncelleme bölümünü kullanın.</p>
                    <?php
                    // Sol sutun: sistem bilgileri; sag sutun: yedekleme bilgileri (sunucu diski yedeklerin saklandigi yer oldugu icin burada)
                    $isBackupCheck = static fn (string $label): bool => str_starts_with($label, 'Sunucu diski') || str_starts_with($label, 'Panelden elle') || str_starts_with($label, 'Otomatik yedek') || str_starts_with($label, 'pCloud');
                    $checkGroups = [
                        'Sistem' => array_filter($systemChecks, static fn (array $check): bool => !$isBackupCheck($check[0])),
                        'Yedekleme' => array_filter($systemChecks, static fn (array $check): bool => $isBackupCheck($check[0])),
                    ];
                    ?>
                    <div class="admin-checks-grid">
                        <?php foreach ($checkGroups as $groupTitle => $groupChecks): ?>
                            <div class="admin-checks-col">
                                <h3 class="admin-subhead"><?= contacts_admin_h($groupTitle) ?></h3>
                                <div class="setting-list">
                                    <?php foreach ($groupChecks as [$checkLabel, $checkState, $checkDetail]): ?>
                                        <div>
                                            <span><?= contacts_admin_h($checkLabel) ?></span>
                                            <strong class="check-<?= contacts_admin_h($checkState) ?>"><?= contacts_admin_h($checkDetail) ?></strong>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <h3 class="admin-subhead">Yedek kayıtları</h3>
                    <div class="setting-list">
                        <?php if (!$backupHistory): ?>
                            <div><span>Henüz kayıt yok.</span><strong class="check-warn">İlk yedek bu gece 03:00'te alınacak</strong></div>
                        <?php endif; ?>
                        <?php foreach ($backupHistory as $entry): ?>
                            <?php
                            $entryMode = match ($entry['mode'] ?? '') { 'weekly' => 'Haftalık tam yedek', 'user' => 'Kullanıcı yedekleri', default => 'Günlük yedek' };
                            $entryState = empty($entry['ok']) || ($entry['remote'] ?? '') === 'failed' ? 'bad' : (($entry['mode'] ?? '') !== 'user' && ($entry['remote'] ?? '') !== 'ok' ? 'warn' : 'ok');
                            ?>
                            <div>
                                <span><?= contacts_admin_h(date('d.m.Y H:i', (int)strtotime((string)$entry['time']))) ?> · <?= contacts_admin_h($entryMode) ?><?= !empty($entry['size']) ? ' · ' . contacts_admin_h($formatBytes((float)$entry['size'])) : '' ?></span>
                                <strong class="check-<?= $entryState ?>"><?= contacts_admin_h((string)($entry['message'] ?? '')) ?></strong>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </article>

                <article class="admin-panel wide update-panel" id="update" data-admin-section="settings">
                    <div class="panel-head">
                        <div>
                            <span>GÜNCELLEME</span>
                            <h2>Bakım paketi</h2>
                        </div>
                        <button type="button">Geçmiş</button>
                    </div>

                    <p class="admin-help-text">Bakım paketini ZIP olarak yükleyip bu site üzerinde uygulayabilirsiniz. ZIP önce kontrol edilir, mevcut uygulama ve veritabanı yedeklenir, sonra yalnızca güvenli dosyalar ve migration SQL dosyaları uygulanır.</p>

                    <?php if (is_array($updateNotice)): ?>
                        <div class="update-notice <?= ($updateNotice['type'] ?? '') === 'success' ? 'is-success' : 'is-error' ?>" role="status">
                            <strong><?= contacts_admin_h((string)($updateNotice['title'] ?? 'Bilgi')) ?></strong>
                            <span><?= contacts_admin_h((string)($updateNotice['message'] ?? '')) ?></span>
                        </div>
                    <?php endif; ?>

                    <section class="update-status-card">
                        <div class="update-status-row">
                            <strong>Manuel bakım</strong>
                            <span class="status-badge">Süper admin</span>
                        </div>
                        <p><strong>Kurulu sürüm:</strong> <?= contacts_admin_h($currentVersion) ?></p>
                        <p>Normal güncellemede korunacak klasörler: <strong>app/Config/config.local.php</strong>, <strong>storage</strong>, <strong>public/uploads</strong> ve kullanıcı oturum/veri dosyaları. Güncelleme paketi bu alanlara doğrudan yazmamalı.</p>
                    </section>

                    <form class="update-form" method="post" enctype="multipart/form-data" autocomplete="off">
                        <p class="admin-help-text">Güncellemeden önce tam uygulama yedeği alınmalı. Yedek kod dosyalarını, ayarları, yüklenen görselleri ve gerekli kullanıcı verilerini kapsayacak şekilde tasarlanacak.</p>

                        <label class="admin-form-field">
                            <span>Hedef uygulama sürümü</span>
                            <select name="target_version">
                                <option value="1.0.0">1.0.0</option>
                                <option value="1.0.1">1.0.1</option>
                                <option value="1.1.0">1.1.0</option>
                            </select>
                        </label>

                        <p class="admin-help-text">Sürüm listesi ileride lisans merkezi veya yerel sürüm dosyasından alınabilir. Güncelleme başarılı olursa seçilen sürüm sistem durumuna işlenecek.</p>

                        <label class="admin-form-field">
                            <span>Güncelleme paketi</span>
                            <input type="file" name="update_zip" accept=".zip,application/zip">
                        </label>

                        <p class="admin-help-text">Paket, uygulama kök dizinine göre hazırlanmış ZIP olmalı. ZIP önce geçici klasöre açılacak, dosya listesi kontrol edilecek, yedek alınacak ve sonra uygulanacak.</p>

                        <div class="update-checklist" aria-label="Güncelleme kontrol listesi">
                            <div>
                                <span class="status-dot muted"></span>
                                ZIP dosyası kontrol edilecek
                            </div>
                            <div>
                                <span class="status-dot muted"></span>
                                Mevcut uygulama yedeklenecek
                            </div>
                            <div>
                                <span class="status-dot muted"></span>
                                SQL migration dosyaları listelenecek
                            </div>
                            <div>
                                <span class="status-dot muted"></span>
                                Korunan klasörlere dokunulmayacak
                            </div>
                        </div>

                        <div class="update-actions">
                            <button type="submit" name="admin_download_full_backup" value="1">Tam uygulama yedeğini indir</button>
                            <button type="submit" name="admin_install_manual_update" value="1" class="primary-action">Paketi yükle ve uygula</button>
                        </div>
                    </form>
                </article>

                <article class="admin-panel wide update-panel" id="android" data-admin-section="android">
                    <div class="panel-head">
                        <div>
                            <span>ANDROID</span>
                            <h2>Arayan Tanıma uygulaması sürümü</h2>
                        </div>
                    </div>

                    <p class="admin-help-text">Yeni bir APK yayınladığınızda indirme linki her zaman aynı kalır (<code>/apk.php</code>) — kullanıcılara tekrar link göndermeniz gerekmez. Dilerseniz e-posta adresi kayıtlı tüm kullanıcılara bildirim gönderebilirsiniz.</p>

                    <?php if (is_array($androidNotice)): ?>
                        <div class="update-notice <?= ($androidNotice['type'] ?? '') === 'success' ? 'is-success' : 'is-error' ?>" role="status">
                            <strong><?= contacts_admin_h((string)($androidNotice['title'] ?? 'Bilgi')) ?></strong>
                            <span><?= contacts_admin_h((string)($androidNotice['message'] ?? '')) ?></span>
                        </div>
                    <?php endif; ?>

                    <section class="update-status-card">
                        <div class="update-status-row">
                            <strong>Yayındaki sürüm</strong>
                            <span class="status-badge">Android</span>
                        </div>
                        <?php if ($latestAndroidRelease): ?>
                            <p><strong>Sürüm:</strong> v<?= contacts_admin_h((string)$latestAndroidRelease['version_name']) ?> (kod <?= (int)$latestAndroidRelease['version_code'] ?>)</p>
                            <?php if (!empty($latestAndroidRelease['notes'])): ?>
                                <p><strong>Notlar:</strong> <?= nl2br(contacts_admin_h((string)$latestAndroidRelease['notes'])) ?></p>
                            <?php endif; ?>
                            <p><strong>İndirme linki:</strong> <?= contacts_admin_h(app_releases_apk_url($config)) ?></p>
                            <p><strong>Son bildirim:</strong> <?= $latestAndroidRelease['notified_at'] ? contacts_admin_h((string)$latestAndroidRelease['notified_at']) : 'Henüz gönderilmedi' ?></p>
                        <?php else: ?>
                            <p>Henüz bir Android sürümü yayınlanmadı.</p>
                        <?php endif; ?>
                    </section>

                    <?php $apkDisplayVersionValue = (string)(app_settings_get($pdo, 'apk_display_version', '') ?? ''); ?>
                    <?php
                    // Sonraki surum onerisi: kod bir artar, ad sonundaki sayi bir artar (26.12 -> 26.13); APK'nin build.gradle'daki surumuyle ayni olmali.
                    $nextVersionCode = $latestAndroidRelease ? (int)$latestAndroidRelease['version_code'] + 1 : 1;
                    $nextVersionName = '';
                    if ($latestAndroidRelease) {
                        $nextVersionName = preg_replace_callback('/(\d+)(?!.*\d)/', static fn (array $m): string => (string)((int)$m[1] + 1), (string)$latestAndroidRelease['version_name']) ?? '';
                    }
                    ?>
                    <form class="update-form" method="post" enctype="multipart/form-data" autocomplete="off">

                        <label class="admin-form-field">
                            <span>APK'da görünen sürüm yazısı (Ayarlar ekranının altındaki sürüm satırı) · "Sürümü yayınla" ile kaydedilir</span>
                            <input type="text" name="apk_display_version" maxlength="60" value="<?= contacts_admin_h($apkDisplayVersionValue) ?>" placeholder="Örn. MyContacts Caller · Sürüm 2.1">
                            <small class="admin-help-text">Bu metin APK'da sürüm satırının yerine aynen görünür. Boş bırakırsanız APK kendi sürüm numarasını yazar. Güncelleme kontrolü ve sürüm kodu bundan etkilenmez.</small>
                        </label>

                        <label class="admin-form-field">
                            <span>Sürüm kodu · APK'nın içinden otomatik okunur<?= $latestAndroidRelease ? ' (son yayın: ' . (int)$latestAndroidRelease['version_code'] . ', yenisi bundan büyük olmalı)' : '' ?></span>
                            <input type="text" disabled placeholder="APK yüklenince otomatik belirlenir">
                        </label>

                        <label class="admin-form-field">
                            <span>Sürüm notları (isteğe bağlı)</span>
                            <textarea name="notes" rows="3" placeholder="Bu sürümde neler değişti?"></textarea>
                        </label>

                        <label class="admin-form-field">
                            <span>APK dosyası</span>
                            <input type="file" name="android_apk" accept=".apk" required>
                        </label>

                        <label class="admin-form-field admin-form-checkbox">
                            <input type="checkbox" name="notify_users" value="1" checked>
                            <span>E-posta adresi kayıtlı tüm kullanıcılara "yeni sürüm yayınlandı" bildirimi gönder</span>
                        </label>

                        <label class="admin-form-field admin-form-checkbox">
                            <input type="checkbox" name="notify_bell" value="1" checked>
                            <span>Tüm kullanıcıların uygulamadaki bildirim (zil) sayfasına ekle (tıklayınca indirme sayfası açılır)</span>
                        </label>

                        <div class="update-actions">
                            <button type="submit" name="admin_publish_android_release" value="1" class="primary-action">Sürümü yayınla</button>
                        </div>
                    </form>
                </article>

                <article class="admin-panel wide update-panel" id="windows" data-admin-section="windows">
                    <div class="panel-head">
                        <div>
                            <span>PC (WINDOWS)</span>
                            <h2>PC uygulaması sürümü</h2>
                        </div>
                    </div>

                    <p class="admin-help-text">Yeni bir PC sürümü yayınladığınızda indirme linki her zaman aynı kalır (<code>/desktop.php</code>) — kullanıcılara tekrar link göndermeniz gerekmez. Dilerseniz e-posta adresi kayıtlı tüm kullanıcılara bildirim gönderebilirsiniz.</p>

                    <?php if (is_array($windowsNotice)): ?>
                        <div class="update-notice <?= ($windowsNotice['type'] ?? '') === 'success' ? 'is-success' : 'is-error' ?>" role="status">
                            <strong><?= contacts_admin_h((string)($windowsNotice['title'] ?? 'Bilgi')) ?></strong>
                            <span><?= contacts_admin_h((string)($windowsNotice['message'] ?? '')) ?></span>
                        </div>
                    <?php endif; ?>

                    <section class="update-status-card">
                        <div class="update-status-row">
                            <strong>Yayındaki sürüm</strong>
                            <span class="status-badge">Windows</span>
                        </div>
                        <?php if ($latestWindowsRelease): ?>
                            <p><strong>Sürüm:</strong> v<?= contacts_admin_h((string)$latestWindowsRelease['version_name']) ?> (kod <?= (int)$latestWindowsRelease['version_code'] ?>)</p>
                            <?php if (!empty($latestWindowsRelease['notes'])): ?>
                                <p><strong>Notlar:</strong> <?= nl2br(contacts_admin_h((string)$latestWindowsRelease['notes'])) ?></p>
                            <?php endif; ?>
                            <p><strong>İndirme linki:</strong> <?= contacts_admin_h(app_releases_windows_url($config)) ?></p>
                            <p><strong>Son bildirim:</strong> <?= $latestWindowsRelease['notified_at'] ? contacts_admin_h((string)$latestWindowsRelease['notified_at']) : 'Henüz gönderilmedi' ?></p>
                        <?php else: ?>
                            <p>Henüz bir PC sürümü yayınlanmadı.</p>
                        <?php endif; ?>
                    </section>

                    <?php
                    // Sonraki surum onerisi: kod bir artar, ad sonundaki sayi bir artar (26.12 -> 26.13); APK'nin build.gradle'daki surumuyle ayni olmali.
                    $nextWinVersionCode = $latestWindowsRelease ? (int)$latestWindowsRelease['version_code'] + 1 : 1;
                    $nextWinVersionName = '';
                    if ($latestWindowsRelease) {
                        $nextWinVersionName = preg_replace_callback('/(\d+)(?!.*\d)/', static fn (array $m): string => (string)((int)$m[1] + 1), (string)$latestWindowsRelease['version_name']) ?? '';
                    }
                    ?>
                    <form class="update-form" method="post" enctype="multipart/form-data" autocomplete="off">

                        <label class="admin-form-field">
                            <span>Sürüm kodu · son yayından büyük olmalı<?= $latestWindowsRelease ? ' (son: ' . (int)$latestWindowsRelease['version_code'] . ')' : '' ?></span>
                            <input type="number" name="version_code" min="1" step="1" required placeholder="örn. 15" value="<?= $nextWinVersionCode ?>">
                        </label>

                        <label class="admin-form-field">
                            <span>Sürüm notları (isteğe bağlı)</span>
                            <textarea name="notes" rows="3" placeholder="Bu sürümde neler değişti?"></textarea>
                        </label>

                        <label class="admin-form-field">
                            <span>PC uygulaması dosyası (.zip, .exe veya .msi)</span>
                            <input type="file" name="windows_app" accept=".zip,.exe,.msi" required>
                        </label>

                        <label class="admin-form-field admin-form-checkbox">
                            <input type="checkbox" name="notify_users" value="1" checked>
                            <span>E-posta adresi kayıtlı tüm kullanıcılara "yeni sürüm yayınlandı" bildirimi gönder</span>
                        </label>

                        <label class="admin-form-field admin-form-checkbox">
                            <input type="checkbox" name="notify_bell" value="1" checked>
                            <span>Tüm kullanıcıların uygulamadaki bildirim (zil) sayfasına ekle (tıklayınca indirme sayfası açılır)</span>
                        </label>

                        <div class="update-actions">
                            <button type="submit" name="admin_publish_windows_release" value="1" class="primary-action">Sürümü yayınla</button>
                        </div>
                    </form>
                </article>
            </section>
        </main>
    </div>
    <script>
        (() => {
            const titles = {
                dashboard: 'Yönetim Merkezi',
                users: 'Kullanıcı yönetimi',
                userdetail: 'Kullanıcı detayı',
                update: 'Bakım paketi',
                android: 'Android sürümü',
                windows: 'PC (Windows) sürümü',
                verification: 'Telefon doğrulama',
                plans: 'Planlar',
                payments: 'Ödemeler ve abonelikler',
                paymentsettings: 'Ödeme ayarları',
                password: 'Şifre değiştir',
                settings: 'Ayar ve bakım',
            };
            // Acilir pencereler: [data-X-modal] pencere, [data-X-add] acan, [data-X-modal-close] kapatan dugme.
            const modalNames = ['plan', 'grant'];
            const setModal = (modal, open) => {
                modal.hidden = !open;
                if (open) {
                    modal.querySelector('input:not([type="hidden"])')?.focus();
                }
            };
            modalNames.forEach((name) => {
                const modal = document.querySelector('[data-' + name + '-modal]');
                if (!modal) {
                    return;
                }
                document.querySelector('[data-' + name + '-add]')?.addEventListener('click', () => setModal(modal, true));
                modal.querySelector('[data-' + name + '-modal-close]')?.addEventListener('click', () => setModal(modal, false));
                modal.addEventListener('click', (event) => {
                    if (event.target === modal) {
                        setModal(modal, false);
                    }
                });
                document.addEventListener('keydown', (event) => {
                    if (event.key === 'Escape') {
                        setModal(modal, false);
                    }
                });
            });
            // Onay penceresi: [data-confirm] olan dugmeye basinca sayfa ici pencere acilir; "Evet" formu o dugmeyle gonderir.
            // (Tarayicinin yerlesik confirm() penceresi bazi ortamlarda gorunmedigi icin kullanilmiyor.)
            const confirmModal = document.querySelector('[data-confirm-modal]');
            let confirmButton = null;
            const closeConfirm = () => {
                if (confirmModal) {
                    confirmModal.hidden = true;
                }
                confirmButton = null;
            };
            document.addEventListener('click', (event) => {
                const button = event.target.closest('[data-confirm]');
                if (!button || !confirmModal) {
                    return;
                }
                event.preventDefault();
                confirmButton = button;
                confirmModal.querySelector('[data-confirm-title]').textContent = button.dataset.confirmTitle || 'Onay';
                confirmModal.querySelector('[data-confirm-message]').textContent = button.dataset.confirm;
                confirmModal.hidden = false;
                confirmModal.querySelector('[data-confirm-cancel]').focus();
            });
            confirmModal?.querySelector('[data-confirm-cancel]')?.addEventListener('click', closeConfirm);
            confirmModal?.addEventListener('click', (event) => {
                if (event.target === confirmModal) {
                    closeConfirm();
                }
            });
            confirmModal?.querySelector('[data-confirm-ok]')?.addEventListener('click', () => {
                const button = confirmButton;
                closeConfirm();
                if (button?.form) {
                    button.form.requestSubmit(button);
                }
            });
            document.addEventListener('keydown', (event) => {
                if (event.key === 'Escape') {
                    closeConfirm();
                }
            });
            // Bildirim kutulari sabit kalmaz: basari 4 sn, hata 12 sn sonra solarak kaybolur; tiklayinca hemen kapanir.
            document.querySelectorAll('.update-notice').forEach((notice) => {
                const hide = () => {
                    notice.classList.add('is-leaving');
                    setTimeout(() => notice.remove(), 450);
                };
                notice.addEventListener('click', hide);
                setTimeout(hide, notice.classList.contains('is-error') ? 12000 : 4000);
            });
            const sections = Array.from(document.querySelectorAll('[data-admin-section]'));
            const navLinks = Array.from(document.querySelectorAll('.admin-nav a[href^="#"]'));
            const pageTitle = document.querySelector('.admin-topbar h1');

            const showSection = () => {
                const hasUserParam = new URLSearchParams(window.location.search).has('user');
                const requested = (window.location.hash || (hasUserParam ? '#userdetail' : '#dashboard')).slice(1);
                const active = sections.some((section) => section.dataset.adminSection === requested) ? requested : 'dashboard';

                sections.forEach((section) => {
                    const isActive = section.dataset.adminSection === active;
                    section.classList.toggle('admin-section-hidden', !isActive);
                    section.toggleAttribute('hidden', !isActive);
                });

                navLinks.forEach((link) => {
                    link.classList.toggle('is-active', link.getAttribute('href') === `#${active}` || (active === 'userdetail' && link.getAttribute('href') === '#users'));
                });

                if (pageTitle) {
                    pageTitle.textContent = titles[active] || 'Yönetim Merkezi';
                }
            };

            window.addEventListener('hashchange', showSection);
            showSection();

            // Kullanici detayi: rastgele sifre uret (okunmasi kolay karakterler).
            const generateButton = document.getElementById('admin-user-generate-password');
            if (generateButton) {
                generateButton.addEventListener('click', () => {
                    const alphabet = 'ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789';
                    const bytes = new Uint32Array(12);
                    window.crypto.getRandomValues(bytes);
                    document.getElementById('admin-user-new-password').value = Array.from(bytes, (value) => alphabet[value % alphabet.length]).join('');
                });
            }
        })();
    </script>
<script>
        // Ozellik tiki kapaliyken sayi kutusu 0 gorunur; tik acilinca 0 ise bos (sinirsiz) olur, onceki deger varsa geri gelir.
        (function () {
            document.querySelectorAll('.admin-form-field').forEach(function (field) {
                var tick = field.querySelector('input[type="checkbox"][name^="feature_"]');
                var input = field.querySelector('input[type="number"][name^="limit_"], input[type="number"][name="team_limit"]');
                if (!tick || !input || tick.name === 'feature_backup') { return; }
                var remembered = tick.checked ? input.value : '';
                if (!tick.checked) { input.value = '0'; }
                input.addEventListener('input', function () { if (tick.checked) { remembered = input.value; } });
                tick.addEventListener('change', function () {
                    if (tick.checked) { input.value = remembered === '0' ? '' : remembered; }
                    else { remembered = input.value; input.value = '0'; }
                });
            });
        })();
    </script>
<script>
        // Yedek aralığı tiki kapaliyken yedek rakam kutulari soluk ve salt okunur olur (deger yine de kaydedilir).
        (function () {
            function sync(form) {
                var tick = form.querySelector('input[name="feature_backup"]');
                if (!tick) { return; }
                var mirror = form.querySelector('[data-backup-mirror]');
                if (mirror) { mirror.checked = tick.checked; }
                form.querySelectorAll('[data-backup-field]').forEach(function (input) {
                    input.readOnly = !tick.checked;
                    input.tabIndex = tick.checked ? 0 : -1;
                    input.classList.toggle('is-off', !tick.checked);
                    var field = input.closest('.admin-form-field');
                    if (!field.querySelector('input[name="feature_backup"]')) { field.classList.toggle('is-off', !tick.checked); }
                });
            }
            // Ucret bos veya 0 ise plan "Pasif", doluysa "Aktif" gorunur (kayitta da ayni kural uygulanir).
            function syncStatus(form) {
                var price = form.querySelector('input[name="price_monthly"]');
                var yearly = form.querySelector('input[name="price_yearly"]');
                var badge = form.querySelector('[data-plan-status]');
                if (!price || !badge || price.disabled) { return; }
                var value = parseFloat(String(price.value).replace(',', '.'));
                var yearlyValue = yearly ? parseFloat(String(yearly.value).replace(',', '.')) : 0;
                badge.textContent = (value > 0 || yearlyValue > 0) ? 'Aktif' : 'Pasif';
            }
            // Fiyat alanindan cikinca 4990 -> 4990,00 (Turk bicimi, binlik ayraci yok).
            function formatPrice(input) {
                var text = String(input.value).replace(/\s/g, '');
                if (text === '') { return; }
                if (text.indexOf(',') !== -1) { text = text.replace(/\./g, '').replace(',', '.'); }
                else if (/\.\d{3}(\.|$)/.test(text) && !/\.\d{1,2}$/.test(text)) { text = text.replace(/\./g, ''); }
                var number = parseFloat(text);
                if (isNaN(number) || number < 0) { return; }
                input.value = number.toFixed(2).replace('.', ',');
            }
            // "Tümünü kaydet": plan formlari sirayla kaydedilir; ilk hatada durulur, bitince sayfa yenilenir.
            var saveAll = document.querySelector('[data-plans-save-all]');
            if (saveAll) {
                saveAll.addEventListener('click', async function () {
                    var forms = Array.from(document.querySelectorAll('.admin-plan-form')).filter(function (form) { return !form.classList.contains('admin-plan-modal-form'); });
                    var errorBox = document.querySelector('[data-plans-error]');
                    if (errorBox) { errorBox.hidden = true; }
                    for (var i = 0; i < forms.length; i += 1) {
                        if (!forms[i].reportValidity()) { return; }
                    }
                    saveAll.disabled = true;
                    saveAll.textContent = 'Kaydediliyor…';
                    try {
                        for (var j = 0; j < forms.length; j += 1) {
                            var data = new FormData(forms[j]);
                            data.set('admin_save_plan', '1');
                            var response = await fetch(window.location.pathname, {
                                method: 'POST',
                                body: data,
                                credentials: 'same-origin',
                                headers: { 'X-Admin-Batch': j === forms.length - 1 ? 'last' : '1' },
                            });
                            var result = await response.json();
                            if (!result.ok) {
                                var name = (forms[j].querySelector('[name="name"]') || {}).value || 'Plan';
                                throw new Error(name + ': ' + (result.message || 'Kaydedilemedi.'));
                            }
                        }
                        window.location.hash = '#plans';
                        window.location.reload();
                    } catch (error) {
                        if (errorBox) {
                            errorBox.textContent = 'Planlar kaydedilemedi. ' + error.message;
                            errorBox.hidden = false;
                        }
                        saveAll.disabled = false;
                        saveAll.textContent = 'Tümünü kaydet';
                    }
                });
            }
            document.querySelectorAll('.admin-plan-form').forEach(function (form) {
                sync(form);
                syncStatus(form);
                form.addEventListener('focusout', function (event) {
                    if (event.target && (event.target.name === 'price_monthly' || event.target.name === 'price_yearly')) { formatPrice(event.target); syncStatus(form); }
                });
                form.addEventListener('input', function (event) {
                    if (event.target && (event.target.name === 'price_monthly' || event.target.name === 'price_yearly')) { syncStatus(form); }
                });
                form.addEventListener('change', function (event) {
                    if (event.target && event.target.name === 'feature_backup') { sync(form); }
                });
            });
        })();
    </script>
</body>
</html>

/* Panel ici sekmeler (Surumler: Android / PC) */
.admin-tabs {
    display: flex;
    gap: 6px;
    margin: 0 0 14px;
    padding: 4px;
    border: 1px solid var(--line, #d9e2df);
    border-radius: 10px;
    background: #f3f7f6;
    width: fit-content;
    max-width: 100%;
}

.admin-tabs a {
    padding: 7px 16px;
    border-radius: 8px;
    color: #4f605d;
    font-size: 13px;
    font-weight: 700;
    text-decoration: none;
    white-space: nowrap;
}

.admin-tabs a.is-active {
    background: #fff;
    color: #0f6560;
    box-shadow: 0 1px 3px rgba(15, 40, 36, 0.14);
}

/* Plan ozellikleri: kisa baslik + altinda kucuk aciklama */
.admin-plan-team-check .admin-plan-hint {
    display: block;
    margin-top: 2px;
    color: var(--muted, #5f716e);
    font-size: 11px;
    font-weight: 400;
    line-height: 1.3;
}

/* Bayiler: komisyon turu / deger / yillik en az uye yan yana */
.admin-plan-checks.dealer-commission-row { flex-direction: row; flex-wrap: wrap; align-items: flex-end; gap: 12px; }
.admin-plan-checks.dealer-commission-row > label { display: grid; gap: 4px; flex: 1 1 140px; min-width: 0; }
.admin-plan-checks.dealer-commission-row input, .admin-plan-checks.dealer-commission-row select { width: 100%; box-sizing: border-box; }
