<?php
declare(strict_types=1);

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

function admin_debug_render_error(string $title, string $message, string $file = '', int $line = 0): void
{
    if (!headers_sent()) {
        http_response_code(500);
        header('Content-Type: text/html; charset=utf-8');
    }

    echo '<div style="margin:20px;padding:16px;border:2px solid #b42318;background:#fff5f5;color:#111;font:14px/1.5 monospace">';
    echo '<h1 style="margin:0 0 12px;color:#b42318;font-size:20px">' . htmlspecialchars($title, ENT_QUOTES, 'UTF-8') . '</h1>';
    echo '<div><strong>Message:</strong> ' . htmlspecialchars($message, ENT_QUOTES, 'UTF-8') . '</div>';
    if ($file !== '') {
        echo '<div><strong>File:</strong> ' . htmlspecialchars($file, ENT_QUOTES, 'UTF-8') . '</div>';
    }
    if ($line > 0) {
        echo '<div><strong>Line:</strong> ' . $line . '</div>';
    }
    echo '</div>';
}

set_error_handler(static function (int $severity, string $message, string $file, int $line): bool {
    if (!(error_reporting() & $severity)) {
        return false;
    }

    admin_debug_render_error('PHP Error', $message, $file, $line);
    return true;
});

set_exception_handler(static function (Throwable $e): void {
    admin_debug_render_error('Uncaught Exception', $e->getMessage(), $e->getFile(), $e->getLine());
    exit;
});

register_shutdown_function(static function (): void {
    $error = error_get_last();
    if (!is_array($error)) {
        return;
    }

    $fatalTypes = [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR];
    if (!in_array((int)($error['type'] ?? 0), $fatalTypes, true)) {
        return;
    }

    admin_debug_render_error(
        'Fatal Error',
        (string)($error['message'] ?? 'Unknown fatal error'),
        (string)($error['file'] ?? ''),
        (int)($error['line'] ?? 0)
    );
});

require_once __DIR__ . '/common/admin_auth.php';
require_once __DIR__ . '/common/auth_middleware.php';
require_once __DIR__ . '/common/ops_service.php';
require_once __DIR__ . '/common/customer_provision.php';
require_once __DIR__ . '/common/demo_request_service.php';
require_once __DIR__ . '/common/customer_cleanup.php';

function af(string $type, string $message): void
{
    golder_admin_session_start();
    $_SESSION['golder_admin_flash'] = ['type' => $type, 'message' => $message];
}

function take_flash(): ?array
{
    golder_admin_session_start();
    $flash = $_SESSION['golder_admin_flash'] ?? null;
    unset($_SESSION['golder_admin_flash']);
    return is_array($flash) ? $flash : null;
}

function h($value): string
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function go(string $tab, array $query = []): void
{
    header('Location: admin.php?' . http_build_query(array_merge(['tab' => $tab], $query)));
    exit;
}

function admin_money($value): string
{
    return number_format((float)$value, 2, '.', ',');
}

function admin_safe_username(string $input): bool
{
    return preg_match('/^[a-z0-9_]+$/', $input) === 1;
}

function admin_datetime_value(?string $value): string
{
    return golder_normalize_datetime_string((string)$value);
}

function admin_plan_options(): array
{
    $options = [];
    foreach (golder_plan_codes() as $planType) {
        $options[$planType] = golder_plan_label($planType);
    }
    return $options;
}

function admin_plan_ui_rules(): array
{
    $rules = [];
    foreach (golder_plan_definitions() as $planType => $definition) {
        $rules[$planType] = [
            'pc_fixed' => ((string)($definition['pc_limit_mode'] ?? '') === 'fixed_1'),
            'web_fixed' => ((string)($definition['web_limit_mode'] ?? '') === 'fixed_0'),
            'web_positive' => golder_plan_supports_web_mobile($planType),
            'desktop_enabled' => ((string)($definition['desktop_expiry_mode'] ?? '') === 'dated'),
            'desktop_required' => golder_plan_requires_desktop_expiry($planType),
            'sync_enabled' => ((string)($definition['sync_expiry_mode'] ?? '') === 'dated'),
            'sync_required' => golder_plan_requires_sync_expiry($planType),
            'web_mobile_enabled' => golder_plan_supports_web_mobile($planType),
            'profile_sync_enabled' => golder_plan_supports_profile_sync($planType),
        ];
    }
    return $rules;
}

function admin_database_name(PDO $master): string
{
    static $cache = [];
    $key = spl_object_id($master);
    if (isset($cache[$key])) {
        return $cache[$key];
    }

    $dbName = (string)($master->query('SELECT DATABASE()')->fetchColumn() ?: '');
    $cache[$key] = $dbName;
    return $dbName;
}

function admin_table_exists(PDO $master, string $tableName): bool
{
    $dbName = admin_database_name($master);
    if ($dbName === '') {
        return false;
    }

    $st = $master->prepare(
        'SELECT COUNT(*)
         FROM information_schema.TABLES
         WHERE TABLE_SCHEMA = :db
           AND TABLE_NAME = :table_name'
    );
    $st->execute([
        ':db' => $dbName,
        ':table_name' => $tableName,
    ]);
    return ((int)$st->fetchColumn()) > 0;
}

function admin_safe_scalar_query(PDO $master, string $sql, $default = 0)
{
    try {
        $value = $master->query($sql)->fetchColumn();
        return ($value === false || $value === null) ? $default : $value;
    } catch (Throwable $_ignored) {
        return $default;
    }
}

function admin_ensure_schema(PDO $master): void
{
    golder_ensure_customers_columns($master);
    golder_ensure_plan_tables($master);
    golder_ensure_demo_license_tables($master);
    golder_ensure_customer_devices_schema($master);
    golder_ensure_api_security_tables($master);
    golder_ensure_backup_tables($master);
    golder_ensure_job_runs_table($master);
}

function admin_build_demo_username(string $email, string $phone, string $fullName): string
{
    $base = trim($email);
    if ($base !== '' && strpos($base, '@') !== false) {
        $base = strstr($base, '@', true) ?: $base;
    }
    if ($base === '') {
        $base = preg_replace('/[^a-zA-Z0-9_]/', '', strtolower(trim($fullName)));
    }
    if ($base === '') {
        $base = 'demo_' . substr(hash('sha256', $phone . microtime(true)), 0, 6);
    }
    $base = preg_replace('/[^a-zA-Z0-9_]/', '', $base) ?: 'demo_user';
    return 'demo_' . strtolower($base);
}

function admin_upsert_yearly_pricing(PDO $master, string $planType, float $base, float $perPc, float $perWeb, string $currency): void
{
    $planType = golder_normalize_plan_type($planType);
    if (!in_array($planType, golder_plan_codes(), true)) {
        throw new RuntimeException('plan_type is invalid.');
    }

    $base = max(0, $base);
    $perPc = max(0, $perPc);
    $perWeb = max(0, $perWeb);
    if (!golder_plan_supports_web_mobile($planType)) {
        $perWeb = 0;
    }

    $currency = strtoupper(trim($currency));
    if ($currency === '') {
        $currency = 'TRY';
    }

    $master->prepare(
        'INSERT INTO pricing_rules (plan_type, duration_key, duration_days, base_price, per_pc_price, per_web_price, currency, is_active)
         VALUES (:pt, :dk, :dd, :bp, :pp, :pw, :cu, 1)
         ON DUPLICATE KEY UPDATE
             duration_days = VALUES(duration_days),
             base_price = VALUES(base_price),
             per_pc_price = VALUES(per_pc_price),
             per_web_price = VALUES(per_web_price),
             currency = VALUES(currency),
             is_active = 1'
    )->execute([
        ':pt' => $planType,
        ':dk' => 'yearly',
        ':dd' => 365,
        ':bp' => number_format($base, 2, '.', ''),
        ':pp' => number_format($perPc, 2, '.', ''),
        ':pw' => number_format($perWeb, 2, '.', ''),
        ':cu' => $currency,
    ]);
}

function approve_payment(PDO $master, string $requestId, string $message, string $adminUser): void
{
    $result = golder_approve_payment_request($master, $requestId, $message, $adminUser);
    if (empty($result['ok'])) {
        throw new RuntimeException((string)($result['message'] ?? 'Payment request approval failed.'));
    }
}

function create_manual_demo(PDO $master, string $fullName, string $email, string $phone, string $password): array
{
    $fullName = trim($fullName);
    $email = trim($email);
    $phone = trim($phone);
    $password = trim($password);

    if ($fullName === '' || ($email === '' && $phone === '')) {
        throw new RuntimeException('full_name and one contact field are required.');
    }
    if ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
        throw new RuntimeException('email is invalid.');
    }
    if ($phone !== '' && preg_match('/^[0-9+()\\-\\s]{7,20}$/', $phone) !== 1) {
        throw new RuntimeException('phone is invalid.');
    }
    if ($password === '') {
        $password = golder_generate_password(10);
    }
    if (strlen($password) < 6) {
        throw new RuntimeException('demo password is too short.');
    }

    $username = admin_build_demo_username($email, $phone, $fullName);
    $provision = golder_provision_customer_with_tenant(
        $master,
        $username,
        $password,
        $email,
        $phone,
        'A-COMPLEX',
        1,
        1,
        golder_demo_duration_key(),
        true
    );
    if (empty($provision['ok'])) {
        throw new RuntimeException((string)($provision['message'] ?? 'Demo provisioning failed.'));
    }

    $customerId = (int)($provision['customer_id'] ?? 0);
    $demoCode = golder_generate_demo_code($master);
    $expiresAt = golder_demo_expiry_from_now();
    $master->prepare(
        'INSERT INTO demo_licenses (customer_id, demo_code, starts_at, expires_at, status)
         VALUES (:cid, :dc, UTC_TIMESTAMP(), :ex, :st)'
    )->execute([
        ':cid' => $customerId,
        ':dc' => $demoCode,
        ':ex' => $expiresAt,
        ':st' => 'active',
    ]);

    return [
        'customer_id' => $customerId,
        'demo_code' => $demoCode,
        'expires_at' => $expiresAt,
        'username' => (string)($provision['username'] ?? $username),
        'password' => $password,
    ];
}

golder_admin_session_start();
$flash = take_flash();
$tab = trim((string)($_GET['tab'] ?? 'customers'));
$validTabs = ['customers', 'devices', 'pricing', 'demo', 'jobs'];
if (!in_array($tab, $validTabs, true)) {
    $tab = 'customers';
}

$configured = !empty(golder_admin_expected_credentials()['configured']);
$adminUser = golder_admin_current_user();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = trim((string)($_POST['action'] ?? ''));

    if ($action === 'login') {
        if (!$configured) {
            $flash = ['type' => 'error', 'message' => 'GOLDER_ADMIN_USER / GOLDER_ADMIN_PASS tanimli degil.'];
        } elseif (golder_admin_login(trim((string)($_POST['username'] ?? '')), (string)($_POST['password'] ?? ''))) {
            af('success', 'Admin oturumu acildi.');
            go($tab);
        } else {
            $flash = ['type' => 'error', 'message' => 'Gecersiz admin girisi.'];
        }
    } elseif ($action === 'logout' && golder_admin_is_logged_in()) {
        if (!golder_admin_verify_csrf((string)($_POST['csrf_token'] ?? ''))) {
            $flash = ['type' => 'error', 'message' => 'CSRF hatasi.'];
        } else {
            golder_admin_logout();
            af('success', 'Oturum kapatildi.');
            go('customers');
        }
    } elseif (golder_admin_is_logged_in()) {
        if (!golder_admin_verify_csrf((string)($_POST['csrf_token'] ?? ''))) {
            $flash = ['type' => 'error', 'message' => 'CSRF hatasi.'];
        } else {
            $master = golder_master_pdo();
            admin_ensure_schema($master);

            try {
                switch ($action) {
                    case 'create_customer':
                        $username = strtolower(trim((string)($_POST['username'] ?? '')));
                        $password = trim((string)($_POST['password'] ?? ''));
                        $email = trim((string)($_POST['email'] ?? ''));
                        $phone = trim((string)($_POST['phone'] ?? ''));
                        $planType = trim((string)($_POST['plan_type'] ?? golder_default_plan_type()));
                        $maxPc = (int)($_POST['max_pc_devices'] ?? 1);
                        $maxWeb = (int)($_POST['max_web_sessions'] ?? 0);
                        $isAiEnabled = !empty($_POST['is_ai_enabled']) ? 1 : 0;
                        $desktopExpiryDate = trim((string)($_POST['desktop_expiry_date'] ?? ''));
                        $syncExpiryDate = trim((string)($_POST['sync_expiry_date'] ?? ''));

                        if ($username === '' || !admin_safe_username($username)) {
                            throw new RuntimeException('username zorunlu ve sadece kucuk harf/rakam/_ olabilir.');
                        }
                        if ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
                            throw new RuntimeException('email gecersiz.');
                        }
                        if ($phone !== '' && preg_match('/^[0-9+()\\-\\s]{7,20}$/', $phone) !== 1) {
                            throw new RuntimeException('telefon gecersiz.');
                        }
                        if ($password === '') {
                            $password = golder_generate_password(12);
                        }
                        $normalized = golder_normalize_plan_limits($planType, $maxPc, $maxWeb);
                        $validatedDates = golder_validate_plan_expiry_dates(
                            $normalized['plan_type'],
                            $desktopExpiryDate,
                            $syncExpiryDate
                        );
                        if (!empty($validatedDates['errors'])) {
                            throw new RuntimeException((string)reset($validatedDates['errors']));
                        }

                        $provision = golder_provision_customer_with_tenant(
                            $master,
                            $username,
                            $password,
                            $email,
                            $phone,
                            $normalized['plan_type'],
                            (int)$normalized['max_pc_devices'],
                            (int)$normalized['max_web_sessions'],
                            'yearly',
                            false,
                            0,
                            null,
                            $isAiEnabled,
                            (string)($validatedDates['desktop_expiry_date'] ?? ''),
                            (string)($validatedDates['sync_expiry_date'] ?? '')
                        );
                        if (empty($provision['ok'])) {
                            throw new RuntimeException((string)($provision['message'] ?? 'Musteri olusturulamadi.'));
                        }
                        af(
                            'success',
                            'Musteri olusturuldu. Kullanici: ' . (string)($provision['username'] ?? $username) . ' | Sifre: ' . $password
                        );
                        go('customers', ['customer_id' => (int)($provision['customer_id'] ?? 0)]);

                    case 'update_customer_details':
                        $customerId = (int)($_POST['customer_id'] ?? 0);
                        $customer = golder_customer_by_id($master, $customerId);
                        if (!$customer) {
                            throw new RuntimeException('Musteri bulunamadi.');
                        }

                        $username = strtolower(trim((string)($_POST['username'] ?? '')));
                        $email = trim((string)($_POST['email'] ?? ''));
                        $phone = trim((string)($_POST['phone_number'] ?? ''));
                        $planType = trim((string)($_POST['plan_type'] ?? golder_fallback_plan_type()));
                        $maxPc = (int)($_POST['max_pc_devices'] ?? 1);
                        $maxWeb = (int)($_POST['max_web_sessions'] ?? 0);
                        $isAiEnabled = !empty($_POST['is_ai_enabled']) ? 1 : 0;
                        $licenseStatus = trim((string)($_POST['license_status'] ?? 'active'));
                        $desktopExpiryDate = trim((string)($_POST['desktop_expiry_date'] ?? ''));
                        $syncExpiryDate = trim((string)($_POST['sync_expiry_date'] ?? ''));
                        $mysqlDbName = trim((string)($_POST['mysql_db_name'] ?? ''));
                        $mysqlDbUser = trim((string)($_POST['mysql_db_user'] ?? ''));
                        $mysqlDbPass = trim((string)($_POST['mysql_db_pass'] ?? ''));

                        if ($username === '' || !admin_safe_username($username)) {
                            throw new RuntimeException('username gecersiz.');
                        }
                        if ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
                            throw new RuntimeException('email gecersiz.');
                        }
                        if ($phone !== '' && preg_match('/^[0-9+()\\-\\s]{7,20}$/', $phone) !== 1) {
                            throw new RuntimeException('telefon gecersiz.');
                        }
                        if (!in_array($licenseStatus, ['active', 'expired', 'suspended', 'pending', 'cancelled'], true)) {
                            $licenseStatus = 'active';
                        }

                        $normalized = golder_normalize_plan_limits($planType, $maxPc, $maxWeb);
                        $validatedDates = golder_validate_plan_expiry_dates(
                            $normalized['plan_type'],
                            $desktopExpiryDate,
                            $syncExpiryDate
                        );
                        if (!empty($validatedDates['errors'])) {
                            throw new RuntimeException((string)reset($validatedDates['errors']));
                        }
                        $master->prepare(
                            'UPDATE customers
                             SET username = :u,
                                 email = :e,
                                 phone_number = :p,
                                 plan_type = :pt,
                                 max_pc_devices = :pc,
                                 max_web_sessions = :ws,
                                 max_devices = :md,
                                 is_ai_enabled = :ai,
                                 license_status = :ls,
                                 desktop_expiry_date = :dex,
                                 sync_expiry_date = :sex,
                                 expiry_date = :ex,
                                 mysql_db_name = :dbn,
                                 mysql_db_user = :dbu,
                                 mysql_db_pass = :dbp
                             WHERE id = :id'
                        )->execute([
                            ':u' => $username,
                            ':e' => ($email !== '' ? $email : null),
                            ':p' => ($phone !== '' ? $phone : null),
                            ':pt' => $normalized['plan_type'],
                            ':pc' => $normalized['max_pc_devices'],
                            ':ws' => $normalized['max_web_sessions'],
                            ':md' => $normalized['max_pc_devices'],
                            ':ai' => $isAiEnabled,
                            ':ls' => $licenseStatus,
                            ':dex' => (($validatedDates['desktop_expiry_date'] ?? '') !== '' ? $validatedDates['desktop_expiry_date'] : null),
                            ':sex' => (($validatedDates['sync_expiry_date'] ?? '') !== '' ? $validatedDates['sync_expiry_date'] : null),
                            ':ex' => (($validatedDates['expiry_date'] ?? '') !== '' ? $validatedDates['expiry_date'] : null),
                            ':dbn' => ($mysqlDbName !== '' ? $mysqlDbName : null),
                            ':dbu' => ($mysqlDbUser !== '' ? $mysqlDbUser : null),
                            ':dbp' => ($mysqlDbPass !== '' ? $mysqlDbPass : null),
                            ':id' => $customerId,
                        ]);
                        golder_enforce_customer_plan($master, $customerId);
                        af('success', 'Musteri detaylari guncellendi.');
                        go('customers', ['customer_id' => $customerId]);

                    case 'set_customer_password':
                        $customerId = (int)($_POST['customer_id'] ?? 0);
                        $newPassword = trim((string)($_POST['new_password'] ?? ''));
                        if (!golder_customer_by_id($master, $customerId)) {
                            throw new RuntimeException('Musteri bulunamadi.');
                        }
                        if ($newPassword === '') {
                            $newPassword = golder_generate_password(12);
                        }
                        if (strlen($newPassword) < 8) {
                            throw new RuntimeException('Sifre en az 8 karakter olmalidir.');
                        }
                        $hash = password_hash($newPassword, PASSWORD_DEFAULT);
                        if (!is_string($hash) || $hash === '') {
                            throw new RuntimeException('Sifre hashlenemedi.');
                        }
                        $master->prepare('UPDATE customers SET password_hash = :h WHERE id = :id')->execute([
                            ':h' => $hash,
                            ':id' => $customerId,
                        ]);
                        af('success', 'Musteri sifresi guncellendi. Yeni sifre: ' . $newPassword);
                        go('customers', ['customer_id' => $customerId]);

                    case 'hard_delete_customer':
                        $customerId = (int)($_POST['customer_id'] ?? 0);
                        $customer = golder_customer_by_id($master, $customerId);
                        if (!$customer) {
                            throw new RuntimeException('Musteri bulunamadi.');
                        }
                        $confirmText = trim((string)($_POST['confirm_text'] ?? ''));
                        $expected = 'DELETE ' . (string)($customer['username'] ?? '');
                        if (!hash_equals($expected, $confirmText)) {
                            throw new RuntimeException('Yazili onay hatali. Beklenen metin: ' . $expected);
                        }
                        $res = golder_hard_delete_customer($master, $customerId);
                        if (empty($res['ok'])) {
                            throw new RuntimeException((string)($res['message'] ?? 'Tam silme basarisiz.'));
                        }
                        $counts = (array)($res['counts'] ?? []);
                        $message = 'Musteri tamamen silindi (#' . $customerId . '). Backup dosya: '
                            . (int)($counts['backup_files_deleted'] ?? 0)
                            . ', payment: ' . (int)($counts['payment_requests'] ?? 0)
                            . ', demo: ' . (int)($counts['demo_licenses'] ?? 0);
                        $warnings = (array)($res['warnings'] ?? []);
                        if ($warnings) {
                            $message .= ' | Uyarilar: ' . implode(' | ', $warnings);
                        }
                        af('success', $message);
                        go('customers');

                    case 'rename_device':
                        $cid = (int)($_POST['customer_id'] ?? 0);
                        if (!golder_rename_device($master, $cid, (int)($_POST['device_id'] ?? 0), trim((string)($_POST['device_name'] ?? '')))) {
                            throw new RuntimeException('Cihaz guncellenemedi.');
                        }
                        af('success', 'Cihaz adi guncellendi.');
                        go('devices', ['customer_id' => $cid]);

                    case 'remove_device':
                        $cid = (int)($_POST['customer_id'] ?? 0);
                        if (!golder_remove_device($master, $cid, (int)($_POST['device_id'] ?? 0))) {
                            throw new RuntimeException('Cihaz kaldirilamadi.');
                        }
                        af('success', 'Cihaz kaldirildi.');
                        go('devices', ['customer_id' => $cid]);

                    case 'logout_device_sessions':
                        $cid = (int)($_POST['customer_id'] ?? 0);
                        $deviceId = (int)($_POST['device_id'] ?? 0);
                        $stDevice = $master->prepare(
                            'SELECT device_type, device_uid
                             FROM customer_devices
                             WHERE id = :id AND customer_id = :cid
                             LIMIT 1'
                        );
                        $stDevice->execute([':id' => $deviceId, ':cid' => $cid]);
                        $deviceRow = $stDevice->fetch() ?: [];
                        $closed = golder_close_web_sessions_by_device($master, $cid, $deviceId, 'admin_logout');
                        $revoked = 0;
                        if (strtolower(trim((string)($deviceRow['device_type'] ?? ''))) === 'pc') {
                            $revoked = golder_revoke_desktop_tokens_by_device_uid(
                                $master,
                                $cid,
                                (string)($deviceRow['device_uid'] ?? '')
                            );
                        }
                        af('success', $closed . ' web oturumu ve ' . $revoked . ' desktop token kapatildi.');
                        go('devices', ['customer_id' => $cid]);

                    case 'logout_web_session':
                        $cid = (int)($_POST['customer_id'] ?? 0);
                        golder_close_web_session($master, trim((string)($_POST['session_uuid'] ?? '')), 'admin_logout');
                        af('success', 'Web oturumu kapatildi.');
                        go('devices', ['customer_id' => $cid]);

                    case 'reset_hardware_lock':
                        $cid = (int)($_POST['customer_id'] ?? 0);
                        $result = golder_reset_customer_desktop_hardware_locks($master, $cid);
                        af(
                            'success',
                            'PC cihaz kilitleri sifirlandi. Silinen cihaz: '
                            . (int)($result['devices_deleted'] ?? 0)
                            . ' | Revoke edilen token: '
                            . (int)($result['tokens_revoked'] ?? 0)
                        );
                        go('customers', ['customer_id' => $cid]);

                    case 'approve_payment':
                        $requestId = trim((string)($_POST['payment_request_id'] ?? ''));
                        approve_payment($master, $requestId, trim((string)($_POST['admin_message'] ?? 'Approved')), $adminUser);
                        $usernameText = (string)($master->query("SELECT COALESCE(application_username, '-') FROM payment_requests WHERE id = " . $master->quote($requestId) . " LIMIT 1")->fetchColumn() ?: '-');
                        af('success', 'Odeme talebi onaylandi. Uygulama girisi: ' . $usernameText . ' | Sifre: portal sifresi ile ayni.');
                        go('payments', ['payment_id' => $requestId]);

                    case 'reject_payment':
                        $requestId = trim((string)($_POST['payment_request_id'] ?? ''));
                        $message = trim((string)($_POST['admin_message'] ?? 'Rejected'));
                        $st = $master->prepare(
                            'UPDATE payment_requests
                             SET status = :st,
                                 admin_message = :msg,
                                 rejected_at = UTC_TIMESTAMP(),
                                 reviewed_by = :rb,
                                 updated_at = UTC_TIMESTAMP()
                             WHERE id = :id AND status = :pending'
                        );
                        $st->execute([
                            ':st' => 'rejected',
                            ':msg' => $message,
                            ':rb' => $adminUser,
                            ':id' => $requestId,
                            ':pending' => 'pending',
                        ]);
                        if ($st->rowCount() <= 0) {
                            throw new RuntimeException('Talep bulunamadi veya beklemede degil.');
                        }
                        $master->prepare(
                            'INSERT INTO payment_request_messages (payment_request_id, sender_type, sender_name, message_text)
                             VALUES (:id, :st, :sn, :msg)'
                        )->execute([
                            ':id' => $requestId,
                            ':st' => 'admin',
                            ':sn' => $adminUser,
                            ':msg' => $message,
                        ]);
                        af('success', 'Odeme reddedildi.');
                        go('payments', ['payment_id' => $requestId]);

                    case 'message_payment':
                        $requestId = trim((string)($_POST['payment_request_id'] ?? ''));
                        $message = trim((string)($_POST['message'] ?? ''));
                        if ($requestId === '' || $message === '') {
                            throw new RuntimeException('Mesaj bos olamaz.');
                        }
                        $master->prepare(
                            'INSERT INTO payment_request_messages (payment_request_id, sender_type, sender_name, message_text)
                             VALUES (:id, :st, :sn, :msg)'
                        )->execute([
                            ':id' => $requestId,
                            ':st' => 'admin',
                            ':sn' => $adminUser,
                            ':msg' => $message,
                        ]);
                        af('success', 'Mesaj eklendi.');
                        go('payments', ['payment_id' => $requestId]);

                    case 'message_support_thread':
                        $threadId = trim((string)($_POST['support_thread_id'] ?? ''));
                        $message = trim((string)($_POST['message'] ?? ''));
                        if ($threadId === '' || $message === '') {
                            throw new RuntimeException('Mesaj bos olamaz.');
                        }
                        golder_add_support_thread_message($master, $threadId, 'admin', $adminUser, $message);
                        $master->prepare('UPDATE support_threads SET assigned_admin = :au WHERE id = :id')->execute([
                            ':au' => $adminUser,
                            ':id' => $threadId,
                        ]);
                        af('success', 'Destek mesaji eklendi.');
                        go('support', ['support_thread_id' => $threadId]);

                    case 'close_support_thread':
                        $threadId = trim((string)($_POST['support_thread_id'] ?? ''));
                        if ($threadId === '') {
                            throw new RuntimeException('Support thread secilmedi.');
                        }
                        $master->prepare(
                            'UPDATE support_threads
                             SET status = :st,
                                 assigned_admin = :au,
                                 closed_at = UTC_TIMESTAMP(),
                                 updated_at = UTC_TIMESTAMP()
                             WHERE id = :id'
                        )->execute([
                            ':st' => 'closed',
                            ':au' => $adminUser,
                            ':id' => $threadId,
                        ]);
                        af('success', 'Destek sohbeti kapatildi.');
                        go('support', ['support_thread_id' => $threadId]);

                    case 'reopen_support_thread':
                        $threadId = trim((string)($_POST['support_thread_id'] ?? ''));
                        if ($threadId === '') {
                            throw new RuntimeException('Support thread secilmedi.');
                        }
                        $master->prepare(
                            'UPDATE support_threads
                             SET status = :st,
                                 assigned_admin = :au,
                                 closed_at = NULL,
                                 updated_at = UTC_TIMESTAMP()
                             WHERE id = :id'
                        )->execute([
                            ':st' => 'open',
                            ':au' => $adminUser,
                            ':id' => $threadId,
                        ]);
                        af('success', 'Destek sohbeti tekrar acildi.');
                        go('support', ['support_thread_id' => $threadId]);

                    case 'create_demo_manual':
                        $demo = create_manual_demo(
                            $master,
                            trim((string)($_POST['full_name'] ?? '')),
                            trim((string)($_POST['email'] ?? '')),
                            trim((string)($_POST['phone'] ?? '')),
                            trim((string)($_POST['password'] ?? ''))
                        );
                        af(
                            'success',
                            'Demo olusturuldu. Kod: ' . $demo['demo_code'] . ' | Kullanici: ' . $demo['username'] . ' | Sifre: ' . $demo['password']
                        );
                        go('demo');

                    case 'approve_demo_request':
                        $requestId = trim((string)($_POST['demo_request_id'] ?? ''));
                        $passwordOverride = trim((string)($_POST['demo_password'] ?? ''));
                        $adminMessage = trim((string)($_POST['admin_message'] ?? ''));
                        $res = golder_approve_demo_request($master, $requestId, $adminUser, $passwordOverride);
                        if (empty($res['ok'])) {
                            throw new RuntimeException((string)($res['message'] ?? 'Demo request approve failed.'));
                        }
                        if ($adminMessage !== '') {
                            golder_add_demo_request_message($master, $requestId, 'admin', $adminUser, $adminMessage);
                            $master->prepare('UPDATE demo_requests SET admin_message = :m WHERE id = :id')->execute([
                                ':m' => $adminMessage,
                                ':id' => $requestId,
                            ]);
                        }
                        $mail = (array)($res['mail'] ?? []);
                        af(
                            'success',
                            'Demo onaylandi. Kullanici: ' . (string)($res['credentials']['username'] ?? '-')
                            . ' | Sifre: ' . (string)($res['credentials']['password'] ?? '-')
                            . ' | Mail: ' . (!empty($mail['ok']) ? 'sent' : ('failed - ' . (string)($mail['message'] ?? 'unknown')))
                        );
                        go('demo', ['demo_request_id' => $requestId]);

                    case 'reject_demo_request':
                        $requestId = trim((string)($_POST['demo_request_id'] ?? ''));
                        $adminMessage = trim((string)($_POST['admin_message'] ?? 'Demo talebiniz reddedildi.'));
                        $res = golder_reject_demo_request($master, $requestId, $adminUser, $adminMessage);
                        if (empty($res['ok'])) {
                            throw new RuntimeException((string)($res['message'] ?? 'Demo request reject failed.'));
                        }
                        af('success', 'Demo talebi reddedildi.');
                        go('demo', ['demo_request_id' => $requestId]);

                    case 'message_demo_request':
                        $requestId = trim((string)($_POST['demo_request_id'] ?? ''));
                        $message = trim((string)($_POST['message'] ?? ''));
                        if ($requestId === '' || $message === '') {
                            throw new RuntimeException('Mesaj bos olamaz.');
                        }
                        golder_add_demo_request_message($master, $requestId, 'admin', $adminUser, $message);
                        af('success', 'Demo talebine mesaj eklendi.');
                        go('demo', ['demo_request_id' => $requestId]);

                    case 'upsert_pricing_yearly':
                        admin_upsert_yearly_pricing(
                            $master,
                            (string)($_POST['plan_type'] ?? golder_default_plan_type()),
                            (float)($_POST['base_price'] ?? 0),
                            (float)($_POST['per_pc_price'] ?? 0),
                            (float)($_POST['per_web_price'] ?? 0),
                            (string)($_POST['currency'] ?? 'TRY')
                        );
                        af('success', 'Yillik pricing kaydedildi.');
                        go('pricing');

                    case 'add_bank_account':
                        $accountName = trim((string)($_POST['account_name'] ?? ''));
                        $iban = strtoupper(str_replace(' ', '', trim((string)($_POST['iban'] ?? ''))));
                        if ($accountName === '' || $iban === '') {
                            throw new RuntimeException('account_name ve iban zorunlu.');
                        }
                        $master->prepare(
                            'INSERT INTO bank_accounts (account_name, iban, is_active, display_order)
                             VALUES (:an, :ib, :ia, :ord)'
                        )->execute([
                            ':an' => $accountName,
                            ':ib' => $iban,
                            ':ia' => !empty($_POST['is_active']) ? 1 : 0,
                            ':ord' => (int)($_POST['display_order'] ?? 0),
                        ]);
                        af('success', 'Banka hesabi eklendi.');
                        go('pricing');

                    case 'toggle_bank_account':
                        $master->prepare('UPDATE bank_accounts SET is_active = :ia WHERE id = :id')->execute([
                            ':ia' => ((int)($_POST['next_state'] ?? 0) === 1 ? 1 : 0),
                            ':id' => (int)($_POST['bank_id'] ?? 0),
                        ]);
                        af('success', 'Banka hesabi guncellendi.');
                        go('pricing');
                }
            } catch (Throwable $e) {
                $flash = ['type' => 'error', 'message' => $e->getMessage()];
            }
        }
    }
}

$csrf = golder_admin_csrf_token();
$logged = golder_admin_is_logged_in();

$dashboard = [];
$customers = [];
$devices = [];
$sessions = [];
$activeDevices = [];
$activeSessions = [];
$selectedCustomerActivity = [];
$payments = [];
$paymentMessages = [];
$selectedSupportThread = null;
$demos = [];
$demoRequests = [];
$demoRequestMessages = [];
$supportThreads = [];
$supportMessages = [];
$pricingByPlan = [
    'L-SOLO' => ['base_price' => '0.00', 'per_pc_price' => '0.00', 'per_web_price' => '0.00', 'currency' => 'TRY'],
    'L-SYNC' => ['base_price' => '0.00', 'per_pc_price' => '0.00', 'per_web_price' => '0.00', 'currency' => 'TRY'],
    'A-SOLO' => ['base_price' => '0.00', 'per_pc_price' => '0.00', 'per_web_price' => '0.00', 'currency' => 'TRY'],
    'A-OFFICE' => ['base_price' => '0.00', 'per_pc_price' => '0.00', 'per_web_price' => '0.00', 'currency' => 'TRY'],
    'A-COMPLEX' => ['base_price' => '0.00', 'per_pc_price' => '0.00', 'per_web_price' => '0.00', 'currency' => 'TRY'],
];
$banks = [];
$jobs = [];

$selectedCustomerId = (int)($_GET['customer_id'] ?? 0);
$selectedPaymentId = trim((string)($_GET['payment_id'] ?? ''));
$selectedSupportThreadId = trim((string)($_GET['support_thread_id'] ?? ''));
$selectedDemoRequestId = trim((string)($_GET['demo_request_id'] ?? ''));
$selectedCustomer = null;
$selectedPayment = null;
$selectedDemoRequest = null;

$paymentStatus = trim((string)($_GET['status'] ?? 'pending'));
if (!in_array($paymentStatus, ['pending', 'approved', 'rejected', 'all'], true)) {
    $paymentStatus = 'pending';
}
$demoStatus = trim((string)($_GET['demo_status'] ?? 'pending'));
if (!in_array($demoStatus, ['pending', 'approved', 'rejected', 'all'], true)) {
    $demoStatus = 'pending';
}
$supportStatus = trim((string)($_GET['support_status'] ?? 'open'));
if (!in_array($supportStatus, ['open', 'closed', 'all'], true)) {
    $supportStatus = 'open';
}

$backupSummary = [
    'storage_dir' => golder_backup_storage_dir(),
    'total_count' => 0,
    'total_bytes' => 0,
    'manual_today' => 0,
    'last_created' => null,
    'profile_quota' => 1,
    'soft_quota_bytes' => (float)golder_env('GOLDER_BACKUP_SOFT_QUOTA_BYTES', '10737418240'),
];
$backupProfiles = [];

if ($logged) {
    $master = golder_master_pdo();
    admin_ensure_schema($master);
    $sessionTimeoutSql = (string)golder_web_session_timeout_seconds();
    $hasPaymentRequests = admin_table_exists($master, 'payment_requests');
    $hasDemoRequests = admin_table_exists($master, 'demo_requests');
    $hasSupportThreads = admin_table_exists($master, 'support_threads');
    $hasDemoLicenses = admin_table_exists($master, 'demo_licenses');
    $hasBackupFiles = admin_table_exists($master, 'backup_files');
    $hasPricingRules = admin_table_exists($master, 'pricing_rules');
    $hasBankAccounts = admin_table_exists($master, 'bank_accounts');
    $hasJobRuns = admin_table_exists($master, 'job_runs');
    $hasPortalUsers = admin_table_exists($master, 'sales_portal_users');

    $dashboard = [
        'customers' => (int)$master->query('SELECT COUNT(*) FROM customers')->fetchColumn(),
        'pending_payments' => $hasPaymentRequests
            ? (int)admin_safe_scalar_query($master, "SELECT COUNT(*) FROM payment_requests WHERE status='pending'", 0)
            : 0,
        'pending_demo_requests' => $hasDemoRequests
            ? (int)admin_safe_scalar_query($master, "SELECT COUNT(*) FROM demo_requests WHERE status='pending'", 0)
            : 0,
        'active_demos' => $hasDemoLicenses
            ? (int)admin_safe_scalar_query($master, "SELECT COUNT(*) FROM demo_licenses WHERE status='active'", 0)
            : 0,
        'open_support_threads' => $hasSupportThreads
            ? (int)admin_safe_scalar_query($master, "SELECT COUNT(*) FROM support_threads WHERE status='open'", 0)
            : 0,
        'mismatch_payments' => $hasPaymentRequests
            ? (int)admin_safe_scalar_query($master, "SELECT COUNT(*) FROM payment_requests WHERE status='pending' AND amount_mismatch_flag=1", 0)
            : 0,
        'active_sessions' => (int)$master->query(
            "SELECT COUNT(*)
             FROM customer_web_sessions
             WHERE is_active = 1
               AND logout_at IS NULL
               AND (expires_at IS NULL OR expires_at >= UTC_TIMESTAMP())
               AND last_activity >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL {$sessionTimeoutSql} SECOND)
               AND (
                    NOT EXISTS (
                        SELECT 1
                        FROM customer_web_session_tabs t_all
                        WHERE t_all.session_uuid = customer_web_sessions.session_uuid
                    )
                    OR EXISTS (
                        SELECT 1
                        FROM customer_web_session_tabs t_active
                        WHERE t_active.session_uuid = customer_web_sessions.session_uuid
                          AND t_active.disconnected_at IS NULL
                          AND t_active.last_seen_at >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL {$sessionTimeoutSql} SECOND)
                    )
               )"
        )->fetchColumn(),
        'jobs_last_day' => $hasJobRuns
            ? (int)admin_safe_scalar_query($master, "SELECT COUNT(*) FROM job_runs WHERE started_at >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL 1 DAY)", 0)
            : 0,
    ];

    $term = trim((string)($_GET['q'] ?? ''));
    $backupCountSelect = $hasBackupFiles
        ? '(SELECT COUNT(*) FROM backup_files b WHERE b.customer_id = c.id) AS backup_count'
        : '0 AS backup_count';
    $customerSql =
        'SELECT c.*,
                ' . $backupCountSelect . '
         FROM customers c';
    $params = [];
    if ($term !== '') {
        $customerSql .= ' WHERE c.username LIKE :t OR c.email LIKE :t OR c.phone_number LIKE :t';
        $params[':t'] = '%' . $term . '%';
    }
    $customerSql .= ' ORDER BY c.id DESC LIMIT 200';
    $stCustomers = $master->prepare($customerSql);
    $stCustomers->execute($params);
    $customers = $stCustomers->fetchAll() ?: [];
    $customerIds = array_values(array_filter(array_map(static fn(array $row): int => (int)($row['id'] ?? 0), $customers), static fn(int $id): bool => $id > 0));
    $activityMap = golder_customer_activity_map($master, $customerIds);
    foreach ($customers as &$customerRow) {
        $customerId = (int)($customerRow['id'] ?? 0);
        $summary = $activityMap[$customerId] ?? [];
        $customerRow['active_pc_sessions'] = (int)($summary['active_pc_sessions'] ?? 0);
        $customerRow['active_pc_devices'] = (int)($summary['active_pc_devices'] ?? 0);
        $customerRow['registered_pc_devices'] = (int)($summary['registered_pc_devices'] ?? 0);
        $customerRow['active_web_devices'] = (int)($summary['active_web_devices'] ?? 0);
        $customerRow['registered_web_devices'] = (int)($summary['registered_web_devices'] ?? 0);
        $customerRow['active_web_sessions'] = (int)($summary['active_web_sessions'] ?? 0);
        $customerRow['last_seen_at'] = (string)($summary['last_seen_at'] ?? '');
    }
    unset($customerRow);

    if ($selectedCustomerId <= 0 && $customers) {
        $selectedCustomerId = (int)($customers[0]['id'] ?? 0);
    }
    if ($selectedCustomerId > 0) {
        $selectedCustomer = golder_customer_by_id($master, $selectedCustomerId);
        if ($selectedCustomer) {
            $selectedCustomer = golder_enforce_customer_plan($master, $selectedCustomerId) ?? $selectedCustomer;
            $devices = golder_list_customer_devices($master, $selectedCustomerId);
            $sessions = golder_list_customer_web_sessions($master, $selectedCustomerId);
            $selectedCustomerActivity = golder_customer_activity_summary($master, $selectedCustomerId);
            $activeDevices = array_values(array_filter($devices, static function (array $row): bool {
                return (int)($row['is_blocked'] ?? 0) === 0 && (int)($row['is_active_device'] ?? 0) === 1;
            }));
            $activeSessions = array_values(array_filter($sessions, static function (array $row): bool {
                return (int)($row['is_active_now'] ?? 0) === 1;
            }));

            if ($hasBackupFiles) {
                $stBackupSummary = $master->prepare(
                    "SELECT
                        COUNT(*) AS total_count,
                        COALESCE(SUM(file_size), 0) AS total_bytes,
                        SUM(CASE WHEN backup_type='manual' AND DATE(created_at)=UTC_DATE() THEN 1 ELSE 0 END) AS manual_today,
                        MAX(created_at) AS last_created
                     FROM backup_files
                     WHERE customer_id = :cid"
                );
                $stBackupSummary->execute([':cid' => $selectedCustomerId]);
                $row = $stBackupSummary->fetch() ?: [];
                $backupSummary['total_count'] = (int)($row['total_count'] ?? 0);
                $backupSummary['total_bytes'] = (int)($row['total_bytes'] ?? 0);
                $backupSummary['manual_today'] = (int)($row['manual_today'] ?? 0);
                $backupSummary['last_created'] = $row['last_created'] ?? null;
            }

            $profileNameMap = [];
            try {
                $tenant = golder_tenant_pdo_from_customer($selectedCustomer);
                $profileRows = $tenant->query('SELECT id, name FROM profiles ORDER BY created_at DESC LIMIT 500')->fetchAll() ?: [];
                foreach ($profileRows as $profileRow) {
                    $pid = trim((string)($profileRow['id'] ?? ''));
                    if ($pid === '') {
                        continue;
                    }
                    $profileNameMap[$pid] = trim((string)($profileRow['name'] ?? ''));
                }
            } catch (Throwable $_ignored) {
            }

            $backupSummary['profile_quota'] = max(1, count($profileNameMap));
            if ($hasBackupFiles) {
                $stProfileStats = $master->prepare(
                    'SELECT profile_id, COUNT(*) AS backup_count, COALESCE(SUM(file_size),0) AS total_bytes, MAX(created_at) AS last_created
                     FROM backup_files
                     WHERE customer_id = :cid
                     GROUP BY profile_id
                     ORDER BY backup_count DESC, profile_id ASC'
                );
                $stProfileStats->execute([':cid' => $selectedCustomerId]);
                foreach ($stProfileStats->fetchAll() ?: [] as $profileStat) {
                    $pid = trim((string)($profileStat['profile_id'] ?? ''));
                    if ($pid === '') {
                        continue;
                    }
                    $backupProfiles[] = [
                        'profile_id' => $pid,
                        'profile_name' => $profileNameMap[$pid] ?? '-',
                        'backup_count' => (int)($profileStat['backup_count'] ?? 0),
                        'total_bytes' => (int)($profileStat['total_bytes'] ?? 0),
                        'last_created' => $profileStat['last_created'] ?? null,
                    ];
                }
            }
        }
    }

    if ($hasPaymentRequests) {
        $portalJoin = $hasPortalUsers
            ? ' LEFT JOIN sales_portal_users spu ON spu.id = pr.portal_user_id'
            : ' ';
        $portalSelect = $hasPortalUsers
            ? ', spu.email AS portal_email, spu.full_name AS portal_full_name'
            : ", '' AS portal_email, '' AS portal_full_name";
        $paymentSql =
            'SELECT pr.*, c.username AS customer_username' . $portalSelect . '
             FROM payment_requests pr
             LEFT JOIN customers c ON c.id = pr.customer_id' . $portalJoin;
        $params = [];
        if ($paymentStatus !== 'all') {
            $paymentSql .= ' WHERE pr.status = :st';
            $params[':st'] = $paymentStatus;
        }
        $paymentSql .= ' ORDER BY pr.created_at DESC LIMIT 300';
        $stPayments = $master->prepare($paymentSql);
        $stPayments->execute($params);
        $payments = $stPayments->fetchAll() ?: [];

        if ($selectedPaymentId === '' && $payments) {
            $selectedPaymentId = (string)($payments[0]['id'] ?? '');
        }
        if ($selectedPaymentId !== '') {
            $stPayment = $master->prepare(
                'SELECT pr.*, c.username AS customer_username' . $portalSelect . '
                 FROM payment_requests pr
                 LEFT JOIN customers c ON c.id = pr.customer_id' . $portalJoin . '
                 WHERE pr.id = :id
                 LIMIT 1'
            );
            $stPayment->execute([':id' => $selectedPaymentId]);
            $selectedPayment = $stPayment->fetch() ?: null;
            $paymentMessages = function_exists('golder_payment_request_messages')
                ? golder_payment_request_messages($master, $selectedPaymentId)
                : [];
        }
    }

    if ($hasSupportThreads) {
        $supportPortalJoin = $hasPortalUsers
            ? ' LEFT JOIN sales_portal_users spu ON spu.id = st.portal_user_id'
            : ' ';
        $supportPortalSelect = $hasPortalUsers
            ? 'spu.full_name AS portal_full_name, spu.email AS portal_email, '
            : "'' AS portal_full_name, '' AS portal_email, ";
        $supportSql =
            'SELECT st.*, ' . $supportPortalSelect . 'c.username AS customer_username
             FROM support_threads st' . $supportPortalJoin . '
             LEFT JOIN customers c ON c.id = st.customer_id';
        $params = [];
        if ($supportStatus !== 'all') {
            $supportSql .= ' WHERE st.status = :sst';
            $params[':sst'] = $supportStatus;
        }
        $supportSql .= ' ORDER BY st.updated_at DESC LIMIT 300';
        $stSupport = $master->prepare($supportSql);
        $stSupport->execute($params);
        $supportThreads = $stSupport->fetchAll() ?: [];

        if ($selectedSupportThreadId === '' && $supportThreads) {
            $selectedSupportThreadId = (string)($supportThreads[0]['id'] ?? '');
        }
        if ($selectedSupportThreadId !== '' && function_exists('golder_support_thread_by_id')) {
            $selectedSupportThread = golder_support_thread_by_id($master, $selectedSupportThreadId);
            $supportMessages = function_exists('golder_support_thread_messages')
                ? golder_support_thread_messages($master, $selectedSupportThreadId)
                : [];
        }
    }

    if ($hasDemoLicenses) {
        $demos = $master->query(
            'SELECT dl.*, c.username, c.email, c.phone_number
             FROM demo_licenses dl
             INNER JOIN customers c ON c.id = dl.customer_id
             ORDER BY dl.created_at DESC
             LIMIT 300'
        )->fetchAll() ?: [];
    }

    if ($hasDemoRequests) {
        $demoPortalJoin = $hasPortalUsers
            ? ' LEFT JOIN sales_portal_users spu ON spu.id = dr.portal_user_id'
            : ' ';
        $demoPortalSelect = $hasPortalUsers
            ? 'spu.full_name AS portal_full_name, spu.email AS portal_email, '
            : "'' AS portal_full_name, '' AS portal_email, ";
        $demoReqSql =
            'SELECT dr.*, ' . $demoPortalSelect . 'c.username AS approved_customer_username
             FROM demo_requests dr' . $demoPortalJoin . '
             LEFT JOIN customers c ON c.id = dr.approved_customer_id';
        $params = [];
        if ($demoStatus !== 'all') {
            $demoReqSql .= ' WHERE dr.status = :dst';
            $params[':dst'] = $demoStatus;
        }
        $demoReqSql .= ' ORDER BY dr.created_at DESC LIMIT 300';
        $stDemoReq = $master->prepare($demoReqSql);
        $stDemoReq->execute($params);
        $demoRequests = $stDemoReq->fetchAll() ?: [];

        if ($selectedDemoRequestId === '' && $demoRequests) {
            $selectedDemoRequestId = (string)($demoRequests[0]['id'] ?? '');
        }
        if ($selectedDemoRequestId !== '' && function_exists('golder_demo_request_by_id')) {
            $selectedDemoRequest = golder_demo_request_by_id($master, $selectedDemoRequestId);
            if ($selectedDemoRequest) {
                $selectedDemoRequest['demo_password'] = golder_decrypt_demo_secret((string)($selectedDemoRequest['demo_password_enc'] ?? ''));
                $demoRequestMessages = function_exists('golder_demo_request_messages')
                    ? golder_demo_request_messages($master, $selectedDemoRequestId)
                    : [];
            }
        }
    }

    if ($hasPricingRules) {
        $pricingRows = $master->query("SELECT * FROM pricing_rules WHERE duration_key='yearly' ORDER BY plan_type ASC")->fetchAll() ?: [];
        foreach ($pricingRows as $row) {
            $plan = (string)($row['plan_type'] ?? '');
            if (!isset($pricingByPlan[$plan])) {
                continue;
            }
            $pricingByPlan[$plan] = [
                'base_price' => (string)($row['base_price'] ?? '0.00'),
                'per_pc_price' => (string)($row['per_pc_price'] ?? '0.00'),
                'per_web_price' => (string)($row['per_web_price'] ?? '0.00'),
                'currency' => (string)($row['currency'] ?? 'TRY'),
            ];
        }
    }

    if ($hasBankAccounts) {
        $banks = $master->query('SELECT * FROM bank_accounts ORDER BY display_order ASC, id ASC')->fetchAll() ?: [];
    }
    if ($hasJobRuns) {
        $jobs = $master->query('SELECT * FROM job_runs ORDER BY started_at DESC, id DESC LIMIT 100')->fetchAll() ?: [];
    }
}
?>
<!doctype html>
<html lang="tr">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Golder Admin V2</title>
    <style>
        :root {
            --bg: #090909;
            --card: #141414;
            --line: #2a2a2a;
            --text: #f5f5f5;
            --muted: #b0b0b0;
            --gold: #b88a3b;
            --gold-dark: #8d6a2c;
            --ok: #69d38d;
            --warn: #d4a451;
            --err: #f07070;
        }
        * { box-sizing: border-box; }
        body { margin: 0; font-family: Segoe UI, Arial, sans-serif; background: radial-gradient(circle at top, #1a1a1a 0%, var(--bg) 55%); color: var(--text); }
        main { width: min(1500px, calc(100% - 28px)); margin: 14px auto 18px; }
        .box { border: 1px solid var(--line); border-radius: 16px; background: linear-gradient(180deg, #181818 0%, var(--card) 100%); padding: 14px; margin-bottom: 12px; box-shadow: 0 14px 34px rgba(0,0,0,.28); }
        nav a { display: inline-block; text-decoration: none; color: var(--text); border: 1px solid var(--line); padding: 8px 12px; border-radius: 999px; margin-right: 8px; margin-bottom: 8px; background:#111; }
        nav a.on { background: var(--gold); border-color: var(--gold); color: #fff; }
        .flash { padding: 11px 12px; border-radius: 10px; margin-bottom: 12px; }
        .flash.success { background: rgba(44, 109, 70, .18); color: var(--ok); border: 1px solid rgba(105, 211, 141, .25); }
        .flash.error { background: rgba(159, 47, 47, .18); color: #ffd8d8; border: 1px solid rgba(240, 112, 112, .25); }
        .grid { display: grid; gap: 12px; }
        .two { grid-template-columns: 1.2fr 1fr; }
        .metrics { grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); }
        table { width: 100%; border-collapse: collapse; }
        th, td { text-align: left; vertical-align: top; border-bottom: 1px solid var(--line); padding: 8px; font-size: 13px; }
        th { background: #1b1b1b; }
        input, select, textarea, button { width: 100%; border: 1px solid var(--line); border-radius: 10px; padding: 8px 10px; font: inherit; background:#101010; color:var(--text); }
        textarea { min-height: 82px; }
        button { cursor: pointer; background: linear-gradient(180deg, var(--gold) 0%, var(--gold-dark) 100%); color: #fff; border-color: var(--gold-dark); }
        button.secondary { background: #161616; color: var(--text); }
        button.danger { background: linear-gradient(180deg, #bb4f4f 0%, #8b2d2d 100%); border-color: #8b2d2d; }
        button.warning { background: linear-gradient(180deg, #c08c3c 0%, #935f16 100%); border-color: #935f16; }
        .inline { display: inline-block; width: auto; }
        .inline input, .inline button, .inline select { width: auto; }
        .muted { color: var(--muted); font-size: 12px; }
        .kpi { font-size: 30px; font-weight: 700; margin-bottom: 4px; }
        .row-tools { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
        .row-tools input { width: 150px; }
        .status-pill { display: inline-block; padding: 3px 8px; border-radius: 999px; font-size: 12px; border: 1px solid var(--line); }
        .status-pill.pending { background: #fff7e9; color: var(--warn); border-color: #ebcf9f; }
        .status-pill.open { background: #edf8f2; color: var(--ok); border-color: #c5e3d3; }
        .status-pill.closed { background: #f4f4f4; color: #666; border-color: #ddd; }
        .status-pill.approved { background: #edf8f2; color: var(--ok); border-color: #c5e3d3; }
        .status-pill.rejected { background: #fff1f1; color: var(--err); border-color: #e5c1c1; }
        .status-pill.expired { background: #f4f4f4; color: #666; border-color: #ddd; }
        .msg-list { display: grid; gap: 8px; }
        .msg-item { border: 1px solid var(--line); border-radius: 8px; padding: 8px; background: #161616; }
        .msg-item header { display: flex; justify-content: space-between; font-size: 12px; color: var(--muted); margin-bottom: 5px; }
        .msg-item p { margin: 0; white-space: pre-wrap; font-size: 13px; }
        .warn-box { padding: 11px; border-radius: 9px; border: 1px solid rgba(212,164,81,.25); background: rgba(212,164,81,.14); color: #f3cb7e; }
        .danger-box { padding: 11px; border-radius: 9px; border: 1px solid #e4b4b4; background: #fff3f3; color: #8a2a2a; }
        .progress { margin-top: 6px; background: #1b1b1b; border: 1px solid var(--line); border-radius: 999px; height: 10px; overflow: hidden; }
        .progress > span { display: block; height: 100%; background: linear-gradient(90deg, #b88a3b 0%, #845a20 100%); }
        .progress.warn > span { background: linear-gradient(90deg, #d59b34 0%, #9b6315 100%); }
        .progress.err > span { background: linear-gradient(90deg, #ca5e5e 0%, #912f2f 100%); }
        .pill-mini { font-size: 11px; border: 1px solid #ddcfb7; background: #fff8ec; color: #6e4e1f; border-radius: 999px; padding: 2px 8px; display: inline-block; }
        .form-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 9px; }
        .form-grid.three { grid-template-columns: repeat(3, minmax(0, 1fr)); }
        .form-grid label { display: flex; flex-direction: column; gap: 4px; font-size: 12px; color: var(--muted); }
        .code { font-family: Consolas, monospace; font-size: 12px; background: #141414; padding: 2px 6px; border-radius: 6px; border: 1px solid var(--line); color: var(--text); }
        @media (max-width: 1100px) {
            .two, .form-grid, .form-grid.three { grid-template-columns: 1fr; }
            .row-tools input { width: 100%; }
        }
    </style>
</head>
<body>
<main>
<?php if (!$logged): ?>
    <div class="box" style="max-width:460px; margin:70px auto 0;">
        <h1>Golder Admin V2</h1>
        <p>Env: <code>GOLDER_ADMIN_USER</code>, <code>GOLDER_ADMIN_PASS</code></p>
        <?php if ($flash): ?>
            <div class="flash <?= h($flash['type'] ?? 'error') ?>"><?= h($flash['message'] ?? '') ?></div>
        <?php endif; ?>
        <?php if (!$configured): ?>
            <div class="flash error">Admin credential tanimli degil.</div>
        <?php endif; ?>
        <form method="post">
            <input type="hidden" name="action" value="login">
            <p><input type="text" name="username" placeholder="Kullanici" required></p>
            <p><input type="password" name="password" placeholder="Sifre" required></p>
            <button type="submit">Giris</button>
        </form>
    </div>
<?php else: ?>
    <div class="box">
        <strong>Golder Admin V2</strong>
        <span class="muted"> | <?= h($adminUser) ?> | UTC <?= h(gmdate('Y-m-d H:i:s')) ?></span>
        <form method="post" class="inline" style="float:right">
            <input type="hidden" name="action" value="logout">
            <input type="hidden" name="csrf_token" value="<?= h($csrf) ?>">
            <button type="submit" class="secondary">Logout</button>
        </form>
    </div>

    <nav>
        <a class="<?= $tab === 'customers' ? 'on' : '' ?>" href="?tab=customers">Musteriler</a>
        <a class="<?= $tab === 'devices' ? 'on' : '' ?>" href="?tab=devices<?= $selectedCustomerId > 0 ? '&customer_id=' . $selectedCustomerId : '' ?>">Cihaz/Oturum</a>
        <a class="<?= $tab === 'pricing' ? 'on' : '' ?>" href="?tab=pricing">Pricing</a>
        <a class="<?= $tab === 'demo' ? 'on' : '' ?>" href="?tab=demo">Demo Yonetimi</a>
        <a class="<?= $tab === 'jobs' ? 'on' : '' ?>" href="?tab=jobs">Job Runs</a>
    </nav>

    <?php if ($flash): ?>
        <div class="flash <?= h($flash['type'] ?? 'error') ?>"><?= h($flash['message'] ?? '') ?></div>
    <?php endif; ?>

    <?php if ($tab === 'dashboard'): ?>
        <div class="grid metrics">
            <?php foreach ($dashboard as $label => $count): ?>
                <div class="box">
                    <div class="kpi"><?= (int)$count ?></div>
                    <div class="muted"><?= h($label) ?></div>
                </div>
            <?php endforeach; ?>
        </div>
        <div class="box">
            <h3>Global Ticari Kurallar</h3>
            <ul>
                <li>Ticari akislarda sadece <strong>yearly</strong> fiyatlandirma aktif.</li>
                <li>L-SOLO / A-SOLO web-mobil kapali; L-SYNC / A-COMPLEX web-mobil acik; A-OFFICE sadece PC senkronu icin acik.</li>
                <li>Public demo talepleri <strong>pending</strong> acilir, admin onayinda provision edilir.</li>
                <li>Expired demo + 48 saat sonrasinda hard-delete cron ile fiziksel temizlik yapilir.</li>
            </ul>
        </div>

    <?php elseif ($tab === 'customers'): ?>
        <div class="grid two">
            <div class="box">
                <form method="get" class="inline">
                    <input type="hidden" name="tab" value="customers">
                    <input type="text" name="q" value="<?= h($_GET['q'] ?? '') ?>" placeholder="username / email / telefon">
                    <button type="submit" class="secondary">Filtrele</button>
                </form>
                <table>
                    <tr><th>ID</th><th>Kullanici</th><th>Plan</th><th>Lisans</th><th>Hak (Limit)</th><th>Kullanim</th><th>Backup</th><th>Sil</th></tr>
                    <?php foreach ($customers as $row): $effective = golder_customer_effective_plan($row); $uname = (string)($row['username'] ?? ''); ?>
                        <tr>
                            <td><a href="?tab=customers&amp;customer_id=<?= (int)$row['id'] ?>">#<?= (int)$row['id'] ?></a></td>
                            <td><strong><?= h($uname) ?></strong><br><span class="muted"><?= h($row['email'] ?? '-') ?> | <?= h($row['phone_number'] ?? '-') ?></span></td>
                            <td><?= h(golder_plan_label((string)($effective['plan_type'] ?? ''))) ?></td>
                            <td>
                                <span class="status-pill <?= h((string)($row['license_status'] ?? '')) ?>"><?= h($row['license_status'] ?? '-') ?></span><br>
                                <span class="muted">Desktop: <?= h(($effective['desktop_expiry_date'] ?? '') !== '' ? (string)$effective['desktop_expiry_date'] : 'Suresiz') ?></span><br>
                                <span class="muted">Sync: <?= h(($effective['sync_expiry_date'] ?? '') !== '' ? (string)$effective['sync_expiry_date'] : ((string)($effective['sync_status'] ?? '') === 'disabled' ? 'Kapali' : '-')) ?></span><br>
                                <span class="pill-mini">Sync <?= h((string)($effective['sync_status'] ?? 'disabled')) ?></span>
                            </td>
                            <td style="line-height: 1.6;">
                                <span style="display:inline-block; width:35px;" class="muted">PC:</span> <strong><?= (int)($effective['max_pc_devices'] ?? 0) ?></strong><br>
                                <span style="display:inline-block; width:35px;" class="muted">Web:</span> <strong><?= (int)($effective['max_web_sessions'] ?? 0) ?></strong>
                            </td>
                            <td style="line-height: 1.6;">
                                <?php
                                $pcLimit = (int)($effective['max_pc_devices'] ?? 0);
                                $webLimit = (int)($effective['max_web_sessions'] ?? 0);
                                $pcActive = (int)($row['active_pc_sessions'] ?? 0);
                                $pcRegistered = (int)($row['registered_pc_devices'] ?? 0);
                                $webDevices = (int)($row['active_web_devices'] ?? 0);
                                $webRegistered = (int)($row['registered_web_devices'] ?? 0);
                                $webActive = (int)($row['active_web_sessions'] ?? 0);
                                $pcColor = ($pcLimit > 0 && $pcActive >= $pcLimit) ? '#d32f2f' : '#1b8f3f';
                                $webColor = ($webLimit > 0 && ($webActive >= $webLimit || $webDevices >= $webLimit)) ? '#d32f2f' : '#1b8f3f';
                                ?>
                                <span style="display:inline-block; width:35px;" class="muted">PC:</span> <strong style="color:<?= $pcColor ?>"><?= $pcActive ?></strong><br>
                                <span style="display:inline-block; width:35px;" class="muted">Web:</span> <strong style="color:<?= $webColor ?>"><?= $webActive ?></strong><br>
                                <span style="display:inline-block; width:35px;" class="muted">Cihaz:</span> <strong><?= $webDevices ?></strong>
                                <div class="muted" style="margin-top:4px">Kayitli: <?= $pcRegistered ?> PC / <?= $webRegistered ?> Web</div>
                            </td>
                            <td><?= (int)($row['backup_count'] ?? 0) ?></td>
                            <td>
                                <form method="post" class="row-tools" onsubmit="return confirm('Bu islem geri donulemez. Devam etmek istiyor musunuz?');">
                                    <input type="hidden" name="action" value="hard_delete_customer">
                                    <input type="hidden" name="csrf_token" value="<?= h($csrf) ?>">
                                    <input type="hidden" name="customer_id" value="<?= (int)$row['id'] ?>">
                                    <input type="text" name="confirm_text" placeholder="DELETE <?= h($uname) ?>" required>
                                    <button type="submit" class="danger">Tamamen Sil</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </table>
            </div>

            <div class="box">
                <h2>Manuel Musteri Olustur</h2>
                <p class="muted">Bu islem customer kaydi + tenant DB + MySQL user olusturur. Masaustu ve sync bitisleri secilen plana gore zorunlu hale gelir.</p>
                <form method="post" class="form-grid three" data-plan-sync="1">
                    <input type="hidden" name="action" value="create_customer">
                    <input type="hidden" name="csrf_token" value="<?= h($csrf) ?>">
                    <label>Username
                        <input type="text" name="username" required pattern="[a-z0-9_]+" placeholder="ornek_musteri">
                    </label>
                    <label>Adminin Belirledigi Sifre
                        <div class="row-tools">
                            <input type="text" name="password" id="create_customer_password" placeholder="Bossa otomatik uretilir">
                            <button type="button" class="secondary" data-password-target="create_customer_password">Oneri Uret</button>
                        </div>
                    </label>
                    <label>E-posta
                        <input type="email" name="email" placeholder="mail@example.com">
                    </label>
                    <label>Telefon
                        <input type="text" name="phone" placeholder="+90...">
                    </label>
                    <label>Plan
                        <select name="plan_type" data-plan-field>
                            <?php foreach (admin_plan_options() as $planCode => $planLabel): ?>
                                <option value="<?= h($planCode) ?>" <?= $planCode === golder_default_plan_type() ? 'selected' : '' ?>><?= h($planLabel) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </label>
                    <label>Max PC
                        <input type="number" name="max_pc_devices" min="1" value="1" data-plan-pc>
                    </label>
                    <label>Max WEB
                        <input type="number" name="max_web_sessions" min="0" value="1" data-plan-web>
                    </label>
                    <label>Masaustu Bitis (UTC)
                        <input type="text" name="desktop_expiry_date" value="" placeholder="YYYY-MM-DD HH:MM:SS" data-plan-desktop-expiry>
                    </label>
                    <label>Sync Bitis (UTC)
                        <input type="text" name="sync_expiry_date" value="" placeholder="YYYY-MM-DD HH:MM:SS" data-plan-sync-expiry>
                    </label>
                    <label>Yapay Zeka (AI) Asistanı
                        <select name="is_ai_enabled">
                            <option value="0">Kapalı</option>
                            <option value="1">Açık</option>
                        </select>
                    </label>
                    <label>Plan Notu
                        <input type="text" value="Lisans kurallari secilen plana gore otomatik uygulanir" readonly data-plan-note>
                    </label>
                    <div style="grid-column:1/-1">
                        <button type="submit">Musteri Ac</button>
                    </div>
                </form>
                <?php if ($selectedCustomer): $effective = golder_customer_effective_plan($selectedCustomer); ?>
                    <hr>
                    <h2>Musteri Detay Duzenleme (#<?= (int)($selectedCustomer['id'] ?? 0) ?>)</h2>
                    <form method="post" class="form-grid three" data-plan-sync="1">
                        <input type="hidden" name="action" value="update_customer_details">
                        <input type="hidden" name="csrf_token" value="<?= h($csrf) ?>">
                        <input type="hidden" name="customer_id" value="<?= (int)($selectedCustomer['id'] ?? 0) ?>">
                        <label>Username
                            <input type="text" name="username" required pattern="[a-z0-9_]+" value="<?= h($selectedCustomer['username'] ?? '') ?>">
                        </label>
                        <label>E-posta
                            <input type="email" name="email" value="<?= h($selectedCustomer['email'] ?? '') ?>">
                        </label>
                        <label>Telefon
                            <input type="text" name="phone_number" value="<?= h($selectedCustomer['phone_number'] ?? '') ?>">
                        </label>
                        <label>Plan
                            <select name="plan_type" data-plan-field>
                                <?php foreach (admin_plan_options() as $planCode => $planLabel): ?>
                                    <option value="<?= h($planCode) ?>" <?= ($effective['plan_type'] ?? '') === $planCode ? 'selected' : '' ?>><?= h($planLabel) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </label>
                        <label>Max PC
                            <input type="number" name="max_pc_devices" min="1" value="<?= (int)($effective['max_pc_devices'] ?? 1) ?>" data-plan-pc>
                        </label>
                        <label>Max WEB
                            <input type="number" name="max_web_sessions" min="0" value="<?= (int)($effective['max_web_sessions'] ?? 0) ?>" data-plan-web>
                        </label>
                        <label>Yapay Zeka (AI) Asistanı
                            <select name="is_ai_enabled">
                                <option value="0">Kapalı</option>
                                <option value="1" <?= (!empty($selectedCustomer['is_ai_enabled']) ? 'selected' : '') ?>>Açık</option>
                            </select>
                        </label>
                        <label>Lisans Durumu
                            <select name="license_status">
                                <?php foreach (['active', 'expired', 'suspended', 'pending', 'cancelled'] as $ls): ?>
                                    <option value="<?= h($ls) ?>" <?= (string)($selectedCustomer['license_status'] ?? 'active') === $ls ? 'selected' : '' ?>><?= h($ls) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </label>
                        <label>Masaustu Bitis (UTC)
                            <input type="text" name="desktop_expiry_date" value="<?= h(admin_datetime_value((string)($effective['desktop_expiry_date'] ?? ''))) ?>" placeholder="YYYY-MM-DD HH:MM:SS" data-plan-desktop-expiry>
                        </label>
                        <label>Sync Bitis (UTC)
                            <input type="text" name="sync_expiry_date" value="<?= h(admin_datetime_value((string)($effective['sync_expiry_date'] ?? ''))) ?>" placeholder="YYYY-MM-DD HH:MM:SS" data-plan-sync-expiry>
                        </label>
                        <label>Sync Durumu
                            <input type="text" value="<?= h((string)($effective['sync_status'] ?? 'disabled')) ?>" readonly data-plan-note>
                        </label>
                        <label>mysql_db_name
                            <input type="text" name="mysql_db_name" value="<?= h($selectedCustomer['mysql_db_name'] ?? '') ?>">
                        </label>
                        <label>mysql_db_user
                            <input type="text" name="mysql_db_user" value="<?= h($selectedCustomer['mysql_db_user'] ?? '') ?>">
                        </label>
                        <label>mysql_db_pass
                            <input type="text" name="mysql_db_pass" value="<?= h($selectedCustomer['mysql_db_pass'] ?? '') ?>">
                        </label>
                        <div style="grid-column:1/-1">
                            <button type="submit">Detaylari Kaydet</button>
                        </div>
                    </form>

                    <div class="warn-box" style="margin-top:10px;">
                        Masaustu HWID kilidini sifirlamak sadece PC cihaz kayitlarini ve desktop_sync tokenlarini temizler. Web/mobil oturumlari etkilenmez.
                        <form method="post" class="inline" onsubmit="return confirm('Kayitli PC HWID kilitleri sifirlansin mi?');" style="margin-top:8px;">
                            <input type="hidden" name="action" value="reset_hardware_lock">
                            <input type="hidden" name="csrf_token" value="<?= h($csrf) ?>">
                            <input type="hidden" name="customer_id" value="<?= (int)($selectedCustomer['id'] ?? 0) ?>">
                            <button type="submit" class="warning">Cihaz Kilidini Sifirla</button>
                        </form>
                    </div>

                    <div class="box" style="margin-top:10px;">
                        <h3>Musteri Sifresi</h3>
                        <p class="muted">Oneri uret + admin duzenle akisi. Veritabaninda sadece hash saklanir.</p>
                        <form method="post" class="form-grid" style="grid-template-columns:1fr auto;">
                            <input type="hidden" name="action" value="set_customer_password">
                            <input type="hidden" name="csrf_token" value="<?= h($csrf) ?>">
                            <input type="hidden" name="customer_id" value="<?= (int)($selectedCustomer['id'] ?? 0) ?>">
                            <input type="text" name="new_password" id="customer_password_input" placeholder="Bossa otomatik uretilir">
                            <button type="button" class="secondary" data-password-target="customer_password_input">Oneri Uret</button>
                            <div style="grid-column:1/-1">
                                <button type="submit">Sifreyi Guncelle</button>
                            </div>
                        </form>
                    </div>

                    <div class="box" style="margin-top:10px;">
                        <h3>Backup Netligi</h3>
                        <p class="muted">
                            Fiziksel backup yolu: <span class="code"><?= h($backupSummary['storage_dir']) ?></span><br>
                            Bu musteri klasoru: <span class="code"><?= h(rtrim((string)$backupSummary['storage_dir'], '/\\') . DIRECTORY_SEPARATOR . (string)($selectedCustomer['id'] ?? 0)) ?></span>
                        </p>
                        <div class="grid two" style="grid-template-columns:repeat(3, minmax(0, 1fr));">
                            <div>
                                <div><strong>Toplam Backup</strong></div>
                                <div class="kpi" style="font-size:24px"><?= (int)$backupSummary['total_count'] ?></div>
                                <div class="muted">Son islem: <?= h($backupSummary['last_created'] ?? '-') ?></div>
                            </div>
                            <div>
                                <div><strong>Toplam Boyut</strong></div>
                                <div class="kpi" style="font-size:24px"><?= admin_money(((int)$backupSummary['total_bytes']) / (1024 * 1024)) ?> MB</div>
                                <div class="muted">Disk kullanimi</div>
                            </div>
                            <div>
                                <?php
                                $manualQuota = max(1, (int)$backupSummary['profile_quota']);
                                $manualToday = (int)$backupSummary['manual_today'];
                                $manualPct = min(100, (int)round(($manualToday / $manualQuota) * 100));
                                $storageSoft = max(1, (float)$backupSummary['soft_quota_bytes']);
                                $storagePct = min(100, (int)round((((int)$backupSummary['total_bytes']) / $storageSoft) * 100));
                                ?>
                                <div><strong>Manuel Kota (Gunluk)</strong></div>
                                <div class="muted"><?= $manualToday ?> / <?= $manualQuota ?></div>
                                <div class="progress <?= $manualPct >= 100 ? 'warn' : '' ?>"><span style="width:<?= $manualPct ?>%"></span></div>
                                <div class="muted" style="margin-top:8px;">Toplam depolama kullanimi (soft quota)</div>
                                <div class="progress <?= $storagePct >= 90 ? 'err' : ($storagePct >= 70 ? 'warn' : '') ?>"><span style="width:<?= $storagePct ?>%"></span></div>
                            </div>
                        </div>

                        <h4 style="margin:12px 0 8px">Profil Eslesmeleri</h4>
                        <table>
                            <tr><th>Profile ID</th><th>Profil Adi</th><th>Backup Adedi</th><th>Boyut (MB)</th><th>Son Backup</th></tr>
                            <?php if (!$backupProfiles): ?>
                                <tr><td colspan="5" class="muted">Bu musteri icin backup metadata bulunamadi.</td></tr>
                            <?php else: ?>
                                <?php
                                $maxCount = 1;
                                foreach ($backupProfiles as $bp) {
                                    $maxCount = max($maxCount, (int)$bp['backup_count']);
                                }
                                ?>
                                <?php foreach ($backupProfiles as $bp): ?>
                                    <?php $pct = min(100, (int)round(((int)$bp['backup_count'] / $maxCount) * 100)); ?>
                                    <tr>
                                        <td><span class="code"><?= h($bp['profile_id']) ?></span></td>
                                        <td><?= h($bp['profile_name']) ?></td>
                                        <td><?= (int)$bp['backup_count'] ?><div class="progress" style="margin-top:4px"><span style="width:<?= $pct ?>%"></span></div></td>
                                        <td><?= admin_money(((int)$bp['total_bytes']) / (1024 * 1024)) ?></td>
                                        <td><?= h($bp['last_created'] ?? '-') ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </table>
                    </div>

                    <div class="danger-box" style="margin-top:10px;">
                        <h3 style="margin-top:0">Musteriyi Tamamen Sil (Geri Donulemez)</h3>
                        <p>Bu islem customers kaydi, tenant DB, MySQL user, demo/payment iliskileri, cihaz/oturum/token kayitlari, backup metadata ve disk dosyalarini siler.</p>
                        <form method="post" class="row-tools" onsubmit="return confirm('Musteri tamamen silinecek. Devam etmek istiyor musunuz?');">
                            <input type="hidden" name="action" value="hard_delete_customer">
                            <input type="hidden" name="csrf_token" value="<?= h($csrf) ?>">
                            <input type="hidden" name="customer_id" value="<?= (int)($selectedCustomer['id'] ?? 0) ?>">
                            <input type="text" name="confirm_text" required placeholder="DELETE <?= h($selectedCustomer['username'] ?? '') ?>">
                            <button type="submit" class="danger">Musteriyi Tamamen Sil</button>
                        </form>
                    </div>
                <?php else: ?>
                    <hr>
                    <p class="muted">Secili musteri yok.</p>
                <?php endif; ?>
            </div>
        </div>

    <?php elseif ($tab === 'devices'): ?>
        <?php
        $selectedEffective = $selectedCustomer ? golder_customer_effective_plan($selectedCustomer) : ['max_pc_devices' => 0, 'max_web_sessions' => 0];
        $selectedPcDevices = (int)($selectedCustomerActivity['active_pc_devices'] ?? 0);
        $selectedPcRegistered = (int)($selectedCustomerActivity['registered_pc_devices'] ?? 0);
        $selectedWebDevices = (int)($selectedCustomerActivity['active_web_devices'] ?? 0);
        $selectedWebRegistered = (int)($selectedCustomerActivity['registered_web_devices'] ?? 0);
        $selectedActiveWebSessions = (int)($selectedCustomerActivity['active_web_sessions'] ?? 0);
        ?>
        <div class="grid two">
            <div class="box">
                <?php if ($selectedCustomer): ?>
                    <p class="muted">
                        Musteri: <strong><?= h($selectedCustomer['username'] ?? '-') ?></strong> |
                        Web cihaz: <strong><?= $selectedWebDevices ?></strong> / <?= (int)($selectedEffective['max_web_sessions'] ?? 0) ?> |
                        Aktif web oturum: <strong><?= $selectedActiveWebSessions ?></strong> |
                        PC cihaz: <strong><?= $selectedPcDevices ?></strong> / <?= (int)($selectedEffective['max_pc_devices'] ?? 0) ?><br>
                        Kayitli cihazlar: <?= $selectedPcRegistered ?> PC / <?= $selectedWebRegistered ?> Web
                    </p>
                <?php endif; ?>
                <h2>Aktif Cihazlar</h2>
                <table>
                    <tr><th>ID</th><th>Grup</th><th>Ad</th><th>IP</th><th>Son Gorulme</th><th>Aktif Oturum</th><th>Islem</th></tr>
                    <?php if (!$activeDevices): ?>
                        <tr><td colspan="7" class="muted">Aktif cihaz yok.</td></tr>
                    <?php endif; ?>
                    <?php foreach ($activeDevices as $row): ?>
                        <tr>
                            <td><?= (int)($row['id'] ?? 0) ?></td>
                            <td><?= h($row['device_group'] ?? '-') ?></td>
                            <td>
                                <form method="post" class="row-tools">
                                    <input type="hidden" name="action" value="rename_device">
                                    <input type="hidden" name="csrf_token" value="<?= h($csrf) ?>">
                                    <input type="hidden" name="customer_id" value="<?= (int)$selectedCustomerId ?>">
                                    <input type="hidden" name="device_id" value="<?= (int)($row['id'] ?? 0) ?>">
                                    <input type="text" name="device_name" value="<?= h($row['device_name'] ?? '') ?>">
                                    <button type="submit" class="secondary">Yenile</button>
                                </form>
                            </td>
                            <td><?= h($row['ip_address'] ?? '-') ?></td>
                            <td><?= h($row['last_seen_at'] ?? '-') ?></td>
                            <td><?= (int)($row['active_sessions'] ?? 0) ?></td>
                            <td>
                                <form method="post" class="inline">
                                    <input type="hidden" name="action" value="logout_device_sessions">
                                    <input type="hidden" name="csrf_token" value="<?= h($csrf) ?>">
                                    <input type="hidden" name="customer_id" value="<?= (int)$selectedCustomerId ?>">
                                    <input type="hidden" name="device_id" value="<?= (int)($row['id'] ?? 0) ?>">
                                    <button type="submit" class="warning">Oturum Kapat</button>
                                </form>
                                <form method="post" class="inline" onsubmit="return confirm('Bu cihaz kaydi silinsin mi?');">
                                    <input type="hidden" name="action" value="remove_device">
                                    <input type="hidden" name="csrf_token" value="<?= h($csrf) ?>">
                                    <input type="hidden" name="customer_id" value="<?= (int)$selectedCustomerId ?>">
                                    <input type="hidden" name="device_id" value="<?= (int)($row['id'] ?? 0) ?>">
                                    <button type="submit" class="danger">Kaldir</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </table>
            </div>

            <div class="box">
                <h2>Aktif Web Oturumlari</h2>
                <table>
                    <tr><th>Session</th><th>Cihaz</th><th>IP</th><th>Login</th><th>Last Active</th><th>Durum</th><th></th></tr>
                    <?php if (!$activeSessions): ?>
                        <tr><td colspan="7" class="muted">Aktif web oturumu yok.</td></tr>
                    <?php endif; ?>
                    <?php foreach ($activeSessions as $row): $isClosed = (int)($row['is_active_now'] ?? 0) !== 1; ?>
                        <tr>
                            <td><span class="code"><?= h($row['session_uuid'] ?? '-') ?></span></td>
                            <td><?= h($row['device_name'] ?? '-') ?></td>
                            <td><?= h($row['ip_address'] ?? '-') ?></td>
                            <td><?= h($row['login_at'] ?? '-') ?></td>
                            <td><?= h($row['last_seen_at'] ?? '-') ?></td>
                            <td><?= h($isClosed ? 'Kapali' : 'Aktif') ?></td>
                            <td>
                                <?php if (!$isClosed): ?>
                                    <form method="post" class="inline">
                                        <input type="hidden" name="action" value="logout_web_session">
                                        <input type="hidden" name="csrf_token" value="<?= h($csrf) ?>">
                                        <input type="hidden" name="customer_id" value="<?= (int)$selectedCustomerId ?>">
                                        <input type="hidden" name="session_uuid" value="<?= h($row['session_uuid'] ?? '') ?>">
                                        <button type="submit" class="warning">Kapat</button>
                                    </form>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </table>
            </div>
        </div>

    <?php elseif ($tab === 'payments'): ?>
        <div class="grid two">
            <div class="box">
                <p>
                    <a href="?tab=payments&amp;status=pending">Pending</a>
                    <a href="?tab=payments&amp;status=approved">Approved</a>
                    <a href="?tab=payments&amp;status=rejected">Rejected</a>
                    <a href="?tab=payments&amp;status=all">All</a>
                </p>
                <table>
                    <tr><th>Kod</th><th>Talep Sahibi</th><th>Plan</th><th>Kullanici/Sistem</th><th>M.</th><th>Status</th></tr>
                    <?php foreach ($payments as $row): ?>
                        <tr>
                            <td><a href="?tab=payments&amp;status=<?= h($paymentStatus) ?>&amp;payment_id=<?= h($row['id'] ?? '') ?>"><?= h($row['payment_code'] ?? '') ?></a></td>
                            <td><?= h($row['portal_full_name'] ?: ($row['full_name'] ?? '')) ?><br><span class="muted"><?= h($row['portal_email'] ?? ($row['email'] ?? '-')) ?></span></td>
                            <td>Plan <?= h($row['requested_plan_type'] ?? '-') ?> / <?= (int)($row['requested_pc_devices'] ?? 0) ?>PC / <?= (int)($row['requested_web_sessions'] ?? 0) ?>WEB</td>
                            <td><?= admin_money($row['submitted_amount'] ?? $row['amount'] ?? 0) ?> / <?= admin_money($row['calculated_amount'] ?? $row['amount'] ?? 0) ?> <?= h($row['currency'] ?? 'TRY') ?></td>
                            <td><?php if ((int)($row['amount_mismatch_flag'] ?? 0) === 1): ?><span class="pill-mini">Mismatch</span><?php else: ?>-<?php endif; ?></td>
                            <td><span class="status-pill <?= h((string)($row['status'] ?? '')) ?>"><?= h($row['status'] ?? '-') ?></span></td>
                        </tr>
                    <?php endforeach; ?>
                </table>
            </div>
            <div class="box">
                <?php if ($selectedPayment): ?>
                    <h2><?= h($selectedPayment['payment_code'] ?? '') ?></h2>
                    <p class="muted"><?= h($selectedPayment['full_name'] ?? '-') ?> | <?= h($selectedPayment['status'] ?? '-') ?> | <?= h($selectedPayment['email'] ?? '-') ?> | <?= h($selectedPayment['phone'] ?? '-') ?></p>
                    <p><strong>Portal kullanici:</strong> <?= h($selectedPayment['portal_full_name'] ?? '-') ?> / <?= h($selectedPayment['portal_email'] ?? '-') ?></p>
                    <p><strong>Uygulama girisi:</strong> <?= h($selectedPayment['application_username'] ?? '-') ?><?php if (!empty($selectedPayment['application_username'])): ?> <span class="muted">| Sifre: portal sifresi ile ayni</span><?php endif; ?></p>
                    <p><strong>Provision:</strong> <?= h($selectedPayment['provisioned_at'] ?? '-') ?> | <strong>Mail:</strong> <?= h($selectedPayment['mail_status'] ?? 'none') ?><?php if (!empty($selectedPayment['mail_last_error'])): ?> <span class="muted">| <?= h($selectedPayment['mail_last_error']) ?></span><?php endif; ?></p>
                    <p><strong>Musteri kaydi:</strong> <?= h($selectedPayment['customer_username'] ?? '-') ?><?php if (!empty($selectedPayment['customer_id'])): ?> <span class="muted">#<?= (int)$selectedPayment['customer_id'] ?></span><?php endif; ?></p>
                    <?php if ((int)($selectedPayment['amount_mismatch_flag'] ?? 0) === 1): ?>
                        <div class="warn-box" style="margin:10px 0;">Kullanici/Sistem tutar farki: <?= admin_money($selectedPayment['amount_delta'] ?? 0) ?> <?= h($selectedPayment['currency'] ?? 'TRY') ?></div>
                    <?php endif; ?>
                    <?php if ((string)($selectedPayment['status'] ?? '') === 'pending'): ?>
                        <form method="post" style="margin-bottom:8px;">
                            <input type="hidden" name="action" value="approve_payment">
                            <input type="hidden" name="csrf_token" value="<?= h($csrf) ?>">
                            <input type="hidden" name="payment_request_id" value="<?= h($selectedPayment['id'] ?? '') ?>">
                            <label>Onay Mesaji
                                <textarea name="admin_message">Approved</textarea>
                            </label>
                            <button type="submit">Onayla</button>
                        </form>
                        <form method="post" style="margin-bottom:8px;">
                            <input type="hidden" name="action" value="reject_payment">
                            <input type="hidden" name="csrf_token" value="<?= h($csrf) ?>">
                            <input type="hidden" name="payment_request_id" value="<?= h($selectedPayment['id'] ?? '') ?>">
                            <label>Red Mesaji
                                <textarea name="admin_message">Rejected</textarea>
                            </label>
                            <button type="submit" class="danger">Reddet</button>
                        </form>
                    <?php endif; ?>
                    <form method="post" style="margin-bottom:10px;">
                        <input type="hidden" name="action" value="message_payment">
                        <input type="hidden" name="csrf_token" value="<?= h($csrf) ?>">
                        <input type="hidden" name="payment_request_id" value="<?= h($selectedPayment['id'] ?? '') ?>">
                        <label>Talep Mesaji
                            <textarea name="message" required></textarea>
                        </label>
                        <button type="submit" class="secondary">Mesaj Ekle</button>
                    </form>
                    <h3>Mesaj Gecmisi</h3>
                    <div class="msg-list">
                        <?php foreach ($paymentMessages as $msg): ?>
                            <article class="msg-item">
                                <header><strong><?= h($msg['sender_name'] ?? $msg['sender_type'] ?? '-') ?></strong><span><?= h($msg['created_at'] ?? '-') ?></span></header>
                                <p><?= h($msg['message_text'] ?? '') ?></p>
                            </article>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <p class="muted">Talep seciniz.</p>
                <?php endif; ?>
            </div>
        </div>

    <?php elseif ($tab === 'support'): ?>
        <div class="grid two">
            <div class="box">
                <p>
                    <a href="?tab=support&amp;support_status=open">Open</a>
                    <a href="?tab=support&amp;support_status=closed">Closed</a>
                    <a href="?tab=support&amp;support_status=all">All</a>
                </p>
                <table>
                    <tr><th>Konu</th><th>Kullanici</th><th>Musteri</th><th>Durum</th><th>Guncel</th></tr>
                    <?php foreach ($supportThreads as $row): ?>
                        <tr>
                            <td><a href="?tab=support&amp;support_status=<?= h($supportStatus) ?>&amp;support_thread_id=<?= h($row['id'] ?? '') ?>"><?= h($row['subject'] ?? '-') ?></a></td>
                            <td><?= h($row['portal_full_name'] ?? '-') ?><br><span class="muted"><?= h($row['portal_email'] ?? '-') ?></span></td>
                            <td><?= h($row['customer_username'] ?? '-') ?></td>
                            <td><span class="status-pill <?= h((string)($row['status'] ?? 'open')) ?>"><?= h($row['status'] ?? 'open') ?></span></td>
                            <td><?= h($row['updated_at'] ?? '-') ?></td>
                        </tr>
                    <?php endforeach; ?>
                </table>
            </div>
            <div class="box">
                <?php if ($selectedSupportThread): ?>
                    <h2><?= h($selectedSupportThread['subject'] ?? '-') ?></h2>
                    <p class="muted"><?= h($selectedSupportThread['portal_full_name'] ?? '-') ?> | <?= h($selectedSupportThread['portal_email'] ?? '-') ?> | <?= h($selectedSupportThread['status'] ?? 'open') ?></p>
                    <p><strong>Musteri:</strong> <?= h($selectedSupportThread['customer_username'] ?? '-') ?></p>
                    <p><strong>Assigned admin:</strong> <?= h($selectedSupportThread['assigned_admin'] ?? '-') ?></p>
                    <form method="post" style="margin-bottom:10px;">
                        <input type="hidden" name="action" value="message_support_thread">
                        <input type="hidden" name="csrf_token" value="<?= h($csrf) ?>">
                        <input type="hidden" name="support_thread_id" value="<?= h($selectedSupportThread['id'] ?? '') ?>">
                        <label>Destek Mesaji
                            <textarea name="message" required></textarea>
                        </label>
                        <button type="submit" class="secondary">Mesaj Gonder</button>
                    </form>
                    <form method="post" class="inline">
                        <input type="hidden" name="csrf_token" value="<?= h($csrf) ?>">
                        <input type="hidden" name="support_thread_id" value="<?= h($selectedSupportThread['id'] ?? '') ?>">
                        <?php if ((string)($selectedSupportThread['status'] ?? 'open') === 'closed'): ?>
                            <input type="hidden" name="action" value="reopen_support_thread">
                            <button type="submit">Tekrar Ac</button>
                        <?php else: ?>
                            <input type="hidden" name="action" value="close_support_thread">
                            <button type="submit" class="warning">Kapat</button>
                        <?php endif; ?>
                    </form>
                    <h3>Mesaj Gecmisi</h3>
                    <div class="msg-list">
                        <?php foreach ($supportMessages as $msg): ?>
                            <article class="msg-item">
                                <header><strong><?= h($msg['sender_name'] ?? $msg['sender_type'] ?? '-') ?></strong><span><?= h($msg['created_at'] ?? '-') ?></span></header>
                                <p><?= h($msg['message_text'] ?? '') ?></p>
                            </article>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <p class="muted">Destek sohbeti seciniz.</p>
                <?php endif; ?>
            </div>
        </div>

    <?php elseif ($tab === 'pricing'): ?>
        <div class="grid two">
            <div class="box">
                <h2>Yillik Pricing</h2>
                <p class="muted">Her plan icin baz fiyat, ek PC ve ek web/mobil koltuk fiyatini yonetin. Web/mobil desteklemeyen planlarda web ucreti otomatik sifirlanir.</p>
                <table>
                    <tr><th>Plan</th><th>Base</th><th>Ek PC</th><th>Ek Web</th><th>Currency</th><th></th></tr>
                    <?php foreach (admin_plan_options() as $planCode => $planLabel): $price = $pricingByPlan[$planCode] ?? ['base_price' => '0.00', 'per_pc_price' => '0.00', 'per_web_price' => '0.00', 'currency' => 'TRY']; ?>
                        <tr>
                            <td>
                                <strong><?= h($planLabel) ?></strong><br>
                                <span class="muted"><?= h($planCode) ?></span>
                            </td>
                            <td colspan="5">
                                <form method="post" class="form-grid" style="grid-template-columns:2fr 1fr 1fr 1fr auto; align-items:end;">
                                    <input type="hidden" name="action" value="upsert_pricing_yearly">
                                    <input type="hidden" name="csrf_token" value="<?= h($csrf) ?>">
                                    <input type="hidden" name="plan_type" value="<?= h($planCode) ?>">
                                    <label>Base
                                        <input type="number" step="0.01" min="0" name="base_price" value="<?= h($price['base_price'] ?? '0.00') ?>">
                                    </label>
                                    <label>Ek PC
                                        <input type="number" step="0.01" min="0" name="per_pc_price" value="<?= h($price['per_pc_price'] ?? '0.00') ?>">
                                    </label>
                                    <label>Ek Web
                                        <input type="number" step="0.01" min="0" name="per_web_price" value="<?= h($price['per_web_price'] ?? '0.00') ?>">
                                    </label>
                                    <label>Currency
                                        <input type="text" name="currency" value="<?= h($price['currency'] ?? 'TRY') ?>" maxlength="8">
                                    </label>
                                    <button type="submit">Kaydet</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </table>
            </div>

            <div class="box">
                <h2>Banka Hesaplari</h2>
                <form method="post" class="form-grid">
                    <input type="hidden" name="action" value="add_bank_account">
                    <input type="hidden" name="csrf_token" value="<?= h($csrf) ?>">
                    <label>Hesap Adi
                        <input type="text" name="account_name" required>
                    </label>
                    <label>IBAN
                        <input type="text" name="iban" required>
                    </label>
                    <label>Siralama
                        <input type="number" name="display_order" min="0" value="0">
                    </label>
                    <label>Durum
                        <select name="is_active">
                            <option value="1">Aktif</option>
                            <option value="0">Pasif</option>
                        </select>
                    </label>
                    <div style="grid-column:1/-1">
                        <button type="submit">Banka Hesabi Ekle</button>
                    </div>
                </form>

                <table style="margin-top:12px;">
                    <tr><th>Hesap</th><th>IBAN</th><th>Durum</th><th></th></tr>
                    <?php if (!$banks): ?>
                        <tr><td colspan="4" class="muted">Kayitli banka hesabi yok.</td></tr>
                    <?php endif; ?>
                    <?php foreach ($banks as $bank): ?>
                        <tr>
                            <td><?= h($bank['account_name'] ?? '-') ?></td>
                            <td><span class="code"><?= h($bank['iban'] ?? '-') ?></span></td>
                            <td><?= !empty($bank['is_active']) ? 'Aktif' : 'Pasif' ?></td>
                            <td>
                                <form method="post" class="inline">
                                    <input type="hidden" name="action" value="toggle_bank_account">
                                    <input type="hidden" name="csrf_token" value="<?= h($csrf) ?>">
                                    <input type="hidden" name="bank_id" value="<?= (int)($bank['id'] ?? 0) ?>">
                                    <input type="hidden" name="next_state" value="<?= !empty($bank['is_active']) ? '0' : '1' ?>">
                                    <button type="submit" class="secondary"><?= !empty($bank['is_active']) ? 'Pasif Yap' : 'Aktif Yap' ?></button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </table>
            </div>
        </div>

    <?php elseif ($tab === 'demo'): ?>
        <div class="grid two">
            <div class="box">
                <h2>Manuel Demo Olustur (<?= h(golder_demo_duration_human()) ?>)</h2>
                <p class="muted">Demo talep akisi kapatildi. Bu ekrandan sadece siz manuel <?= h(golder_demo_duration_human_adjective()) ?> demo hesabi acarsiniz.</p>
                <form method="post" class="form-grid">
                    <input type="hidden" name="action" value="create_demo_manual">
                    <input type="hidden" name="csrf_token" value="<?= h($csrf) ?>">
                    <label>Ad Soyad
                        <input type="text" name="full_name" required>
                    </label>
                    <label>E-posta
                        <input type="email" name="email">
                    </label>
                    <label>Telefon
                        <input type="text" name="phone">
                    </label>
                    <label>Demo Sifresi
                        <div class="row-tools">
                            <input type="text" name="password" id="manual_demo_password" placeholder="Bossa otomatik uretilir">
                            <button type="button" class="secondary" data-password-target="manual_demo_password">Oneri Uret</button>
                        </div>
                    </label>
                    <div style="grid-column:1/-1">
                        <button type="submit"><?= h(golder_demo_duration_human_adjective()) ?> Demo Ac</button>
                    </div>
                </form>
                <hr>
                <div class="warn-box">Demo talebi, demo onay akisi ve portal kaynakli demo threadleri artik kullanilmiyor.</div>
            </div>
            <div class="box">
                <h3>Demo Yonetim Notu</h3>
                <p class="muted">Bu panel artik sadece manuel demo acma ve olusan demo lisanslarini izleme icin kullanilir.</p>
            </div>
        </div>

        <div class="box">
            <h3>Demo Lisanslari</h3>
            <table>
                <tr><th>Kod</th><th>Musteri</th><th>Baslangic</th><th>Bitis</th><th>Status</th></tr>
                <?php foreach ($demos as $row): ?>
                    <tr>
                        <td><?= h($row['demo_code'] ?? '-') ?></td>
                        <td><?= h($row['username'] ?? '-') ?><br><span class="muted"><?= h($row['email'] ?? $row['phone_number'] ?? '-') ?></span></td>
                        <td><?= h($row['starts_at'] ?? '-') ?></td>
                        <td><?= h($row['expires_at'] ?? '-') ?></td>
                        <td><span class="status-pill <?= h((string)($row['status'] ?? '')) ?>"><?= h($row['status'] ?? '-') ?></span></td>
                    </tr>
                <?php endforeach; ?>
            </table>
        </div>

    <?php elseif ($tab === 'jobs'): ?>
        <div class="box">
            <h2>Job Runs</h2>
            <p class="muted">cron_demo_expire demo status'unu expired yapar; cron_demo_hard_delete expired + 48 saat sonrasini fiziksel temizler.</p>
            <table>
                <tr><th>Job</th><th>Status</th><th>Baslangic</th><th>Bitis</th><th>Detay</th></tr>
                <?php foreach ($jobs as $row): ?>
                    <tr>
                        <td><?= h($row['job_name'] ?? '-') ?></td>
                        <td><?= h($row['status'] ?? '-') ?></td>
                        <td><?= h($row['started_at'] ?? '-') ?></td>
                        <td><?= h($row['finished_at'] ?? '-') ?></td>
                        <td><details><summary>JSON</summary><pre><?= h((string)($row['details_json'] ?? '{}')) ?></pre></details></td>
                    </tr>
                <?php endforeach; ?>
            </table>
        </div>
    <?php endif; ?>
<?php endif; ?>
</main>

<script>
(function () {
    var planRules = <?= json_encode(admin_plan_ui_rules(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;

    function randomPassword(length) {
        var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#*';
        var out = '';
        var i;
        for (i = 0; i < length; i += 1) {
            out += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        return out;
    }

    Array.prototype.forEach.call(document.querySelectorAll('[data-password-target]'), function (btn) {
        btn.addEventListener('click', function () {
            var id = btn.getAttribute('data-password-target');
            var input = id ? document.getElementById(id) : null;
            if (input) {
                input.value = randomPassword(12);
            }
        });
    });

    Array.prototype.forEach.call(document.querySelectorAll('[data-plan-sync]'), function (form) {
        var plan = form.querySelector('[data-plan-field]');
        var pc = form.querySelector('[data-plan-pc]');
        var web = form.querySelector('[data-plan-web]');
        var desktopExpiry = form.querySelector('[data-plan-desktop-expiry]');
        var syncExpiry = form.querySelector('[data-plan-sync-expiry]');
        var note = form.querySelector('[data-plan-note]');
        if (!plan || !pc || !web) {
            return;
        }

        var toggleDateField = function (field, enabled, required) {
            if (!field) {
                return;
            }
            field.disabled = !enabled;
            field.required = !!required;
            if (!enabled) {
                field.value = '';
            }
        };

        var sync = function () {
            var p = String(plan.value || '<?= h(golder_fallback_plan_type()) ?>');
            var rule = planRules[p] || {};
            var pcVal = Math.max(1, parseInt(pc.value || '1', 10));
            var webVal = parseInt(web.value || '0', 10);
            if (rule.pc_fixed) {
                pcVal = 1;
                pc.disabled = true;
            } else {
                pc.disabled = false;
            }
            if (rule.web_fixed) {
                webVal = 0;
                web.disabled = true;
            } else {
                web.disabled = false;
                if (rule.web_positive && webVal < 1) {
                    webVal = 1;
                }
            }
            toggleDateField(desktopExpiry, !!rule.desktop_enabled, !!rule.desktop_required);
            toggleDateField(syncExpiry, !!rule.sync_enabled, !!rule.sync_required);
            if (note) {
                if (rule.sync_required) {
                    note.value = 'Desktop acik, sync tarihi zorunlu';
                } else if (rule.desktop_required) {
                    note.value = 'Masaustu bitis tarihi zorunlu';
                } else {
                    note.value = 'Omur boyu lokal lisans';
                }
            }
            pc.value = String(pcVal);
            web.value = String(Math.max(0, webVal));
        };

        plan.addEventListener('change', sync);
        pc.addEventListener('input', sync);
        web.addEventListener('input', sync);
        sync();
    });
}());
</script>
</body>
</html>


