<?php
require_once 'config.php';
require_once 'includes/db.php';
require_once 'includes/functions.php';
require_login();

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    die("Access Denied. Admins only.");
}

$site_settings = get_site_settings($pdo);
$success = '';
$error   = '';
$activeTab = $_GET['tab'] ?? 'users';
// Setup Thumbnail Resizing Helper
function resizeAndSaveThumbnail($sourcePath, $destPath, $targetWidth = 1440, $targetHeight = 2960) {
    if (!file_exists($sourcePath)) return false;
    $info = getimagesize($sourcePath);
    if (!$info) return false;
    
    $mime = $info['mime'];
    switch ($mime) {
        case 'image/jpeg': $image = imagecreatefromjpeg($sourcePath); break;
        case 'image/png':  $image = imagecreatefrompng($sourcePath); break;
        case 'image/gif':  $image = imagecreatefromgif($sourcePath); break;
        default: return false;
    }
    if (!$image) return false;
    
    $newImage = imagecreatetruecolor($targetWidth, $targetHeight);
    
    // Preserve transparency for PNGs
    if ($mime == 'image/png' || $mime == 'image/gif') {
        imagealphablending($newImage, false);
        imagesavealpha($newImage, true);
        $transparent = imagecolorallocatealpha($newImage, 255, 255, 255, 127);
        imagefilledrectangle($newImage, 0, 0, $targetWidth, $targetHeight, $transparent);
    }
    
    // Stretch to exact dimensions 1440x2960
    imagecopyresampled($newImage, $image, 0, 0, 0, 0, $targetWidth, $targetHeight, $info[0], $info[1]);
    
    // Force save as PNG format
    $result = imagepng($newImage, $destPath, 9);
    
    imagedestroy($image);
    imagedestroy($newImage);
    
    return $result;
}

// ─── Handle all POST actions ────────────────────────────────────────────────

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

    // ── SITE SETTINGS ──
    if ($action === 'save_site_settings') {
        $site_name     = trim($_POST['site_name'] ?? 'SonicPesa');
        $landing_title = trim($_POST['landing_title'] ?? 'UTAMU');
        $footer_copy   = trim($_POST['footer_copy'] ?? '');
        $footer_made_by = trim($_POST['footer_made_by'] ?? '');
        $allow_registration = isset($_POST['allow_registration']) ? 1 : 0;
        $allow_uploads = isset($_POST['allow_uploads']) ? 1 : 0;
        $allow_withdrawals = isset($_POST['allow_withdrawals']) ? 1 : 0;
        $system_commission = floatval($_POST['system_commission'] ?? 0);
        $min_withdrawal = floatval($_POST['min_withdrawal'] ?? 1000);
        $system_notification = $_POST['system_notification'] ?? '';

        // Handle logo upload
        $site_logo = $site_settings['site_logo'];
        if (!empty($_FILES['site_logo']['name']) && $_FILES['site_logo']['error'] === 0) {
            $ext = strtolower(pathinfo($_FILES['site_logo']['name'], PATHINFO_EXTENSION));
            if (in_array($ext, ['png','jpg','jpeg','gif','svg','webp'])) {
                $newName = 'assets/images/site_logo.' . $ext;
                move_uploaded_file($_FILES['site_logo']['tmp_name'], __DIR__ . '/' . $newName);
                $site_logo = $newName;
            }
        }

        // Handle favicon upload
        $site_favicon = $site_settings['site_favicon'];
        if (!empty($_FILES['site_favicon']['name']) && $_FILES['site_favicon']['error'] === 0) {
            $ext = strtolower(pathinfo($_FILES['site_favicon']['name'], PATHINFO_EXTENSION));
            if (in_array($ext, ['png','ico','jpg','jpeg','svg'])) {
                $newName = 'assets/images/site_favicon.' . $ext;
                move_uploaded_file($_FILES['site_favicon']['tmp_name'], __DIR__ . '/' . $newName);
                $site_favicon = $newName;
            }
        }

        try {
            // Self-healing: add allow_uploads column if missing
            try { $pdo->exec("ALTER TABLE site_settings ADD COLUMN `allow_uploads` tinyint(1) DEFAULT 1 AFTER allow_registration"); } catch (PDOException $e2) {}

            // Self-healing: add allow_withdrawals column if missing
            try { $pdo->exec("ALTER TABLE site_settings ADD COLUMN `allow_withdrawals` tinyint(1) DEFAULT 1 AFTER allow_uploads"); } catch (PDOException $e3) {}

            // Self-healing: add system_notification column if missing
            try { $pdo->exec("ALTER TABLE site_settings ADD COLUMN `system_notification` text DEFAULT NULL AFTER allow_withdrawals"); } catch (PDOException $e4) {}

            $stmt = $pdo->prepare("INSERT INTO site_settings (id, site_name, site_logo, site_favicon, landing_title, footer_copy, footer_made_by, allow_registration, allow_uploads, allow_withdrawals, system_commission, min_withdrawal, system_notification)
                VALUES (1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE site_name=VALUES(site_name), site_logo=VALUES(site_logo),
                    site_favicon=VALUES(site_favicon), landing_title=VALUES(landing_title),
                    footer_copy=VALUES(footer_copy), footer_made_by=VALUES(footer_made_by),
                    allow_registration=VALUES(allow_registration),
                    allow_uploads=VALUES(allow_uploads),
                    allow_withdrawals=VALUES(allow_withdrawals),
                    system_commission=VALUES(system_commission),
                    min_withdrawal=VALUES(min_withdrawal),
                    system_notification=VALUES(system_notification)");
            $stmt->execute([$site_name, $site_logo, $site_favicon, $landing_title, $footer_copy, $footer_made_by, $allow_registration, $allow_uploads, $allow_withdrawals, $system_commission, $min_withdrawal, $system_notification]);
            $site_settings = get_site_settings($pdo); // refresh
            $success = 'Site settings saved successfully!';
        } catch (PDOException $e) {
            $error = 'Failed to save site settings.';
        }
        $activeTab = 'settings';
    }

    // ── PAYMENT API SETTINGS ──
    elseif ($action === 'save_payment_api') {
        $payment_api_url = trim($_POST['payment_api_url'] ?? '');
        $payment_api_key = trim($_POST['payment_api_public_key'] ?? '');

        if (empty($payment_api_url)) {
            $error = 'Payment API URL cannot be empty.';
        } elseif (!filter_var($payment_api_url, FILTER_VALIDATE_URL)) {
            $error = 'Payment API URL is not a valid URL. Example: https://www.pesagate.online/api';
        } else {
            $payment_api_url = rtrim($payment_api_url, '/'); // Normalize trailing slash
            try {
                // Self-healing: ensure columns exist
                try { $pdo->exec("ALTER TABLE site_settings ADD COLUMN `payment_api_url` varchar(255) DEFAULT NULL"); } catch (PDOException $ex) {}
                try { $pdo->exec("ALTER TABLE site_settings ADD COLUMN `payment_api_public_key` varchar(255) DEFAULT NULL"); } catch (PDOException $ex) {}

                // Upsert row id=1
                $pdo->prepare("INSERT INTO site_settings (id, payment_api_url, payment_api_public_key)
                    VALUES (1, ?, ?)
                    ON DUPLICATE KEY UPDATE payment_api_url = VALUES(payment_api_url), payment_api_public_key = VALUES(payment_api_public_key)")
                    ->execute([$payment_api_url, $payment_api_key ?: null]);

                $site_settings = get_site_settings($pdo); // refresh
                $success = 'Payment API settings saved! System will now use: ' . htmlspecialchars($payment_api_url);
            } catch (PDOException $e) {
                $error = 'Failed to save Payment API settings: ' . $e->getMessage();
            }
        }
        $activeTab = 'settings';
    }

    // ── SYSTEM NOTIFICATION ──
    elseif ($action === 'save_system_notification') {

        $system_notification = $_POST['system_notification'] ?? '';
        $notification_type = in_array($_POST['notification_type'] ?? '', ['primary','info','success','warning','danger']) ? $_POST['notification_type'] : 'primary';
        if (!empty($system_notification)) {
            try {
                // Self-healing: Ensure table exists with type column
                $pdo->exec("CREATE TABLE IF NOT EXISTS `system_notifications` (
                    `id` int(11) NOT NULL AUTO_INCREMENT,
                    `message` text NOT NULL,
                    `type` varchar(20) DEFAULT 'primary',
                    `is_active` tinyint(1) DEFAULT 1,
                    `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
                    PRIMARY KEY (`id`)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
                // Add type column if missing (upgrade existing installs)
                try { $pdo->exec("ALTER TABLE system_notifications ADD COLUMN `type` varchar(20) DEFAULT 'primary' AFTER message"); } catch (PDOException $e2) {}

                $stmt = $pdo->prepare("INSERT INTO system_notifications (message, type, is_active) VALUES (?, ?, 1)");
                $stmt->execute([$system_notification, $notification_type]);
                $success = 'System notification posted!';
            } catch (PDOException $e) {
                $error = 'Failed to save notification: ' . $e->getMessage();
            }
        }
        $activeTab = 'settings';
    }

    // ── DELETE NOTIFICATION ──
    elseif ($action === 'delete_notification') {
        $nid = (int)($_POST['notification_id'] ?? 0);
        try {
            $pdo->prepare("DELETE FROM system_notifications WHERE id = ?")->execute([$nid]);
            $success = 'Notification removed.';
        } catch (PDOException $e) {
            $error = 'Delete failed.';
        }
        $activeTab = 'settings';
    }

    // ── EDIT NOTIFICATION ──
    elseif ($action === 'edit_notification') {
        $nid  = (int)($_POST['notification_id'] ?? 0);
        $msg  = trim($_POST['edit_message'] ?? '');
        $type = in_array($_POST['edit_type'] ?? '', ['primary','info','success','warning','danger']) ? $_POST['edit_type'] : 'primary';
        if ($nid && !empty($msg)) {
            try {
                $pdo->prepare("UPDATE system_notifications SET message = ?, type = ? WHERE id = ?")->execute([$msg, $type, $nid]);
                $success = 'Notification updated!';
            } catch (PDOException $e) {
                $error = 'Update failed: ' . $e->getMessage();
            }
        }
        $activeTab = 'settings';
    }

    // ── REPOST NOTIFICATION ──
    elseif ($action === 'repost_notification') {
        $nid = (int)($_POST['notification_id'] ?? 0);
        try {
            $row = $pdo->prepare("SELECT message, type FROM system_notifications WHERE id = ?");
            $row->execute([$nid]);
            $orig = $row->fetch();
            if ($orig) {
                $pdo->prepare("INSERT INTO system_notifications (message, type, is_active) VALUES (?, ?, 1)")
                    ->execute([$orig['message'], $orig['type']]);
                $success = 'Notification reposted as the latest!';
            }
        } catch (PDOException $e) {
            $error = 'Repost failed: ' . $e->getMessage();
        }
        $activeTab = 'settings';
    }

    // ── CLEAR ALL NOTIFICATIONS ──
    elseif ($action === 'clear_all_notifications') {
        try {
            $pdo->exec("DELETE FROM system_notifications");
            $success = 'All notifications cleared.';
        } catch (PDOException $e) {
            $error = 'Failed to clear notifications.';
        }
        $activeTab = 'settings';
    }

    // ── ADD / EDIT USER ──
    elseif ($action === 'save_user') {
        $uid   = (int)($_POST['user_id'] ?? 0);
        $name  = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $role  = $_POST['role'] === 'admin' ? 'admin' : 'user';
        $pw    = trim($_POST['password'] ?? '');

        if (empty($name) || empty($email)) {
            $error = 'Name and email are required.';
        } else {
            try {
                if ($uid > 0) {
                    // Edit
                    if (!empty($pw)) {
                        $hash = password_hash($pw, PASSWORD_DEFAULT);
                        $stmt = $pdo->prepare("UPDATE users SET name=?, email=?, role=?, password=? WHERE id=?");
                        $stmt->execute([$name, $email, $role, $hash, $uid]);
                    } else {
                        $stmt = $pdo->prepare("UPDATE users SET name=?, email=?, role=? WHERE id=?");
                        $stmt->execute([$name, $email, $role, $uid]);
                    }
                    $success = 'User updated.';
                } else {
                    // Add
                    if (empty($pw)) { $error = 'Password is required for new users.'; }
                    else {
                        $hash  = password_hash($pw, PASSWORD_DEFAULT);
                        $token = bin2hex(random_bytes(32));
                        $stmt  = $pdo->prepare("INSERT INTO users (name, email, password, role, webhook_token) VALUES (?,?,?,?,?)");
                        $stmt->execute([$name, $email, $hash, $role, $token]);
                        $success = 'User created.';
                    }
                }
            } catch (PDOException $e) {
                $error = 'Database error: ' . $e->getMessage();
            }
        }
        $activeTab = 'users';
    }

    // ── DELETE USER ──
    elseif ($action === 'delete_user') {
        $uid = (int)($_POST['user_id'] ?? 0);
        if ($uid === (int)$_SESSION['user_id']) {
            $error = 'You cannot delete your own account.';
        } else {
            try {
                $pdo->prepare("DELETE FROM users WHERE id=?")->execute([$uid]);
                $success = 'User deleted.';
            } catch (PDOException $e) { $error = 'Delete failed.'; }
        }
        $activeTab = 'users';
    }

    // ── ADD / EDIT TEMPLATE ENTRY ──
    elseif ($action === 'save_template') {
        $tid   = (int)($_POST['tpl_id'] ?? 0);
        $tname = trim($_POST['tname'] ?? '');
        $tslug = trim($_POST['tslug'] ?? '');
        if (empty($tname) || empty($tslug)) {
            $error = 'Template name and slug are required.';
        } else {
            try {
                // Handle optional file uploads
                $phpFile = $_FILES['edit_tpl_php'] ?? null;
                $pngFile = $_FILES['edit_tpl_png'] ?? null;
                
                $uploadError = '';
                if ($phpFile && $phpFile['error'] === 0) {
                    $phpExt = strtolower(pathinfo($phpFile['name'], PATHINFO_EXTENSION));
                    if ($phpExt !== 'php') {
                        $uploadError .= "Invalid PHP format. ";
                    } else {
                        $phpDest = __DIR__ . "/templates/{$tslug}.php";
                        move_uploaded_file($phpFile['tmp_name'], $phpDest);
                        @chmod($phpDest, 0644);
                    }
                }
                
                if ($pngFile && $pngFile['error'] === 0) {
                    $pngExt = strtolower(pathinfo($pngFile['name'], PATHINFO_EXTENSION));
                    if (!in_array($pngExt, ['png', 'jpg', 'jpeg'])) {
                        $uploadError .= "Invalid image format. ";
                    } else {
                        $pngDest = __DIR__ . "/assets/landing/{$tslug}.png";
                        if (!resizeAndSaveThumbnail($pngFile['tmp_name'], $pngDest)) {
                            $uploadError .= "Failed to resize & save image to 1440x2960. ";
                        } else {
                            @chmod($pngDest, 0644);
                        }
                    }
                }

                if ($tid > 0) {
                    $pdo->prepare("UPDATE templates SET name=?, slug=? WHERE id=?")->execute([$tname, $tslug, $tid]);
                    $success = 'Template updated successfully.' . ($uploadError ? " Notice: $uploadError" : '');
                } else {
                    $pdo->prepare("INSERT INTO templates (name, slug) VALUES (?,?)")->execute([$tname, $tslug]);
                    $success = 'Template added successfully.' . ($uploadError ? " Notice: $uploadError" : '');
                }
            } catch (PDOException $e) { $error = 'Template save failed: ' . $e->getMessage(); }
        }
        $activeTab = 'templates';
    }

    // ── INSTALL NEW TEMPLATE ──
    elseif ($action === 'install_template') {
        try {
            // Find highest template number (slugs like landing1, landing2... etc)
            $stmt = $pdo->query("SELECT slug FROM templates WHERE slug LIKE 'landing%'");
            $maxNum = 8; // base minimum is landing8
            while($row = $stmt->fetch()) {
                $num = (int)str_replace('landing', '', $row['slug']);
                if($num > $maxNum) {
                    $maxNum = $num;
                }
            }
            $nextNum = $maxNum + 1;
            $newSlug = "landing" . $nextNum;
            $newName = "Model V" . $nextNum;
            
            $phpFile = $_FILES['tpl_php'] ?? null;
            $pngFile = $_FILES['tpl_png'] ?? null;
            
            if (!$phpFile || $phpFile['error'] !== 0 || !$pngFile || $pngFile['error'] !== 0) {
                $error = "Both PHP and PNG files are required.";
            } else {
                $phpExt = strtolower(pathinfo($phpFile['name'], PATHINFO_EXTENSION));
                $pngExt = strtolower(pathinfo($pngFile['name'], PATHINFO_EXTENSION));
                
                if ($phpExt !== 'php' || !in_array($pngExt, ['png', 'jpg', 'jpeg'])) {
                    $error = "Invalid file formats. Must be .php and an image (.png/.jpg).";
                } else {
                    $phpDest = __DIR__ . "/templates/{$newSlug}.php";
                    $pngDest = __DIR__ . "/assets/landing/{$newSlug}.png"; // Force png extension to match settings.php
                    
                    if (move_uploaded_file($phpFile['tmp_name'], $phpDest)) {
                        if (resizeAndSaveThumbnail($pngFile['tmp_name'], $pngDest)) {
                            // Fix permissions for shared hosting to prevent HTTP 500 errors
                            chmod($phpDest, 0644);
                            chmod($pngDest, 0644);
                            
                            $pdo->prepare("INSERT INTO templates (name, slug) VALUES (?,?)")->execute([$newName, $newSlug]);
                            $success = "Template {$newName} installed successfully and image resized to 1440x2960!";
                        } else {
                            $error = "Failed to process and resize the thumbnail image to 1440x2960.";
                            // Clean up uploaded php if image failed
                            @unlink($phpDest);
                        }
                    } else {
                        $error = "Failed to upload PHP file to the server. Check permissions.";
                    }
                }
            }
        } catch (PDOException $e) {
            $error = "Database error during installation: " . $e->getMessage();
        }
        $activeTab = 'templates';
    }

    // ── ADD / EDIT LINK (DOMAIN) ──
    elseif ($action === 'save_link') {
        $link_id = (int)($_POST['domain_id'] ?? 0);
        $user_id = (int)($_POST['owner_id'] ?? $_SESSION['user_id']); // Default to admin if not specified
        $dname   = trim($_POST['domain_name'] ?? '');
        $status  = $_POST['status'] ?? 'active';

        if (empty($dname)) {
            $error = 'Domain name is required.';
        } else {
            // Basic sanitization
            $dname = strtolower(preg_replace('/[^a-z0-9.-]/i', '', $dname));
            try {
                if ($link_id > 0) {
                    $stmt = $pdo->prepare("UPDATE user_domains SET user_id=?, domain_name=?, status=? WHERE id=?");
                    $stmt->execute([$user_id, $dname, $status, $link_id]);
                    $success = 'Domain updated.';
                } else {
                    // Check for duplicate
                    $check = $pdo->prepare("SELECT COUNT(*) FROM user_domains WHERE domain_name=?");
                    $check->execute([$dname]);
                    if ($check->fetchColumn() > 0) {
                        $error = 'Domain already registered.';
                    } else {
                        $stmt = $pdo->prepare("INSERT INTO user_domains (user_id, domain_name, status) VALUES (?,?,?)");
                        $stmt->execute([$user_id, $dname, $status]);
                        $success = 'Domain registered.';
                    }
                }
            } catch (PDOException $e) { $error = 'DB error: ' . $e->getMessage(); }
        }
        $activeTab = 'links';
    }

    // ── DELETE TEMPLATE ──
    elseif ($action === 'delete_template') {
        $tid = (int)($_POST['tpl_id'] ?? 0);
        try {
            $pdo->prepare("DELETE FROM templates WHERE id=?")->execute([$tid]);
            $success = 'Template deleted.';
        } catch (PDOException $e) { $error = 'Delete failed.'; }
        $activeTab = 'templates';
    }

    // ── DELETE LINK (domain) ──
    elseif ($action === 'delete_link') {
        $lid = (int)($_POST['link_id'] ?? 0);
        try {
            $pdo->prepare("DELETE FROM user_domains WHERE id=?")->execute([$lid]);
            $success = 'Link deleted.';
        } catch (PDOException $e) { $error = 'Delete failed.'; }
        $activeTab = 'links';
    }

    // ── ROOT DOMAIN ACTIONS ──
    elseif ($action === 'save_root_domain') {
        $rid    = (int)($_POST['root_id'] ?? 0);
        $dname  = strtolower(trim($_POST['domain_name'] ?? ''));
        $active = isset($_POST['is_active']) ? 1 : 0;

        if (empty($dname)) {
            $error = 'Domain name is required.';
        } else {
            try {
                if ($rid > 0) {
                    $pdo->prepare("UPDATE system_root_domains SET domain_name=?, is_active=? WHERE id=?")->execute([$dname, $active, $rid]);
                    $success = 'Root domain updated.';
                } else {
                    $pdo->prepare("INSERT INTO system_root_domains (domain_name, is_active) VALUES (?,?)")->execute([$dname, $active]);
                    $success = 'Root domain added.';
                }
            } catch (PDOException $e) { $error = 'Save failed: ' . $e->getMessage(); }
        }
        $activeTab = 'root_domains';
    }
    elseif ($action === 'delete_root_domain') {
        $rid = (int)($_POST['root_id'] ?? 0);
        try {
            $pdo->prepare("DELETE FROM system_root_domains WHERE id=?")->execute([$rid]);
            $success = 'Root domain deleted.';
        } catch (PDOException $e) { $error = 'Delete failed.'; }
        $activeTab = 'root_domains';
    }
}

// ─── Fetch data for tabs ─────────────────────────────────────────────────────

// Metrics for scorecards
try {
    $totalUsers = $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
    $totalLinks = $pdo->query("SELECT COUNT(*) FROM user_domains")->fetchColumn();
    $totalEarned = $pdo->query("SELECT SUM(amount) FROM transactions WHERE status = 'completed'")->fetchColumn() ?: 0;
    $totalTemplates = 8 + (int)$pdo->query("SELECT COUNT(*) FROM templates")->fetchColumn();
} catch (PDOException $e) { $totalUsers = $totalLinks = $totalEarned = $totalTemplates = 0; }

// Users
try {
    $users = $pdo->query("
        SELECT u.id, u.name, u.email, u.role, u.created_at,
               (SELECT COUNT(*) FROM videos WHERE user_id = u.id) AS total_videos
        FROM users u ORDER BY u.created_at DESC
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { $users = []; }

// Links / Domains
try {
    $links = $pdo->query("
        SELECT d.*, u.name AS user_name, u.email AS user_email
        FROM user_domains d
        LEFT JOIN users u ON u.id = d.user_id
        ORDER BY d.created_at DESC
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { $links = []; }

// Templates (soft list of landing1-7 + DB-managed extras)
$builtinTemplates = [];
for ($i = 1; $i <= 8; $i++) {
    $builtinTemplates[] = ['slug' => "landing$i", 'name' => "Landing Page $i (Built-in)"];
}
try {
    $dbTemplates = $pdo->query("SELECT * FROM templates ORDER BY id")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    // Table might not exist yet — create it
    try {
        $pdo->exec("CREATE TABLE IF NOT EXISTS templates (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, slug VARCHAR(100) NOT NULL UNIQUE, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");
    } catch (PDOException $ex) {}
    $dbTemplates = [];
}

// Root Domains
try {
    $rootDomains = $pdo->query("SELECT * FROM system_root_domains ORDER BY domain_name ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { $rootDomains = []; }

// Notifications History
try {
    // Self-healing check on fetch as well
    $pdo->exec("CREATE TABLE IF NOT EXISTS `system_notifications` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `message` text NOT NULL,
        `is_active` tinyint(1) DEFAULT 1,
        `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
    
    $notificationsHistory = $pdo->query("SELECT * FROM system_notifications ORDER BY created_at DESC LIMIT 10")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { $notificationsHistory = []; }

// ... existing code ...
?>
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<?php include 'includes/head.php'; ?>
<style>
    .admin-metrics-card {
        background: white;
        border-radius: 16px;
        padding: 24px;
        border: 1px solid rgba(0,0,0,0.04);
        box-shadow: 0 4px 20px rgba(0,0,0,0.03);
        transition: transform 0.3s ease;
    }
    .admin-metrics-card:hover { transform: translateY(-5px); }
    .metric-icon { 
        width: 48px; height: 48px; border-radius: 12px; 
        display: flex; align-items: center; justify-content: center; font-size: 1.5rem;
    }
    .sophisticated-tabs .nav-link {
        border: none;
        padding: 12px 24px;
        border-radius: 12px;
        font-weight: 600;
        color: var(--text-secondary-light);
        transition: all 0.3s ease;
    }
    .sophisticated-tabs .nav-link.active {
        background: var(--primary-600);
        color: white !important;
        box-shadow: 0 4px 15px rgba(72, 127, 255, 0.3);
    }
    .sophisticated-card {
        background: white;
        border: 1px solid rgba(0,0,0,0.05);
        border-radius: 16px;
        box-shadow: 0 10px 30px rgba(0,0,0,0.03);
        overflow: hidden;
    }
    .glass-header {
        background: rgba(255,255,255,0.8) !important;
        backdrop-filter: blur(10px);
        border-bottom: 1px solid rgba(0,0,0,0.05) !important;
    }
    .btn-premium {
        border-radius: 10px;
        padding: 8px 20px;
        font-weight: 600;
        transition: all 0.3s ease;
    }
</style>
<body>
<?php include 'includes/sidebar.php'; ?>
<main class="dashboard-main">
    <?php include 'includes/header.php'; ?>
    <div class="dashboard-main-body">
        <!-- Breadcrumb & Header -->
        <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-24">
            <div>
                <h4 class="fw-bold mb-0">Super Admin Panel</h4>
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb mb-0 text-sm mt-4">
                        <li class="breadcrumb-item"><a href="dashboard.php" class="text-secondary-light">Dashboard</a></li>
                        <li class="breadcrumb-item active text-primary-600 fw-bold">System Administration</li>
                    </ol>
                </nav>
            </div>
            <div class="d-flex align-items-center gap-12">
                <span class="badge bg-primary-100 text-primary-600 px-16 py-8 radius-20 fw-bold">
                    <iconify-icon icon="solar:shield-check-bold-duotone" class="me-8"></iconify-icon> ROOT ADMIN ACCESS
                </span>
            </div>
        </div>

        <!-- Metrics Overview -->
        <div class="row gy-4 mb-32">
            <div class="col-xxl-3 col-sm-6">
                <div class="admin-metrics-card border-start border-4 border-primary-600">
                    <div class="d-flex align-items-center gap-16">
                        <div class="metric-icon bg-primary-100 text-primary-600">
                            <iconify-icon icon="solar:users-group-rounded-bold-duotone"></iconify-icon>
                        </div>
                        <div>
                            <p class="text-secondary-light text-xs fw-bold text-uppercase mb-4 mt-0">Total Users</p>
                            <h3 class="mb-0 fw-bold"><?= number_format($totalUsers) ?></h3>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xxl-3 col-sm-6">
                <div class="admin-metrics-card border-start border-4 border-success-main">
                    <div class="d-flex align-items-center gap-16">
                        <div class="metric-icon bg-success-focus text-success-main">
                            <iconify-icon icon="solar:round-alt-arrow-up-bold-duotone"></iconify-icon>
                        </div>
                        <div>
                            <p class="text-secondary-light text-xs fw-bold text-uppercase mb-4 mt-0">Platform Earnings</p>
                            <h3 class="mb-0 fw-bold">TSH <?= number_format($totalEarned) ?></h3>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xxl-3 col-sm-6">
                <div class="admin-metrics-card border-start border-4 border-warning-main">
                    <div class="d-flex align-items-center gap-16">
                        <div class="metric-icon bg-warning-focus text-warning-main">
                            <iconify-icon icon="solar:link-bold-duotone"></iconify-icon>
                        </div>
                        <div>
                            <p class="text-secondary-light text-xs fw-bold text-uppercase mb-4 mt-0">Total Domains</p>
                            <h3 class="mb-0 fw-bold"><?= number_format($totalLinks) ?></h3>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xxl-3 col-sm-6">
                <div class="admin-metrics-card border-start border-4 border-info-main">
                    <div class="d-flex align-items-center gap-16">
                        <div class="metric-icon bg-info-focus text-info-main">
                            <iconify-icon icon="solar:layout-bold-duotone"></iconify-icon>
                        </div>
                        <div>
                            <p class="text-secondary-light text-xs fw-bold text-uppercase mb-4 mt-0">Active Templates</p>
                            <h3 class="mb-0 fw-bold"><?= number_format($totalTemplates) ?></h3>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Alerts -->
        <?php if ($success): ?>
        <div class="alert alert-success border-0 bg-success-focus text-success-main alert-dismissible fade show radius-12 mb-24 p-16" role="alert">
            <div class="d-flex align-items-center gap-12">
                <iconify-icon icon="solar:check-circle-bold" class="text-xl"></iconify-icon>
                <div class="fw-bold"><?= htmlspecialchars($success) ?></div>
            </div>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>
        <?php if ($error): ?>
        <div class="alert alert-danger border-0 bg-danger-focus text-danger-main alert-dismissible fade show radius-12 mb-24 p-16" role="alert">
            <div class="d-flex align-items-center gap-12">
                <iconify-icon icon="solar:danger-bold" class="text-xl"></iconify-icon>
                <div class="fw-bold"><?= htmlspecialchars($error) ?></div>
            </div>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>

        <!-- Nav Tabs -->
        <ul class="nav nav-pills mb-32 gap-3 sophisticated-tabs" id="adminTabs">
            <li class="nav-item">
                <a class="nav-link <?= $activeTab==='users'?'active':'' ?>" href="superadmin.php?tab=users">
                    <iconify-icon icon="solar:users-group-rounded-linear" class="me-8"></iconify-icon> User Management
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link <?= $activeTab==='links'?'active':'' ?>" href="superadmin.php?tab=links">
                    <iconify-icon icon="solar:link-broken-linear" class="me-8"></iconify-icon> Global Links
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link <?= $activeTab==='templates'?'active':'' ?>" href="superadmin.php?tab=templates">
                    <iconify-icon icon="solar:mirror-linear" class="me-8"></iconify-icon> Templates
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link <?= $activeTab==='settings'?'active':'' ?>" href="superadmin.php?tab=settings">
                    <iconify-icon icon="solar:settings-linear" class="me-8"></iconify-icon> Site Settings
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link <?= $activeTab==='root_domains'?'active':'' ?>" href="superadmin.php?tab=root_domains">
                    <iconify-icon icon="solar:server-bold-duotone" class="me-8"></iconify-icon> System Domains
                </a>
            </li>
        </ul>

        <!-- ══════════════ USERS TAB ══════════════ -->
        <?php if ($activeTab === 'users'): ?>
        <div class="row gy-4">
            <!-- User List -->
            <div class="col-12">
                <div class="sophisticated-card">
                    <div class="card-header glass-header py-20 px-24 d-flex align-items-center justify-content-between">
                        <h6 class="mb-0 fw-bold">Registered Platform Users</h6>
                        <button class="btn btn-primary btn-premium d-flex align-items-center gap-8" data-bs-toggle="modal" data-bs-target="#userModal" onclick="clearUserForm()">
                            <iconify-icon icon="solar:user-plus-bold-duotone" class="text-xl"></iconify-icon>
                            Add New User
                        </button>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table bordered-table mb-0 stripe">
                                <thead>
                                    <tr class="bg-light">
                                        <th class="px-24 py-16 border-0 text-xs fw-bold text-uppercase text-secondary-light">Influencer</th>
                                        <th class="px-24 py-16 border-0 text-xs fw-bold text-uppercase text-secondary-light">System Role</th>
                                        <th class="px-24 py-16 border-0 text-xs fw-bold text-uppercase text-secondary-light">Assets</th>
                                        <th class="px-24 py-16 border-0 text-xs fw-bold text-uppercase text-secondary-light">Join Date</th>
                                        <th class="px-24 py-16 border-0 text-xs fw-bold text-uppercase text-secondary-light text-end">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                <?php foreach ($users as $u): ?>
                                <tr>
                                    <td class="px-24 py-16 border-0">
                                        <div class="d-flex align-items-center gap-12">
                                            <div class="user-avatar-sm" style="background: var(--primary-100); color: var(--primary-600); width: 36px; height: 36px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-weight: 700;">
                                                <?= strtoupper(substr($u['name'], 0, 1)) ?>
                                            </div>
                                            <div>
                                                <div class="fw-bold text-dark text-sm"><?= htmlspecialchars($u['name']) ?></div>
                                                <div class="text-xxs text-secondary-light fw-medium"><?= htmlspecialchars($u['email']) ?></div>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="px-24 py-16 border-0">
                                        <?php if($u['role']==='admin'): ?>
                                            <span class="badge bg-warning-focus text-warning-main px-12 py-4 radius-8 fw-bold text-xxs">ADMINISTRATOR</span>
                                        <?php else: ?>
                                            <span class="badge bg-primary-50 text-primary-600 px-12 py-4 radius-8 fw-bold text-xxs">STANDARD USER</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="px-24 py-16 border-0">
                                        <span class="text-sm fw-bold text-secondary-light"><iconify-icon icon="solar:videocamera-record-bold-duotone" class="me-4"></iconify-icon> <?= number_format($u['total_videos']) ?></span>
                                    </td>
                                    <td class="px-24 py-16 border-0 text-sm fw-medium text-secondary-light"><?= date('M d, Y', strtotime($u['created_at'])) ?></td>
                                    <td class="px-24 py-16 border-0 text-end">
                                        <div class="d-flex align-items-center justify-content-end gap-8">
                                            <a href="impersonate.php?id=<?= $u['id'] ?>" class="btn btn-sm btn-outline-info radius-8" title="Impersonate User">
                                                <iconify-icon icon="solar:user-speak-bold-duotone"></iconify-icon>
                                            </a>
                                            <button class="btn btn-sm btn-outline-primary radius-8" onclick='editUser(<?= json_encode($u) ?>)' data-bs-toggle="modal" data-bs-target="#userModal">
                                                <iconify-icon icon="solar:pen-new-square-bold-duotone"></iconify-icon>
                                            </button>
                                            <?php if ($u['id'] !== $_SESSION['user_id']): ?>
                                            <form method="POST" style="display:inline" onsubmit="return confirm('Delete user <?= htmlspecialchars(addslashes($u['name'])) ?>?')">
                                                <input type="hidden" name="action" value="delete_user">
                                                <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                                                <button class="btn btn-sm btn-outline-danger radius-8"><iconify-icon icon="solar:trash-bin-trash-bold-duotone"></iconify-icon></button>
                                            </form>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <?php elseif ($activeTab === 'links'): ?>
        <div class="row gy-4">
            <!-- Existing Links/User Domains Table -->
            <div class="col-lg-12">
                <div class="sophisticated-card">
                    <div class="card-header glass-header py-20 px-24 d-flex align-items-center justify-content-between">
                        <div>
                            <h6 class="mb-0 fw-bold">Active User Domains & Links</h6>
                            <p class="text-xxs text-secondary-light fw-bold text-uppercase ls-1 mt-4 mb-0">Total Tracked: <?= count($links) ?></p>
                        </div>
                        <button class="btn btn-primary btn-premium d-flex align-items-center gap-8" data-bs-toggle="modal" data-bs-target="#linkModal" onclick="clearLinkForm()">
                            <iconify-icon icon="solar:global-bold-duotone" class="text-xl"></iconify-icon>
                            Add Global Domain
                        </button>
                    </div>
                    <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table bordered-table mb-0 stripe">
                        <thead>
                            <tr class="bg-light">
                                <th class="px-24 py-16 border-0 text-xs fw-bold text-uppercase text-secondary-light">System Owner</th>
                                <th class="px-24 py-16 border-0 text-xs fw-bold text-uppercase text-secondary-light">Domain URL</th>
                                <th class="px-24 py-16 border-0 text-xs fw-bold text-uppercase text-secondary-light">Current Status</th>
                                <th class="px-24 py-16 border-0 text-xs fw-bold text-uppercase text-secondary-light">Created At</th>
                                <th class="px-24 py-16 border-0 text-xs fw-bold text-uppercase text-secondary-light text-end">Management</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($links as $lk): ?>
                        <tr>
                            <td class="px-24 py-16 border-0">
                                <div class="fw-bold text-dark text-sm"><?= htmlspecialchars($lk['user_name'] ?? 'System') ?></div>
                                <div class="text-xxs text-secondary-light fw-medium"><?= htmlspecialchars($lk['user_email'] ?? 'internal@system') ?></div>
                            </td>
                            <td class="px-24 py-16 border-0">
                                <a href="https://<?= htmlspecialchars($lk['domain_name']) ?>" target="_blank" class="text-primary-600 fw-bold text-sm d-flex align-items-center gap-4">
                                    <iconify-icon icon="solar:global-bold-duotone"></iconify-icon>
                                    <?= htmlspecialchars($lk['domain_name']) ?>
                                </a>
                            </td>
                            <td class="px-24 py-16 border-0">
                                <?php $s = $lk['status'] ?? 'pending'; ?>
                                <span class="badge radius-8 px-12 py-4 fw-bold text-xxs <?= $s==='verified'||$s==='active' ? 'bg-success-focus text-success-main' : 'bg-warning-focus text-warning-main' ?>">
                                    <?= strtoupper($s) ?>
                                </span>
                            </td>
                            <td class="px-24 py-16 border-0 text-sm fw-medium text-secondary-light"><?= date('M d, Y', strtotime($lk['created_at'])) ?></td>
                            <td class="px-24 py-16 border-0 text-end">
                                <div class="d-flex align-items-center justify-content-end gap-8">
                                    <button class="btn btn-sm btn-outline-primary radius-8" onclick='editLink(<?= json_encode($lk) ?>)' data-bs-toggle="modal" data-bs-target="#linkModal">
                                        <iconify-icon icon="solar:pen-new-square-bold-duotone" class="text-lg"></iconify-icon>
                                    </button>
                                    <form method="POST" onsubmit="return confirm('Delete this link?')" style="display:inline">
                                        <input type="hidden" name="action" value="delete_link">
                                        <input type="hidden" name="link_id" value="<?= $lk['id'] ?>">
                                        <button class="btn btn-sm btn-outline-danger radius-8"><iconify-icon icon="solar:trash-bin-minimalistic-bold-duotone" class="text-lg"></iconify-icon></button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- ══════════════ TEMPLATES TAB ══════════════ -->
        <?php elseif ($activeTab === 'templates'): ?>
        <div class="row gy-4">
            <!-- Built-in templates list -->
            <div class="col-lg-7">
                <div class="sophisticated-card">
                    <div class="card-header glass-header py-20 px-24 d-flex align-items-center justify-content-between">
                        <h6 class="mb-0 fw-bold">Built-in Viral Landing Templates</h6>
                        <span class="badge bg-primary-50 text-primary-600 px-12 py-4 radius-8 fw-bold text-xxs">CORE SYSTEM</span>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table bordered-table mb-0">
                                <thead>
                                    <tr class="bg-light">
                                        <th class="px-24 py-16 border-0 text-xs fw-bold text-uppercase text-secondary-light">Template Identity</th>
                                        <th class="px-24 py-16 border-0 text-xs fw-bold text-uppercase text-secondary-light">File Handle</th>
                                        <th class="px-24 py-16 border-0 text-xs fw-bold text-uppercase text-secondary-light text-end">Access</th>
                                    </tr>
                                </thead>
                                <tbody>
                                <?php foreach ($builtinTemplates as $t): ?>
                                <tr>
                                    <td class="px-24 py-16 border-0">
                                        <div class="fw-bold text-dark text-sm"><?= htmlspecialchars($t['name']) ?></div>
                                    </td>
                                    <td class="px-24 py-16 border-0">
                                        <code class="text-primary-600 fw-bold bg-primary-50 px-8 py-4 radius-4"><?= htmlspecialchars($t['slug']) ?>.php</code>
                                    </td>
                                    <td class="px-24 py-16 border-0 text-end">
                                        <span class="text-success-main font-bold"><iconify-icon icon="solar:check-read-bold-duotone"></iconify-icon> Ready</span>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Custom template management -->
            <div class="col-lg-5">
                <div class="sophisticated-card">
                    <div class="card-header glass-header py-20 px-24 d-flex align-items-center justify-content-between">
                        <div class="d-flex gap-8">
                            <button class="btn btn-outline-primary btn-premium btn-sm" data-bs-toggle="modal" data-bs-target="#tplModal" onclick="clearTplForm()">
                                <iconify-icon icon="solar:add-circle-bold-duotone" class="me-4 text-lg"></iconify-icon> Manual Add
                            </button>
                            <button class="btn btn-primary btn-premium btn-sm" data-bs-toggle="modal" data-bs-target="#installerModal">
                                <iconify-icon icon="solar:upload-minimalistic-bold-duotone" class="me-4 text-lg"></iconify-icon> Install New
                            </button>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table bordered-table mb-0">
                                <thead>
                                    <tr class="bg-light">
                                        <th class="px-24 py-16 border-0 text-xs fw-bold text-uppercase text-secondary-light">Name</th>
                                        <th class="px-24 py-16 border-0 text-xs fw-bold text-uppercase text-secondary-light text-end">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                <?php foreach ($dbTemplates as $t): ?>
                                <tr>
                                    <td class="px-24 py-16 border-0">
                                        <div class="fw-bold text-dark text-sm"><?= htmlspecialchars($t['name']) ?></div>
                                        <div class="text-xxs text-secondary-light mt-2 fw-medium">Slug: <?= htmlspecialchars($t['slug']) ?></div>
                                    </td>
                                    <td class="px-24 py-16 border-0 text-end">
                                        <div class="d-flex align-items-center justify-content-end gap-8">
                                            <button class="btn btn-sm btn-outline-primary radius-8" onclick='editTpl(<?= json_encode($t) ?>)' data-bs-toggle="modal" data-bs-target="#tplModal">
                                                <iconify-icon icon="solar:pen-new-square-bold-duotone"></iconify-icon>
                                            </button>
                                            <form method="POST" style="display:inline" onsubmit="return confirm('Delete?')">
                                                <input type="hidden" name="action" value="delete_template">
                                                <input type="hidden" name="tpl_id" value="<?= $t['id'] ?>">
                                                <button class="btn btn-sm btn-outline-danger radius-8"><iconify-icon icon="solar:trash-bin-trash-bold-duotone"></iconify-icon></button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                <?php if (empty($dbTemplates)): ?>
                                <tr><td colspan="2" class="text-center text-muted py-32 text-xs">No extended templates configured.</td></tr>
                                <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- ══════════════ SITE SETTINGS TAB ══════════════ -->
        <?php elseif ($activeTab === 'settings'): ?>
        <div class="row justify-content-center">
            <div class="col-lg-10">
                <div class="sophisticated-card mb-32">
                    <div class="card-header glass-header py-24 px-32">
                        <h6 class="mb-0 fw-bold">Global Configuration</h6>
                        <p class="text-xs text-secondary-light fw-medium mt-4 mb-0">Control the brand identity across all system touchpoints and templates.</p>
                    </div>
                    <div class="card-body p-32">
                        <!-- Notification Management Card -->
                        <div class="radius-16 mb-40 border overflow-hidden" style="border-color: #e0e7ff;">
                            <!-- Card Header -->
                            <div class="p-20 d-flex align-items-center justify-content-between gap-3" style="background: linear-gradient(135deg, #6366f1, #8b5cf6);">
                                <div class="d-flex align-items-center gap-12">
                                    <div class="w-40-px h-40-px radius-10 d-flex justify-content-center align-items-center bg-white bg-opacity-20 text-white">
                                        <iconify-icon icon="solar:bell-bing-bold-duotone" class="text-xl"></iconify-icon>
                                    </div>
                                    <div>
                                        <h6 class="text-white fw-bold mb-0">Notification Management</h6>
                                        <p class="text-xxs fw-medium mb-0" style="color:rgba(255,255,255,0.75)">Post system-wide announcements to all dashboards.</p>
                                    </div>
                                </div>
                                <?php if (!empty($notificationsHistory)): ?>
                                <form method="POST" onsubmit="return confirm('Clear ALL notifications from dashboard history?')">
                                    <input type="hidden" name="action" value="clear_all_notifications">
                                    <button class="btn btn-sm btn-light fw-bold text-danger px-16">
                                        <iconify-icon icon="solar:restart-bold" class="me-6"></iconify-icon>
                                        Clear All
                                    </button>
                                </form>
                                <?php endif; ?>
                            </div>

                            <!-- Post Form -->
                            <div class="p-24 bg-light">
                                <form method="POST">
                                    <input type="hidden" name="action" value="save_system_notification">
                                    <div class="row g-12">
                                        <div class="col-md-8">
                                            <textarea name="system_notification" class="form-control radius-12" rows="3"
                                                      placeholder="Enter your message... HTML links like <a href='url'>text</a> are supported!"></textarea>
                                        </div>
                                        <div class="col-md-4 d-flex flex-column gap-12">
                                            <select name="notification_type" class="form-select radius-12 fw-bold" id="notifTypeSelect">
                                                <option value="primary">🔵 Primary</option>
                                                <option value="info">🩵 Info</option>
                                                <option value="success">🟢 Success</option>
                                                <option value="warning">🟡 Warning</option>
                                                <option value="danger">🔴 Danger</option>
                                            </select>
                                            <button type="submit" class="btn btn-primary fw-bold radius-12 flex-grow-1">
                                                <iconify-icon icon="solar:globus-bold-duotone" class="me-6"></iconify-icon>
                                                Post Notification
                                            </button>
                                        </div>
                                    </div>
                                </form>
                            </div>

                            <!-- History -->
                            <?php if (!empty($notificationsHistory)): ?>
                            <div class="p-24 border-top">
                                <h6 class="text-xs fw-bold text-uppercase tracking-wider text-secondary-light mb-16">Posted Notifications (Last 10)</h6>
                                <div class="d-flex flex-column gap-10">
                                    <?php
                                    $typeColors = [
                                        'primary' => ['bg' => '#eef2ff', 'border' => '#6366f1', 'text' => '#4f46e5', 'badge' => 'bg-primary'],
                                        'info'    => ['bg' => '#e0f7fa', 'border' => '#0288d1', 'text' => '#0277bd', 'badge' => 'bg-info'],
                                        'success' => ['bg' => '#f0fdf4', 'border' => '#16a34a', 'text' => '#15803d', 'badge' => 'bg-success'],
                                        'warning' => ['bg' => '#fffbeb', 'border' => '#d97706', 'text' => '#b45309', 'badge' => 'bg-warning text-dark'],
                                        'danger'  => ['bg' => '#fef2f2', 'border' => '#dc2626', 'text' => '#b91c1c', 'badge' => 'bg-danger'],
                                    ];
                                    foreach ($notificationsHistory as $nh):
                                        $t = $nh['type'] ?? 'primary';
                                        $tc = $typeColors[$t] ?? $typeColors['primary'];
                                    ?>
                                    <div class="p-12 radius-10 d-flex align-items-center justify-content-between gap-16 border-start"
                                         style="background:<?= $tc['bg'] ?>; border-left: 3px solid <?= $tc['border'] ?> !important;">
                                        <div class="flex-grow-1 overflow-hidden">
                                            <div class="d-flex align-items-center gap-8 mb-6">
                                                <span class="badge <?= $tc['badge'] ?> px-8 py-4 text-xxs fw-bold text-uppercase"><?= ucfirst($t) ?></span>
                                                <span class="text-xxs text-secondary-light"><?= date('M d, Y H:i', strtotime($nh['created_at'])) ?></span>
                                            </div>
                                            <div class="text-sm fw-medium text-truncate" style="color:<?= $tc['text'] ?>"><?= $nh['message'] ?></div>
                                        </div>
                                        <div class="d-flex align-items-center gap-6 flex-shrink-0">
                                            <!-- Edit -->
                                            <button type="button" class="btn btn-sm btn-outline-primary border-0 p-8 radius-8"
                                                    data-bs-toggle="modal" data-bs-target="#editNotifModal"
                                                    data-notif-id="<?= $nh['id'] ?>"
                                                    data-notif-message="<?= htmlspecialchars($nh['message'], ENT_QUOTES) ?>"
                                                    data-notif-type="<?= $t ?>"
                                                    title="Edit">
                                                <iconify-icon icon="solar:pen-new-square-bold-duotone"></iconify-icon>
                                            </button>
                                            <!-- Repost -->
                                            <form method="POST" onsubmit="return confirm('Repost this notification as the latest?')">
                                                <input type="hidden" name="action" value="repost_notification">
                                                <input type="hidden" name="notification_id" value="<?= $nh['id'] ?>">
                                                <button class="btn btn-sm btn-outline-success border-0 p-8 radius-8" title="Repost">
                                                    <iconify-icon icon="solar:refresh-circle-bold-duotone"></iconify-icon>
                                                </button>
                                            </form>
                                            <!-- Delete -->
                                            <form method="POST" onsubmit="return confirm('Remove this notification?')">
                                                <input type="hidden" name="action" value="delete_notification">
                                                <input type="hidden" name="notification_id" value="<?= $nh['id'] ?>">
                                                <button class="btn btn-sm btn-outline-danger border-0 p-8 radius-8" title="Delete">
                                                    <iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon>
                                                </button>
                                            </form>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <?php else: ?>
                            <div class="p-24 text-center text-secondary-light">
                                <iconify-icon icon="solar:bell-off-bold-duotone" class="text-4xl mb-8 d-block"></iconify-icon>
                                <p class="text-xs fw-medium mb-0">No notifications posted yet.</p>
                            </div>
                            <?php endif; ?>
                        </div>

                        <form method="POST" enctype="multipart/form-data">
                            <input type="hidden" name="action" value="save_site_settings">

                            <div class="row gy-4">
                                <!-- Site Name -->
                                <div class="col-md-6">
                                    <label class="form-label fw-extrabold text-dark text-sm mb-8">Platform Identity <span class="text-danger">*</span></label>
                                    <div class="input-group">
                                        <span class="input-group-text bg-light border-end-0 radius-start-10"><iconify-icon icon="solar:window-frame-bold-duotone"></iconify-icon></span>
                                        <input type="text" name="site_name" class="form-control radius-end-10 border-start-0"
                                               value="<?= htmlspecialchars($site_settings['site_name']) ?>"
                                               placeholder="e.g. SonicPesa">
                                    </div>
                                    <div class="form-text text-xxs mt-8 fw-medium">Browser tab name and dashboard meta title.</div>
                                </div>

                                <!-- Landing Title -->
                                <div class="col-md-6">
                                    <label class="form-label fw-extrabold text-dark text-sm mb-8">Brand Tagline <span class="text-danger">*</span></label>
                                    <div class="input-group">
                                        <span class="input-group-text bg-light border-end-0 radius-start-10"><iconify-icon icon="solar:tag-bold-duotone"></iconify-icon></span>
                                        <input type="text" name="landing_title" class="form-control radius-end-10 border-start-0"
                                               value="<?= htmlspecialchars($site_settings['landing_title']) ?>"
                                               placeholder="e.g. UTAMU">
                                    </div>
                                    <div class="form-text text-xxs mt-8 fw-medium">The main text displayed on viral landing pages.</div>
                                </div>

                                <!-- Footer Copyright -->
                                <div class="col-md-6">
                                    <label class="form-label fw-extrabold text-dark text-sm mb-8">Footer Copyright Text</label>
                                    <div class="input-group">
                                        <span class="input-group-text bg-light border-end-0 radius-start-10"><iconify-icon icon="solar:copyright-bold-duotone"></iconify-icon></span>
                                        <input type="text" name="footer_copy" class="form-control radius-end-10 border-start-0"
                                               value="<?= htmlspecialchars($site_settings['footer_copy'] ?? '') ?>"
                                               placeholder="e.g. SonicPesa Dashboard. All Rights Reserved.">
                                    </div>
                                    <div class="form-text text-xxs mt-8 fw-medium">Appears in the footer (after the year).</div>
                                </div>

                                <!-- Footer Made By -->
                                <div class="col-md-6">
                                    <label class="form-label fw-extrabold text-dark text-sm mb-8">Footer 'Made By' Text</label>
                                    <div class="input-group">
                                        <span class="input-group-text bg-light border-end-0 radius-start-10"><iconify-icon icon="solar:user-bold-duotone"></iconify-icon></span>
                                        <input type="text" name="footer_made_by" class="form-control radius-end-10 border-start-0"
                                               value="<?= htmlspecialchars($site_settings['footer_made_by'] ?? '') ?>"
                                               placeholder="e.g. SonicPesa Dev">
                                    </div>
                                    <div class="form-text text-xxs mt-8 fw-medium">Appears in the footer (after 'Made by').</div>
                                </div>

                                <!-- System Charges -->
                                <div class="col-md-6">
                                    <label class="form-label fw-extrabold text-dark text-sm mb-8">System Commission (%)</label>
                                    <div class="input-group">
                                        <span class="input-group-text bg-light border-end-0 radius-start-10"><iconify-icon icon="solar:percentage-bold-duotone"></iconify-icon></span>
                                        <input type="number" step="0.01" name="system_commission" class="form-control radius-end-10 border-start-0"
                                               value="<?= htmlspecialchars($site_settings['system_commission'] ?? 0) ?>"
                                               placeholder="e.g. 10">
                                    </div>
                                    <div class="form-text text-xxs mt-8 fw-medium">Percent deducted from each transaction.</div>
                                </div>

                                <!-- Min Withdrawal -->
                                <div class="col-md-6">
                                    <label class="form-label fw-extrabold text-dark text-sm mb-8">Minimum Withdrawal (TZS)</label>
                                    <div class="input-group">
                                        <span class="input-group-text bg-light border-end-0 radius-start-10"><iconify-icon icon="solar:wallet-money-bold-duotone"></iconify-icon></span>
                                        <input type="number" step="1" name="min_withdrawal" class="form-control radius-end-10 border-start-0"
                                               value="<?= htmlspecialchars($site_settings['min_withdrawal'] ?? 1000) ?>"
                                               placeholder="e.g. 1000">
                                    </div>
                                    <div class="form-text text-xxs mt-8 fw-medium">Users cannot withdraw less than this amount.</div>
                                </div>

                                <!-- System Notification Area -->
                                <div class="col-md-12">
                                    <label class="form-label fw-extrabold text-dark text-sm mb-8">Global System Note (Optional)</label>
                                    <textarea name="system_notification" class="form-control radius-10" rows="3"
                                              placeholder="e.g. System Wide Announcement or Maintenance Notice..."><?= htmlspecialchars($site_settings['system_notification'] ?? '') ?></textarea>
                                    <div class="form-text text-xxs mt-8 fw-medium">This text is used for global announcements in some areas of the platform.</div>
                                </div>

                                <!-- Allow Registration Toggle -->
                                <div class="col-md-12 mt-16">
                                    <?php $isRegEnabled = ($site_settings['allow_registration'] ?? 1); ?>
                                    <div class="form-check form-switch style-check d-flex align-items-center justify-content-between p-16 <?= $isRegEnabled ? 'bg-success-subtle border-success-main' : 'bg-light' ?> radius-12 border transition-all">
                                        <div class="d-flex align-items-center gap-12">
                                            <input class="form-check-input border border-neutral-300 cursor-pointer" type="checkbox" name="allow_registration" id="allowReg" <?= $isRegEnabled ? 'checked' : '' ?> style="width: 45px; height: 22px;">
                                            <label class="form-check-label fw-bold text-dark mb-0 cursor-pointer" for="allowReg">
                                                Allow Public User Registration
                                                <p class="text-xxs text-secondary-light fw-medium mb-0">Toggle this to enable or disable the "Sign Up" page for new users.</p>
                                            </label>
                                        </div>
                                        <span class="badge <?= $isRegEnabled ? 'bg-success-main' : 'bg-secondary-light' ?> px-12 py-6 radius-8 text-white fw-bold">
                                            <?= $isRegEnabled ? 'ALLOW' : 'RESTRICT' ?>
                                        </span>
                                    </div>
                                </div>

                                <!-- Allow Uploads Toggle -->
                                <div class="col-md-12 mt-12">
                                    <?php $isUploadsEnabled = ($site_settings['allow_uploads'] ?? 1); ?>
                                    <div class="form-check form-switch style-check d-flex align-items-center justify-content-between p-16 <?= $isUploadsEnabled ? 'bg-success-subtle border-success-main' : 'bg-danger-subtle border-danger-main' ?> radius-12 border transition-all">
                                        <div class="d-flex align-items-center gap-12">
                                            <input class="form-check-input border border-neutral-300 cursor-pointer" type="checkbox" name="allow_uploads" id="allowUploads" <?= $isUploadsEnabled ? 'checked' : '' ?> style="width: 45px; height: 22px;">
                                            <label class="form-check-label fw-bold text-dark mb-0 cursor-pointer" for="allowUploads">
                                                Allow Video Uploads
                                                <p class="text-xxs text-secondary-light fw-medium mb-0">Toggle this to enable or disable the video upload page for all users (maintenance mode).</p>
                                            </label>
                                        </div>
                                        <span class="badge <?= $isUploadsEnabled ? 'bg-success-main' : 'bg-danger-main' ?> px-12 py-6 radius-8 text-white fw-bold">
                                            <?= $isUploadsEnabled ? 'ENABLED' : 'DISABLED' ?>
                                        </span>
                                    </div>
                                </div>

                                <!-- Allow Withdrawals Toggle -->
                                <div class="col-md-12 mt-12">
                                    <?php $isWDEnabled = ($site_settings['allow_withdrawals'] ?? 1); ?>
                                    <div class="form-check form-switch style-check d-flex align-items-center justify-content-between p-16 <?= $isWDEnabled ? 'bg-success-subtle border-success-main' : 'bg-danger-subtle border-danger-main' ?> radius-12 border transition-all">
                                        <div class="d-flex align-items-center gap-12">
                                            <input class="form-check-input border border-neutral-300 cursor-pointer" type="checkbox" name="allow_withdrawals" id="allowWD" <?= $isWDEnabled ? 'checked' : '' ?> style="width: 45px; height: 22px;">
                                            <label class="form-check-label fw-bold text-dark mb-0 cursor-pointer" for="allowWD">
                                                Allow Withdrawals
                                                <p class="text-xxs text-secondary-light fw-medium mb-0">Toggle this to enable or disable withdrawals across the platform.</p>
                                            </label>
                                        </div>
                                        <span class="badge <?= $isWDEnabled ? 'bg-success-main' : 'bg-danger-main' ?> px-12 py-6 radius-8 text-white fw-bold">
                                            <?= $isWDEnabled ? 'ENABLED' : 'DISABLED' ?>
                                        </span>
                                    </div>
                                </div>

                                <!-- Site Logo -->
                                <div class="col-md-6">
                                    <label class="form-label fw-extrabold text-dark text-sm mb-8">Official Brand Logo</label>
                                    <div class="d-flex align-items-center gap-16 mb-12 p-12 bg-light radius-12">
                                        <?php if (!empty($site_settings['site_logo'])): ?>
                                            <img src="<?= htmlspecialchars($site_settings['site_logo']) ?>" alt="Logo" class="radius-8" style="height:48px; object-fit: contain;">
                                        <?php else: ?>
                                            <div class="bg-base border radius-8 d-flex align-items-center justify-content-center" style="height:48px; width:48px;">
                                                <iconify-icon icon="solar:image-line" class="text-secondary-light"></iconify-icon>
                                            </div>
                                        <?php endif; ?>
                                        <div class="text-xxs fw-bold text-secondary-light">PRESET LOGO</div>
                                    </div>
                                    <input type="file" name="site_logo" class="form-control radius-10" accept="image/*">
                                    <div class="form-text text-xxs mt-8 fw-medium">Recommended: Transparent SVG or PNG (MAX 2MB).</div>
                                </div>

                                <!-- Site Favicon -->
                                <div class="col-md-6">
                                    <label class="form-label fw-extrabold text-dark text-sm mb-8">System Favicon</label>
                                    <div class="d-flex align-items-center gap-16 mb-12 p-12 bg-light radius-12">
                                        <?php if (!empty($site_settings['site_favicon'])): ?>
                                            <img src="<?= htmlspecialchars($site_settings['site_favicon']) ?>" alt="Favicon" class="radius-4" style="height:32px; width:32px;">
                                        <?php else: ?>
                                            <div class="bg-base border radius-4 d-flex align-items-center justify-content-center" style="height:32px; width:32px;">
                                                <iconify-icon icon="solar:star-line" class="text-secondary-light"></iconify-icon>
                                            </div>
                                        <?php endif; ?>
                                        <div class="text-xxs fw-bold text-secondary-light">PRESET FAVICON</div>
                                    </div>
                                    <input type="file" name="site_favicon" class="form-control radius-10" accept="image/*,.ico">
                                    <div class="form-text text-xxs mt-8 fw-medium">Required: 32x32px ICO or PNG.</div>
                                </div>

                                <!-- Live Brand Preview -->
                                <div class="col-12 mt-12">
                                    <div class="bg-dark p-24 radius-16 shadow-lg">
                                        <div class="d-flex align-items-center justify-content-between mb-16">
                                            <span class="text-xxs fw-extrabold text-uppercase ls-2" style="color:#6366f1;">Live Landing Preview</span>
                                            <div class="d-flex gap-4">
                                                <div style="width:8px; height:8px; border-radius:50%; background:#ef4444;"></div>
                                                <div style="width:8px; height:8px; border-radius:50%; background:#f59e0b;"></div>
                                                <div style="width:8px; height:8px; border-radius:50%; background:#10b981;"></div>
                                            </div>
                                        </div>
                                        <div class="d-inline-flex align-items-center gap-12 border-start border-3 border-danger p-12">
                                            <h2 class="text-white fw-900 mb-0 ls-n1" style="font-family: 'Inter', sans-serif;" id="previewTitle"><?= htmlspecialchars($site_settings['landing_title']) ?>+</h2>
                                            <div class="px-8 py-4 bg-white-focus radius-4 text-xxs fw-bold text-white-75 ls-1">PREMIUM STREAMING</div>
                                        </div>
                                    </div>
                                </div>

                                <div class="col-12 mt-24">
                                    <button type="submit" class="btn btn-primary btn-premium px-40 py-12 d-flex align-items-center gap-12">
                                        <iconify-icon icon="solar:diskette-bold-duotone" class="text-xl"></iconify-icon>
                                        Commit System Changes
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- ═══════════════════════════════════════════════════════════
             PAYMENT API CONFIGURATION CARD
        ════════════════════════════════════════════════════════════ -->
        <div class="row gy-4 mt-4">
            <div class="col-12">
                <div class="sophisticated-card">
                    <div class="card-header glass-header py-20 px-24 d-flex align-items-center justify-content-between">
                        <div>
                            <h6 class="mb-0 fw-bold d-flex align-items-center gap-10">
                                <iconify-icon icon="solar:server-path-bold-duotone" class="text-primary-600 text-xl"></iconify-icon>
                                Payment API Configuration
                            </h6>
                            <p class="text-xxs text-secondary-light fw-bold text-uppercase ls-1 mt-4 mb-0">
                                Change payment gateway endpoint without touching code files
                            </p>
                        </div>
                        <!-- Live status badge updated by JS test -->
                        <span id="apiStatusBadge" class="badge px-16 py-8 radius-20 fw-bold text-xs"
                              style="background:<?= !empty($site_settings['payment_api_url']) ? '#d1fae5' : '#fef3c7' ?>;
                                     color:<?= !empty($site_settings['payment_api_url']) ? '#065f46' : '#92400e' ?>;">
                            <iconify-icon icon="solar:<?= !empty($site_settings['payment_api_url']) ? 'check-circle-bold' : 'danger-triangle-bold' ?>" class="me-4"></iconify-icon>
                            <?= !empty($site_settings['payment_api_url']) ? 'CUSTOM URL ACTIVE' : 'USING DEFAULT FALLBACK' ?>
                        </span>
                    </div>

                    <div class="card-body p-24">

                        <!-- Current active endpoint display -->
                        <div class="p-16 mb-24 radius-12 border d-flex align-items-center gap-16"
                             style="background:linear-gradient(135deg,#f0f9ff,#e0f2fe); border-color:#bae6fd !important;">
                            <iconify-icon icon="solar:link-bold-duotone" class="text-sky-600 text-2xl flex-shrink-0" style="color:#0284c7;"></iconify-icon>
                            <div class="flex-grow-1 overflow-hidden">
                                <div class="text-xxs fw-extrabold text-uppercase ls-1 mb-4" style="color:#0369a1;">Currently Active Endpoint</div>
                                <code class="text-sm fw-bold" style="color:#0c4a6e; word-break:break-all;" id="currentActiveUrl">
                                    <?= htmlspecialchars($site_settings['payment_api_url'] ?? defined('KINDAMBA_API_URL') ? KINDAMBA_API_URL : 'https://www.pesagate.online/api') ?>
                                </code>
                            </div>
                        </div>

                        <form method="POST" id="paymentApiForm">
                            <input type="hidden" name="action" value="save_payment_api">
                            <div class="row gy-4">

                                <!-- API Base URL -->
                                <div class="col-md-12">
                                    <label class="form-label fw-extrabold text-dark text-sm mb-8">
                                        Payment Gateway API URL <span class="text-danger">*</span>
                                    </label>
                                    <div class="input-group">
                                        <span class="input-group-text bg-light border-end-0 radius-start-10">
                                            <iconify-icon icon="solar:global-bold-duotone"></iconify-icon>
                                        </span>
                                        <input type="url" name="payment_api_url" id="paymentApiUrl"
                                               class="form-control border-start-0 border-end-0"
                                               value="<?= htmlspecialchars($site_settings['payment_api_url'] ?? '') ?>"
                                               placeholder="https://www.pesagate.online/api"
                                               required>
                                        <button type="button" class="btn btn-outline-info radius-end-10 px-16 fw-bold"
                                                id="testApiBtn" onclick="testApiConnection()">
                                            <iconify-icon icon="solar:wifi-router-bold-duotone" class="me-6"></iconify-icon>
                                            Test Connection
                                        </button>
                                    </div>
                                    <div class="form-text text-xxs mt-8 fw-medium">
                                        Full base URL of your payment API. Example: <code>https://www.pesagate.online/api</code>
                                        or <code>https://kindamba.site/api</code>
                                    </div>
                                </div>

                                <!-- Public Key -->
                                <div class="col-md-12">
                                    <label class="form-label fw-extrabold text-dark text-sm mb-8">
                                        API Public Key
                                        <span class="text-secondary-light fw-medium">(optional override — uses system default if blank)</span>
                                    </label>
                                    <div class="input-group">
                                        <span class="input-group-text bg-light border-end-0 radius-start-10">
                                            <iconify-icon icon="solar:key-bold-duotone"></iconify-icon>
                                        </span>
                                        <input type="text" name="payment_api_public_key" id="paymentApiKey"
                                               class="form-control radius-end-10 border-start-0 font-monospace"
                                               value="<?= htmlspecialchars($site_settings['payment_api_public_key'] ?? '') ?>"
                                               placeholder="pk_live_xxxxxxxxxxxxxxxxxxxxxxxx">
                                    </div>
                                    <div class="form-text text-xxs mt-8 fw-medium">
                                        If provided, this key will override the default key in <code>config.php</code>.
                                    </div>
                                </div>

                                <!-- Test Result Box -->
                                <div class="col-12" id="testResultBox" style="display:none;">
                                    <div id="testResultInner" class="p-16 radius-12 border d-flex align-items-start gap-12"></div>
                                </div>

                                <!-- Actions -->
                                <div class="col-12 mt-8 d-flex align-items-center gap-12 flex-wrap">
                                    <button type="submit" class="btn btn-primary btn-premium px-32 py-12 d-flex align-items-center gap-10">
                                        <iconify-icon icon="solar:diskette-bold-duotone" class="text-xl"></iconify-icon>
                                        Save API Settings
                                    </button>
                                    <button type="button" class="btn btn-outline-secondary btn-premium px-24 py-12 d-flex align-items-center gap-10"
                                            onclick="testApiConnection()">
                                        <iconify-icon icon="solar:refresh-bold-duotone" class="text-xl"></iconify-icon>
                                        Test &amp; Verify
                                    </button>
                                    <!-- Quick-select buttons -->
                                    <div class="ms-auto d-flex align-items-center gap-8 flex-wrap">
                                        <span class="text-xxs fw-bold text-secondary-light text-uppercase ls-1 me-4">Quick Set:</span>
                                        <button type="button" class="btn btn-sm btn-outline-primary radius-8 fw-bold"
                                                onclick="setApiUrl('https://www.pesagate.online/api')">
                                            PesaGate
                                        </button>
                                        <button type="button" class="btn btn-sm btn-outline-secondary radius-8 fw-bold"
                                                onclick="setApiUrl('https://kindamba.site/api')">
                                            Kindamba
                                        </button>
                                    </div>
                                </div>

                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <!-- END Payment API Configuration Card -->

        <script>
        // ── Quick-select endpoint shortcuts ────────────────────────────────────
        function setApiUrl(url) {
            document.getElementById('paymentApiUrl').value = url;
            // Clear previous test results
            document.getElementById('testResultBox').style.display = 'none';
        }

        // ── Test API Connection (AJAX) ─────────────────────────────────────────
        function testApiConnection() {
            var apiUrl = document.getElementById('paymentApiUrl').value.trim();
            var apiKey = document.getElementById('paymentApiKey').value.trim();

            if (!apiUrl) {
                showTestResult(false, 'Please enter a Payment API URL first.');
                return;
            }

            var btn = document.getElementById('testApiBtn');
            btn.disabled = true;
            btn.innerHTML = '<span class="spinner-border spinner-border-sm me-6"></span> Testing...';
            document.getElementById('testResultBox').style.display = 'none';

            // Use the existing test_kindamba.php endpoint
            var payload = { api_key: apiKey || 'pk_test_connection_check', api_url: apiUrl };

            fetch('api/test_kindamba.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                btn.disabled = false;
                btn.innerHTML = '<iconify-icon icon="solar:wifi-router-bold-duotone" class="me-6"></iconify-icon> Test Connection';

                if (data.success) {
                    showTestResult(true,
                        '<strong>Connection Successful!</strong> ' + data.message +
                        (data.url_tested ? '<br><small class="text-muted">Tested URL: ' + data.url_tested + '</small>' : '')
                    );
                    // Update the badge
                    document.getElementById('apiStatusBadge').style.background = '#d1fae5';
                    document.getElementById('apiStatusBadge').style.color = '#065f46';
                    document.getElementById('apiStatusBadge').innerHTML = '<iconify-icon icon="solar:check-circle-bold" class="me-4"></iconify-icon> CONNECTION OK';
                } else {
                    showTestResult(false,
                        '<strong>Connection Failed.</strong> ' + data.message +
                        (data.url_tested ? '<br><small class="text-muted">Tested URL: ' + data.url_tested + '</small>' : '')
                    );
                    document.getElementById('apiStatusBadge').style.background = '#fee2e2';
                    document.getElementById('apiStatusBadge').style.color = '#991b1b';
                    document.getElementById('apiStatusBadge').innerHTML = '<iconify-icon icon="solar:danger-bold" class="me-4"></iconify-icon> CONNECTION FAILED';
                }
            })
            .catch(function(err) {
                btn.disabled = false;
                btn.innerHTML = '<iconify-icon icon="solar:wifi-router-bold-duotone" class="me-6"></iconify-icon> Test Connection';
                showTestResult(false, 'AJAX error: ' + err.message);
            });
        }

        function showTestResult(success, html) {
            var box = document.getElementById('testResultBox');
            var inner = document.getElementById('testResultInner');
            box.style.display = '';
            if (success) {
                inner.style.background = '#f0fdf4';
                inner.style.borderColor = '#86efac';
                inner.innerHTML = '<iconify-icon icon="solar:check-circle-bold-duotone" style="color:#16a34a; font-size:1.5rem; flex-shrink:0;" class="mt-2"></iconify-icon>'
                    + '<div class="text-sm fw-medium" style="color:#14532d;">' + html + '</div>';
            } else {
                inner.style.background = '#fef2f2';
                inner.style.borderColor = '#fca5a5';
                inner.innerHTML = '<iconify-icon icon="solar:danger-bold-duotone" style="color:#dc2626; font-size:1.5rem; flex-shrink:0;" class="mt-2"></iconify-icon>'
                    + '<div class="text-sm fw-medium" style="color:#7f1d1d;">' + html + '</div>';
            }
        }

        // ── Landing title live preview ─────────────────────────────────────────
        var ltInput = document.querySelector('input[name="landing_title"]');
        if (ltInput) {
            ltInput.addEventListener('input', function() {
                var p = document.getElementById('previewTitle');
                if (p) p.textContent = this.value + '+';
            });
        }
        </script>

        <?php elseif ($activeTab === 'root_domains'): ?>
        <div class="row gy-4">
            <div class="col-12">
                <div class="sophisticated-card">
                    <div class="card-header glass-header py-24 px-32 d-flex align-items-center justify-content-between">
                        <div>
                            <h6 class="mb-0 fw-bold">Master Root Domains</h6>
                            <p class="text-xs text-secondary-light fw-medium mt-4 mb-0">These domains are available for users to create wildcard subdomains.</p>
                        </div>
                        <button class="btn btn-primary btn-premium d-flex align-items-center gap-8" data-bs-toggle="modal" data-bs-target="#rootModal" onclick="clearRootForm()">
                            <iconify-icon icon="solar:server-square-bold-duotone" class="text-xl"></iconify-icon>
                            Add Root Domain
                        </button>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table bordered-table mb-0">
                                <thead>
                                    <tr class="bg-light">
                                        <th class="px-24 py-16 border-0 text-xs fw-bold text-uppercase text-secondary-light">Domain Name</th>
                                        <th class="px-24 py-16 border-0 text-xs fw-bold text-uppercase text-secondary-light">Status</th>
                                        <th class="px-24 py-16 border-0 text-xs fw-bold text-uppercase text-secondary-light">Created</th>
                                        <th class="px-24 py-16 border-0 text-xs fw-bold text-uppercase text-secondary-light text-end">Management</th>
                                    </tr>
                                </thead>
                                <tbody>
                                <?php foreach ($rootDomains as $rd): ?>
                                <tr>
                                    <td class="px-24 py-16 border-0 fw-bold text-primary-600"><?= htmlspecialchars($rd['domain_name']) ?></td>
                                    <td class="px-24 py-16 border-0">
                                        <span class="badge radius-8 px-12 py-4 fw-bold text-xxs <?= $rd['is_active'] ? 'bg-success-focus text-success-main' : 'bg-danger-focus text-danger-main' ?>">
                                            <?= $rd['is_active'] ? 'ACTIVE' : 'INACTIVE' ?>
                                        </span>
                                    </td>
                                    <td class="px-24 py-16 border-0 text-sm text-secondary-light"><?= date('M d, Y', strtotime($rd['created_at'])) ?></td>
                                    <td class="px-24 py-16 border-0 text-end">
                                        <div class="d-flex align-items-center justify-content-end gap-12">
                                            <button class="btn btn-sm btn-outline-primary radius-8" onclick='editRoot(<?= json_encode($rd) ?>)' data-bs-toggle="modal" data-bs-target="#rootModal">
                                                <iconify-icon icon="solar:pen-new-square-bold-duotone" class="text-lg"></iconify-icon>
                                            </button>
                                            <form method="POST" onsubmit="return confirm('Delete this root domain? All associated subdomains may stop working.')" style="display:inline">
                                                <input type="hidden" name="action" value="delete_root_domain">
                                                <input type="hidden" name="root_id" value="<?= $rd['id'] ?>">
                                                <button class="btn btn-sm btn-outline-danger radius-8"><iconify-icon icon="solar:trash-bin-minimalistic-bold-duotone" class="text-lg"></iconify-icon></button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                <?php if (empty($rootDomains)): ?>
                                <tr><td colspan="4" class="text-center py-40 text-secondary-light">No root domains configured yet. Add your first domain to enable subdomains.</td></tr>
                                <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

    </div><!-- end dashboard-main-body -->
    <?php include 'includes/footer.php'; ?>
</main>

<!-- ── User Modal ── -->
<div class="modal fade" id="userModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content radius-16 border-0 shadow-lg">
            <div class="modal-header glass-header py-20 px-24">
                <h5 class="modal-title fw-bold text-dark d-flex align-items-center gap-12" id="userModalTitle">
                    <iconify-icon icon="solar:user-bold-duotone" class="text-primary-600"></iconify-icon>
                    Add Influencer
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="save_user">
                <input type="hidden" name="user_id" id="editUserId" value="0">
                <div class="modal-body p-24">
                    <div class="mb-20">
                        <label class="form-label fw-extrabold text-dark text-xs text-uppercase ls-1">Full Identity <span class="text-danger">*</span></label>
                        <input type="text" name="name" id="editUserName" class="form-control radius-10 py-12" placeholder="e.g. James Gibson" required>
                    </div>
                    <div class="mb-20">
                        <label class="form-label fw-extrabold text-dark text-xs text-uppercase ls-1">Credential Email <span class="text-danger">*</span></label>
                        <input type="email" name="email" id="editUserEmail" class="form-control radius-10 py-12" placeholder="user@SonicPesa.com" required>
                    </div>
                    <div class="mb-20">
                        <label class="form-label fw-extrabold text-dark text-xs text-uppercase ls-1">System Authorization</label>
                        <select name="role" id="editUserRole" class="form-select radius-10 py-12 fw-bold">
                            <option value="user">Standard Influencer</option>
                            <option value="admin">System Administrator</option>
                        </select>
                    </div>
                    <div class="mb-0">
                        <label class="form-label fw-extrabold text-dark text-xs text-uppercase ls-1">Security Access <span id="pwNote" class="text-muted fw-medium">(required for new)</span></label>
                        <input type="password" name="password" id="editUserPw" class="form-control radius-10 py-12" placeholder="••••••••">
                    </div>
                </div>
                <div class="modal-footer border-0 p-24 pt-0">
                    <button type="button" class="btn btn-outline-secondary btn-premium border-0 fw-bold" data-bs-dismiss="modal">Discard</button>
                    <button type="submit" class="btn btn-primary btn-premium px-32">
                        <iconify-icon icon="solar:diskette-bold-duotone" class="me-8"></iconify-icon>
                        Commit User
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- ── Template Modal ── -->
<div class="modal fade" id="tplModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content radius-16 border-0 shadow-lg">
            <div class="modal-header glass-header py-20 px-24">
                <h5 class="modal-title fw-bold text-dark d-flex align-items-center gap-12" id="tplModalTitle">
                    <iconify-icon icon="solar:mirror-bold-duotone" class="text-primary-600"></iconify-icon>
                    Add Template
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="tplForm" method="POST" enctype="multipart/form-data">
                <input type="hidden" name="action" value="save_template">
                <input type="hidden" name="tpl_id" id="editTplId" value="0">
                <div class="modal-body p-24">
                    <div class="mb-20">
                        <label class="form-label fw-extrabold text-dark text-xs text-uppercase ls-1">Template Name <span class="text-danger">*</span></label>
                        <input type="text" name="tname" id="editTplName" class="form-control radius-10 py-12" placeholder="e.g. Cyber Neon" required>
                    </div>
                    <div class="mb-20">
                        <label class="form-label fw-extrabold text-dark text-xs text-uppercase ls-1">System File Handle <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <input type="text" name="tslug" id="editTplSlug" class="form-control radius-start-10 py-12" placeholder="e.g. landing8" required>
                            <span class="input-group-text bg-light border-start-0 radius-end-10 fw-bold">.php</span>
                        </div>
                        <div class="form-text text-xxs mt-8 fw-medium">Must exist in <code>templates/</code> directory.</div>
                    </div>
                    <hr class="my-20 border-light">
                    <div class="mb-20">
                        <label class="form-label fw-extrabold text-dark text-xs text-uppercase ls-1">Update Script (.php) <span class="text-muted text-xxs">(Optional)</span></label>
                        <input type="file" name="edit_tpl_php" class="form-control radius-10 py-12" accept=".php">
                        <div class="form-text text-xxs mt-8 fw-medium">Upload to replace the existing PHP script for this handle.</div>
                    </div>
                    <div class="mb-0">
                        <label class="form-label fw-extrabold text-dark text-xs text-uppercase ls-1">Update Thumbnail <span class="text-muted text-xxs">(Optional)</span></label>
                        <input type="file" name="edit_tpl_png" class="form-control radius-10 py-12" accept="image/png, image/jpeg">
                        <div class="form-text text-xxs mt-8 fw-medium">Upload to replace the existing thumbnail preview image.</div>
                    </div>
                    
                    <!-- Progress Bar (Hidden initially) -->
                    <div id="editProgressContainer" class="mt-4" style="display: none;">
                        <div class="d-flex justify-content-between mb-2">
                            <span class="text-xs fw-bold text-primary-600">Uploading Files...</span>
                            <span class="text-xs fw-bold text-primary-600" id="editUploadPercentage">0%</span>
                        </div>
                        <div class="progress radius-8" style="height: 8px;">
                            <div id="editUploadProgressBar" class="progress-bar bg-primary-600 progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%;"></div>
                        </div>
                    </div>

                </div>
                <div class="modal-footer border-0 p-24 pt-0">
                    <button type="button" class="btn btn-outline-secondary btn-premium border-0 fw-bold" data-bs-dismiss="modal">Discard</button>
                    <button type="submit" id="saveTplBtn" class="btn btn-primary btn-premium px-32">
                        <iconify-icon icon="solar:add-circle-bold-duotone" class="me-8"></iconify-icon>
                        Register Template
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- ── Template Installer Modal ── -->
<div class="modal fade" id="installerModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content radius-16 border-0 shadow-lg">
            <div class="modal-header glass-header py-20 px-24">
                <h5 class="modal-title fw-bold text-dark d-flex align-items-center gap-12">
                    <iconify-icon icon="solar:upload-minimalistic-bold-duotone" class="text-primary-600"></iconify-icon>
                    Install New Template
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="installerForm" method="POST" enctype="multipart/form-data">
                <input type="hidden" name="action" value="install_template">
                <div class="modal-body p-24">
                    <div class="alert alert-info border-0 bg-info-focus text-info-main radius-12 p-16 mb-20 d-flex gap-12">
                        <iconify-icon icon="solar:info-circle-bold" class="text-xl"></iconify-icon>
                        <div class="text-xs fw-medium">The system will automatically assign the next available version number (e.g. Model V9) and slug (e.g. landing9).</div>
                    </div>
                    
                    <div class="mb-20">
                        <label class="form-label fw-extrabold text-dark text-xs text-uppercase ls-1">Template Script (.php) <span class="text-danger">*</span></label>
                        <input type="file" name="tpl_php" class="form-control radius-10 py-12" accept=".php" required>
                        <div class="form-text text-xxs mt-8 fw-medium">Upload the PHP landing template file.</div>
                    </div>
                    <div class="mb-20">
                        <label class="form-label fw-extrabold text-dark text-xs text-uppercase ls-1">Template Thumbnail (.png) <span class="text-danger">*</span></label>
                        <input type="file" name="tpl_png" class="form-control radius-10 py-12" accept="image/png, image/jpeg" required>
                        <div class="form-text text-xxs mt-8 fw-medium">Upload the thumbnail image. It will be shown in the settings panel.</div>
                    </div>

                    <!-- Progress Bar (Hidden initially) -->
                    <div id="uploadProgressContainer" class="mt-4" style="display: none;">
                        <div class="d-flex justify-content-between mb-2">
                            <span class="text-xs fw-bold text-primary-600">Uploading Files...</span>
                            <span class="text-xs fw-bold text-primary-600" id="uploadPercentage">0%</span>
                        </div>
                        <div class="progress radius-8" style="height: 8px;">
                            <div id="uploadProgressBar" class="progress-bar bg-primary-600 progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%;"></div>
                        </div>
                    </div>

                </div>
                <div class="modal-footer border-0 p-24 pt-0">
                    <button type="button" class="btn btn-outline-secondary btn-premium border-0 fw-bold" data-bs-dismiss="modal">Discard</button>
                    <button type="submit" id="installBtn" class="btn btn-primary btn-premium px-32">
                        <iconify-icon icon="solar:magic-stick-3-bold-duotone" class="me-8"></iconify-icon>
                        Auto Install Template
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.getElementById('installerForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    var form = this;
    var btn = document.getElementById('installBtn');
    var progressContainer = document.getElementById('uploadProgressContainer');
    var progressBar = document.getElementById('uploadProgressBar');
    var progressText = document.getElementById('uploadPercentage');
    
    // Disable elements
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span> Uploading...';
    progressContainer.style.display = 'block';
    
    var formData = new FormData(form);
    var xhr = new XMLHttpRequest();
    
    xhr.open('POST', 'superadmin.php', true);
    
    xhr.upload.onprogress = function(e) {
        if (e.lengthComputable) {
            var percentComplete = Math.round((e.loaded / e.total) * 100);
            progressBar.style.width = percentComplete + '%';
            progressText.textContent = percentComplete + '%';
        }
    };
    
    xhr.onload = function() {
        if (xhr.status === 200) {
            document.open();
            document.write(xhr.responseText);
            document.close();
            window.history.pushState('', '', 'superadmin.php?tab=templates');
        } else {
            alert('Upload failed with status ' + xhr.status);
            btn.disabled = false;
            btn.innerHTML = '<iconify-icon icon="solar:magic-stick-3-bold-duotone" class="me-8"></iconify-icon> Auto Install Template';
            progressContainer.style.display = 'none';
        }
    };
    
    xhr.onerror = function() {
        alert('Network error occurred during upload.');
        btn.disabled = false;
        btn.innerHTML = '<iconify-icon icon="solar:magic-stick-3-bold-duotone" class="me-8"></iconify-icon> Auto Install Template';
        progressContainer.style.display = 'none';
    };
    
    xhr.send(formData);
});

document.getElementById('tplForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    var form = this;
    var btn = document.getElementById('saveTplBtn');
    var progressContainer = document.getElementById('editProgressContainer');
    var progressBar = document.getElementById('editUploadProgressBar');
    var progressText = document.getElementById('editUploadPercentage');
    
    // Disable elements
    btn.disabled = true;
    var originalBtnHtml = btn.innerHTML;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span> Saving...';
    progressContainer.style.display = 'block';
    
    var formData = new FormData(form);
    var xhr = new XMLHttpRequest();
    
    xhr.open('POST', 'superadmin.php', true);
    
    xhr.upload.onprogress = function(e) {
        if (e.lengthComputable) {
            var percentComplete = Math.round((e.loaded / e.total) * 100);
            progressBar.style.width = percentComplete + '%';
            progressText.textContent = percentComplete + '%';
        }
    };
    
    xhr.onload = function() {
        if (xhr.status === 200) {
            document.open();
            document.write(xhr.responseText);
            document.close();
            window.history.pushState('', '', 'superadmin.php?tab=templates');
        } else {
            alert('Upload failed with status ' + xhr.status);
            btn.disabled = false;
            btn.innerHTML = originalBtnHtml;
            progressContainer.style.display = 'none';
        }
    };
    
    xhr.onerror = function() {
        alert('Network error occurred during upload.');
        btn.disabled = false;
        btn.innerHTML = originalBtnHtml;
        progressContainer.style.display = 'none';
    };
    
    xhr.send(formData);
});
</script>

<!-- ── Link (Domain) Modal ── -->
<div class="modal fade" id="linkModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content radius-16 border-0 shadow-lg">
            <div class="modal-header glass-header py-20 px-24">
                <h5 class="modal-title fw-bold text-dark d-flex align-items-center gap-12" id="linkModalTitle">
                    <iconify-icon icon="solar:global-bold-duotone" class="text-primary-600"></iconify-icon>
                    Register Domain
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="save_link">
                <input type="hidden" name="domain_id" id="editLinkId" value="0">
                <div class="modal-body p-24">
                    <div class="mb-20">
                        <label class="form-label fw-extrabold text-dark text-xs text-uppercase ls-1">Domain Owner <span class="text-danger">*</span></label>
                        <select name="owner_id" id="editLinkOwner" class="form-select radius-10 py-12 fw-bold" required>
                            <?php foreach ($users as $u): ?>
                                <option value="<?= $u['id'] ?>"><?= htmlspecialchars($u['name']) ?> (<?= htmlspecialchars($u['email']) ?>)</option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-20">
                        <label class="form-label fw-extrabold text-dark text-xs text-uppercase ls-1">Domain Name / Link <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <span class="input-group-text bg-light border-end-0 radius-start-10"><iconify-icon icon="solar:link-bold-duotone"></iconify-icon></span>
                            <input type="text" name="domain_name" id="editLinkName" class="form-control radius-end-10 border-start-0 py-12" placeholder="e.g. store.SonicPesa.com" required>
                        </div>
                        <div class="form-text text-xxs mt-8 fw-medium">No http:// or https:// prefix. Only lowercase alphanumeric, dots, and hyphens.</div>
                    </div>
                    <div class="mb-0">
                        <label class="form-label fw-extrabold text-dark text-xs text-uppercase ls-1">Verification Status</label>
                        <select name="status" id="editLinkStatus" class="form-select radius-10 py-12">
                            <option value="active">Active (Verified)</option>
                            <option value="pending">Pending Verification</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer border-0 p-24 pt-0">
                    <button type="button" class="btn btn-outline-secondary btn-premium border-0 fw-bold" data-bs-dismiss="modal">Discard</button>
                    <button type="submit" class="btn btn-primary btn-premium px-32">
                        <iconify-icon icon="solar:diskette-bold-duotone" class="me-8"></iconify-icon>
                        Save Link
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- ── Root Domain Modal ── -->
<div class="modal fade" id="rootModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content radius-16 border-0 shadow-lg">
            <div class="modal-header glass-header py-20 px-24">
                <h5 class="modal-title fw-bold text-dark d-flex align-items-center gap-12" id="rootModalTitle">
                    <iconify-icon icon="solar:server-square-bold-duotone" class="text-primary-600"></iconify-icon>
                    System Domain
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="save_root_domain">
                <input type="hidden" name="root_id" id="editRootId" value="0">
                <div class="modal-body p-24">
                    <div class="mb-20">
                        <label class="form-label fw-extrabold text-dark text-xs text-uppercase ls-1">Domain Name <span class="text-danger">*</span></label>
                        <input type="text" name="domain_name" id="editRootName" class="form-control radius-10 py-12" placeholder="e.g. mutunda.click" required>
                        <div class="form-text text-xxs mt-8">Ensure Wildcard DNS (*.domain.com) is pointed to this server IP.</div>
                    </div>
                    <div class="form-check form-switch mb-0">
                        <input class="form-check-input" type="checkbox" name="is_active" id="editRootActive" checked>
                        <label class="form-check-label fw-bold text-sm" for="editRootActive">Active and Available for Users</label>
                    </div>
                </div>
                <div class="modal-footer border-0 p-24 pt-0">
                    <button type="button" class="btn btn-outline-secondary btn-premium border-0 fw-bold" data-bs-dismiss="modal">Discard</button>
                    <button type="submit" class="btn btn-primary btn-premium px-32">
                        <iconify-icon icon="solar:diskette-bold-duotone" class="me-8"></iconify-icon>
                        Save Domain
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    // User modal helpers
    function clearUserForm() {
        document.getElementById('userModalTitle').textContent = 'Add User';
        document.getElementById('editUserId').value = '0';
        document.getElementById('editUserName').value = '';
        document.getElementById('editUserEmail').value = '';
        document.getElementById('editUserRole').value = 'user';
        document.getElementById('editUserPw').value = '';
        document.getElementById('pwNote').textContent = '(required for new)';
    }
    function editUser(u) {
        document.getElementById('userModalTitle').textContent = 'Edit User';
        document.getElementById('editUserId').value = u.id;
        document.getElementById('editUserName').value = u.name;
        document.getElementById('editUserEmail').value = u.email;
        document.getElementById('editUserRole').value = u.role;
        document.getElementById('editUserPw').value = '';
        document.getElementById('pwNote').textContent = '(leave blank to keep current)';
    }

    // Template modal helpers
    function clearTplForm() {
        document.getElementById('tplModalTitle').textContent = 'Add Template';
        document.getElementById('editTplId').value = '0';
        document.getElementById('editTplName').value = '';
        document.getElementById('editTplSlug').value = '';
    }
    function editTpl(t) {
        document.getElementById('tplModalTitle').textContent = 'Edit Template';
        document.getElementById('editTplId').value = t.id;
        document.getElementById('editTplName').value = t.name;
        document.getElementById('editTplSlug').value = t.slug;
    }

    // Link modal helpers
    function clearLinkForm() {
        document.getElementById('linkModalTitle').textContent = 'Register Domain';
        document.getElementById('editLinkId').value = '0';
        document.getElementById('editLinkName').value = '';
        document.getElementById('editLinkStatus').value = 'active';
    }
    function editLink(lk) {
        document.getElementById('linkModalTitle').textContent = 'Edit Domain';
        document.getElementById('editLinkId').value = lk.id;
        document.getElementById('editLinkOwner').value = lk.user_id;
        document.getElementById('editLinkName').value = lk.domain_name;
        document.getElementById('editLinkStatus').value = lk.status;
    }

    // Live preview for landing title
    const ltInput = document.querySelector('input[name="landing_title"]');
    const preview = document.getElementById('previewTitle');
    if (ltInput && preview) {
        ltInput.addEventListener('input', () => {
            preview.textContent = (ltInput.value || 'UTAMU') + '+';
        });
    }

</script>

<!-- Edit Notification Modal -->
<div class="modal fade" id="editNotifModal" tabindex="-1" aria-labelledby="editNotifModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content radius-16 border-0 shadow-lg">
            <div class="modal-header border-0 px-24 pt-24 pb-0">
                <div class="d-flex align-items-center gap-12">
                    <div class="w-40-px h-40-px radius-10 d-flex justify-content-center align-items-center text-white" style="background:#6366f1">
                        <iconify-icon icon="solar:pen-new-square-bold-duotone" class="text-lg"></iconify-icon>
                    </div>
                    <div>
                        <h6 class="fw-bold mb-0" id="editNotifModalLabel">Edit Notification</h6>
                        <p class="text-xxs text-secondary-light mb-0">Update the message and type</p>
                    </div>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="edit_notification">
                <input type="hidden" name="notification_id" id="editNotifId">
                <div class="modal-body px-24 py-20">
                    <div class="mb-16">
                        <label class="form-label fw-bold text-sm mb-8">Message <span class="text-danger">*</span></label>
                        <textarea name="edit_message" id="editNotifMessage" class="form-control radius-12" rows="4"
                                  placeholder="Your notification message... HTML links supported"></textarea>
                        <div class="form-text text-xxs mt-6">HTML links like <code>&lt;a href="..."&gt;text&lt;/a&gt;</code> are supported.</div>
                    </div>
                    <div>
                        <label class="form-label fw-bold text-sm mb-8">Status / Type</label>
                        <select name="edit_type" id="editNotifType" class="form-select radius-12">
                            <option value="primary">🔵 Primary</option>
                            <option value="info">🩵 Info</option>
                            <option value="success">🟢 Success</option>
                            <option value="warning">🟡 Warning</option>
                            <option value="danger">🔴 Danger</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer border-0 px-24 pb-24 pt-0 gap-12">
                    <button type="button" class="btn btn-outline-secondary radius-10 px-20" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary radius-10 px-32 fw-bold">
                        <iconify-icon icon="solar:disk-bold-duotone" class="me-8"></iconify-icon>
                        Save Changes
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    // This script runs AFTER the modal HTML exists in the DOM
    document.getElementById('editNotifModal').addEventListener('show.bs.modal', function (event) {
        var btn = event.relatedTarget;
        document.getElementById('editNotifId').value = btn.getAttribute('data-notif-id');
        document.getElementById('editNotifMessage').value = btn.getAttribute('data-notif-message');
        var type = btn.getAttribute('data-notif-type');
        var sel = document.getElementById('editNotifType');
        for (var i = 0; i < sel.options.length; i++) {
            sel.options[i].selected = (sel.options[i].value === type);
        }
    });
</script>

</body>
</html>


