<?php
// --- SECURITY: GATEKEEPER START ---
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();

if (isset($_GET['toggle_admin_access'])) {
    $_SESSION['is_admin'] = ($_GET['toggle_admin_access'] === 'on');
    header("Location: admin.php");
    exit();
}

if (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] !== true) {
    header("Location: login.php");
    exit();
}

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

function validate_csrf($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

try {
    $db = new PDO('sqlite:' . __DIR__ . '/app_feed.db');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->exec("PRAGMA busy_timeout = 5000;");
    $db->exec("PRAGMA journal_mode = WAL;");
    
    // --- CLEANUP LEGACY KEYS ---
    $db->exec("DELETE FROM app_feed_settings WHERE setting_key LIKE 'bg_%' AND setting_key NOT LIKE 'bg_%_%'");

    // Ensure tables exist
    $db->exec("CREATE TABLE IF NOT EXISTS user_registrations (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, email TEXT, phone TEXT, status TEXT)");
    $db->exec("CREATE TABLE IF NOT EXISTS users (id TEXT PRIMARY KEY, name TEXT, balance REAL, tier TEXT)");
    $db->exec("CREATE TABLE IF NOT EXISTS app_feed_settings (setting_key TEXT PRIMARY KEY, setting_value TEXT)");

    // Handle Settings Update
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'admin_update_settings') {
        if (!validate_csrf($_POST['csrf_token'] ?? '')) die("CSRF validation failed");
        
        $up_url = trim($_POST['api_url'] ?? '');
        $up_key = trim($_POST['secret_key'] ?? '');
        $up_status = trim($_POST['system_status'] ?? 'Operational');
        $up_tier = trim($_POST['min_withdrawal_tier'] ?? 'Bronze Tier');

        $stmt = $db->prepare("INSERT OR REPLACE INTO app_feed_settings (setting_key, setting_value) VALUES (?, ?)");
        $stmt->execute(['api_url', $up_url]);
        $stmt->execute(['secret_key', $up_key]);
        $stmt->execute(['system_status', $up_status]);
        $stmt->execute(['min_withdrawal_tier', $up_tier]);

        header("Location: admin.php?status=settings_updated");
        exit();
    }

    // --- IMPLEMENTED: Background Management Logic with Debugging ---
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && in_array($_POST['action'], ['admin_upload_bg', 'admin_update_color', 'admin_reset_bg'])) {
        if (!validate_csrf($_POST['csrf_token'] ?? '')) die("CSRF validation failed");
        $code = strtolower(trim($_POST['country_code']));
        $page = $_POST['page_type'] ?? 'index';

        if ($_POST['action'] === 'admin_upload_bg') {
            if (!isset($_FILES['bg_image']) || $_FILES['bg_image']['error'] !== 0) {
                die("Error: No file uploaded or upload error code: " . ($_FILES['bg_image']['error'] ?? 'N/A'));
            }
            $target_dir = __DIR__ . "/assets/bg/";
            if (!is_dir($target_dir)) mkdir($target_dir, 0755, true);
            $file_name = $page . "_" . $code . ".png";
            $target_file = $target_dir . $file_name;
            
            if (move_uploaded_file($_FILES['bg_image']['tmp_name'], $target_file)) {
                chmod($target_file, 0644);
                // Store path with leading slash to ensure it is always absolute to root
                $db_path = "/assets/bg/" . $file_name;
                $stmt = $db->prepare("INSERT OR REPLACE INTO app_feed_settings (setting_key, setting_value) VALUES (?, ?)");
                $stmt->execute(['bg_' . $page . '_' . $code, $db_path]);
            } else {
                die("Error: Failed to move file to " . $target_file . ". Check folder write permissions (CHMOD 755).");
            }
        } elseif ($_POST['action'] === 'admin_update_color') {
            $stmt = $db->prepare("INSERT OR REPLACE INTO app_feed_settings (setting_key, setting_value) VALUES (?, ?)");
            $stmt->execute(['bg_color_' . $code, $_POST['new_color']]);
        } elseif ($_POST['action'] === 'admin_reset_bg') {
            $stmt = $db->prepare("DELETE FROM app_feed_settings WHERE setting_key = ?");
            $stmt->execute(['bg_' . $page . '_' . $code]);
        }
        die("SUCCESS"); 
    }

    // Handle User Approval
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['approve_user']) && isset($_POST['target_uid'])) {
        $stmt = $db->prepare("SELECT username FROM user_registrations WHERE id = ?");
        $stmt->execute([$_POST['target_uid']]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($user) {
            $db->prepare("INSERT OR REPLACE INTO users (id, name, balance, tier) VALUES (?, ?, 0.00, 'Bronze Tier')")
           ->execute([$_POST['target_uid'], $user['username']]);
        }
    }

    // Add this handler to admin.php
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'admin_update_withdrawal') {
        if (!validate_csrf($_POST['csrf_token'] ?? '')) die("CSRF validation failed");
        
        $uid = $_POST['target_uid'];
        $locked = ($_POST['withdrawal_access'] === '1') ? 1 : 0;
        
        // This updates/creates the record that cdashboard.php reads
        $stmt = $db->prepare("INSERT OR REPLACE INTO user_settings (user_id, withdrawal_locked) VALUES (?, ?)");
        $stmt->execute([$uid, $locked]);
        
        header("Location: admin.php?status=status_updated");
        exit();
    }

    // Fetch Settings
    $currentSettings = $db->query("SELECT setting_key, setting_value FROM app_feed_settings")->fetchAll(PDO::FETCH_KEY_PAIR);
    
    // Fix: Ensure every key is defined to prevent "Undefined array key" warnings
    if (!isset($currentSettings['api_url'])) $currentSettings['api_url'] = '';
    if (!isset($currentSettings['secret_key'])) $currentSettings['secret_key'] = '';
    if (!isset($currentSettings['system_status'])) $currentSettings['system_status'] = 'Operational';
    if (!isset($currentSettings['min_withdrawal_tier'])) $currentSettings['min_withdrawal_tier'] = 'Bronze Tier'; 
    
    $systemStatus = $currentSettings['system_status'];

    // FIX: Fetch users from user_registrations
    $allUsers = $db->query("SELECT * FROM user_registrations ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);

    // Dashboard Data
    $totalLogs = 0;
    $totalVolume = 0;
    $tableCheck = $db->query("SELECT name FROM sqlite_master WHERE type='table' AND name='momo_transactions'");
    if ($tableCheck->fetch()) {
        $totalLogs = $db->query("SELECT COUNT(*) FROM momo_transactions")->fetchColumn();
        $totalVolume = $db->query("SELECT SUM(amount) FROM momo_transactions WHERE status LIKE '%Completed%'")->fetchColumn() ?: 0;
    }

} catch (PDOException $e) {
    die("Database Error: " . $e->getMessage());
}
// --- SECURITY: GATEKEEPER END ---


// --- CONTENT ARRAYS ---
$names = ["Sarah Jenkins", "Michael Osei", "Chidi Okafor", "Amara Adeyemi", "David Mensah", "Elena Rodriguez", "Fatima Bello", "Samuel Tetteh", "Kwame Boateng", "Patience Akoto"];
// Mapping names to icons
$name_icons = [
    "Sarah Jenkins" => "👩‍💼", "Michael Osei" => "👨‍💻", "Chidi Okafor" => "👤", 
    "Amara Adeyemi" => "👩‍🔬", "David Mensah" => "👨‍💼", "Elena Rodriguez" => "👩‍🎨", 
    "Fatima Bello" => "👩‍💻", "Samuel Tetteh" => "👨‍🚀", "Kwame Boateng" => "👨‍🔬", "Patience Akoto" => "👩‍🎓"
];
$comments = [
    "Just hit my first payout, incredibly fast service!",
    "The new updates are absolutely game-changing. Great work team.",
    "Reliability is 10/10. So happy to be part of this community.",
    "Consistency is key! Another successful milestone reached today.",
    "This platform has truly simplified how I handle my transactions.",
    "Seeing real growth and sustainable results every single week.",
    "So grateful for the support and the transparent system.",
    "Achieved my financial target for the month, thanks to this team!"
];

// admin.php - Complete Platform Oversight & Control Panel

try {
    $db = new PDO('sqlite:app_feed.db');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $db->exec("CREATE TABLE IF NOT EXISTS application_comments (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT, flag TEXT, tier TEXT, txt TEXT, avatar_icon TEXT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )");

    // Fix for missing avatar_icon column in existing database
    $columns = $db->query("PRAGMA table_info(application_comments)")->fetchAll(PDO::FETCH_COLUMN, 1);
    if (!in_array('avatar_icon', $columns)) {
        $db->exec("ALTER TABLE application_comments ADD COLUMN avatar_icon TEXT DEFAULT '👤'");
    }

    $db->exec("CREATE TABLE IF NOT EXISTS user_registrations (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        username TEXT,
        email TEXT,
        phone TEXT,
        status TEXT DEFAULT 'Pending',
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )");

    $db->exec("CREATE TABLE IF NOT EXISTS admin_broadcasts (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT,
        tier TEXT,
        message TEXT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )");

    // --- APPROVAL, SUSPENSION & DELETION LOGIC ---
    // ... [KEEP ALL YOUR EXISTING LOGIC HERE] ...

    $db->exec("CREATE TABLE IF NOT EXISTS app_feed_settings (
        setting_key TEXT PRIMARY KEY,
        setting_value TEXT
    )");

    $chkSettings = $db->query("SELECT COUNT(*) FROM app_feed_settings")->fetchColumn();
    if ($chkSettings == 0) {
        $db->exec("INSERT INTO app_feed_settings (setting_key, setting_value) VALUES ('api_url', 'https://api.gateway.com/webhook')");
        $db->exec("INSERT INTO app_feed_settings (setting_key, setting_value) VALUES ('secret_key', 'YOUR_GATEWAY_SECRET_KEY')");
        $db->exec("INSERT INTO app_feed_settings (setting_key, setting_value) VALUES ('system_status', 'Operational')");
    }

    // ... [KEEP ALL YOUR OTHER POST HANDLERS HERE] ...

    $db->exec("CREATE TABLE IF NOT EXISTS momo_transactions (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        phone TEXT,
        amount REAL,
        frequency TEXT,
        status TEXT DEFAULT 'Pending',
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )");

    // --- INSERT FETCHING CODE HERE ---
    $totalVolume = $db->query("SELECT SUM(amount) FROM momo_transactions WHERE status LIKE '%Completed%'")->fetchColumn() ?: 0;
    $allTransactions = $db->query("SELECT * FROM momo_transactions ORDER BY id DESC LIMIT 50")->fetchAll(PDO::FETCH_ASSOC);
    $currentSettings = $db->query("SELECT setting_key, setting_value FROM app_feed_settings")->fetchAll(PDO::FETCH_KEY_PAIR);
    $totalComments = $db->query("SELECT COUNT(*) FROM application_comments")->fetchColumn();
    $allUsers = $db->query("SELECT * FROM user_registrations ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    die("Critical Admin Oversight Database Connection Error: " . $e->getMessage());
}
// --- SECURITY: GATEKEEPER END ---

// --- CONTENT ARRAYS ---
$names = ["Sarah Jenkins", "Michael Osei", "Chidi Okafor", "Amara Adeyemi", "David Mensah", "Elena Rodriguez", "Fatima Bello", "Samuel Tetteh", "Kwame Boateng", "Patience Akoto"];
// Mapping names to icons
$name_icons = [
    "Sarah Jenkins" => "👩‍💼", "Michael Osei" => "👨‍💻", "Chidi Okafor" => "👤", 
    "Amara Adeyemi" => "👩‍🔬", "David Mensah" => "👨‍💼", "Elena Rodriguez" => "👩‍🎨", 
    "Fatima Bello" => "👩‍💻", "Samuel Tetteh" => "👨‍🚀", "Kwame Boateng" => "👨‍🔬", "Patience Akoto" => "👩‍🎓"
];
$comments = [
    "Just hit my first payout, incredibly fast service!",
    "The new updates are absolutely game-changing. Great work team.",
    "Reliability is 10/10. So happy to be part of this community.",
    "Consistency is key! Another successful milestone reached today.",
    "This platform has truly simplified how I handle my transactions.",
    "Seeing real growth and sustainable results every single week.",
    "So grateful for the support and the transparent system.",
    "Achieved my financial target for the month, thanks to this team!"
];

// admin.php - Complete Platform Oversight & Control Panel

try {
    $db = new PDO('sqlite:app_feed.db');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $db->exec("CREATE TABLE IF NOT EXISTS application_comments (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT, flag TEXT, tier TEXT, txt TEXT, avatar_icon TEXT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )");

    // Fix for missing avatar_icon column in existing database
    $columns = $db->query("PRAGMA table_info(application_comments)")->fetchAll(PDO::FETCH_COLUMN, 1);
    if (!in_array('avatar_icon', $columns)) {
        $db->exec("ALTER TABLE application_comments ADD COLUMN avatar_icon TEXT DEFAULT '👤'");
    }

    $db->exec("CREATE TABLE IF NOT EXISTS user_registrations (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        username TEXT,
        email TEXT,
        phone TEXT,
        status TEXT DEFAULT 'Pending',
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )");

    $db->exec("CREATE TABLE IF NOT EXISTS admin_broadcasts (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT,
        tier TEXT,
        message TEXT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )");

    // --- APPROVAL, SUSPENSION & DELETION LOGIC ---
    if (isset($_GET['approve_user_id'])) {
        $id = intval($_GET['approve_user_id']);
        if (validate_csrf($_GET['token'] ?? '')) {
            $db->prepare("UPDATE user_registrations SET status = 'Active' WHERE id = :id")->execute([':id' => $id]);
            header("Location: admin.php?status=user_approved");
            exit();
        }
    }

    if (isset($_GET['suspend_user_id'])) {
        $id = intval($_GET['suspend_user_id']);
        if (validate_csrf($_GET['token'] ?? '')) {
            $db->prepare("UPDATE user_registrations SET status = 'Suspended' WHERE id = :id")->execute([':id' => $id]);
            header("Location: admin.php?status=user_suspended");
            exit();
        }
    }

    if (isset($_GET['delete_user_id'])) {
        $id = intval($_GET['delete_user_id']);
        if (validate_csrf($_GET['token'] ?? '')) {
            $db->prepare("DELETE FROM user_registrations WHERE id = :id")->execute([':id' => $id]);
            header("Location: admin.php?status=user_deleted");
            exit();
        }
    }

    $db->exec("CREATE TABLE IF NOT EXISTS app_feed_settings (
        setting_key TEXT PRIMARY KEY,
        setting_value TEXT
    )");

    $chkSettings = $db->query("SELECT COUNT(*) FROM app_feed_settings")->fetchColumn();
    if ($chkSettings == 0) {
        $db->exec("INSERT INTO app_feed_settings (setting_key, setting_value) VALUES ('api_url', 'https://api.gateway.com/webhook')");
        $db->exec("INSERT INTO app_feed_settings (setting_key, setting_value) VALUES ('secret_key', 'YOUR_GATEWAY_SECRET_KEY')");
        $db->exec("INSERT INTO app_feed_settings (setting_key, setting_value) VALUES ('system_status', 'Operational')");
    }

    // Handle Settings Update
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'admin_update_settings') {
        if (!validate_csrf($_POST['csrf_token'] ?? '')) die("CSRF validation failed");
        
        $up_url = $_POST['api_url'];
        $up_key = $_POST['secret_key'];

        $setStmt1 = $db->prepare("UPDATE app_feed_settings SET setting_value = :val WHERE setting_key = 'api_url'");
        $setStmt1->execute([':val' => $up_url]);

        $setStmt2 = $db->prepare("UPDATE app_feed_settings SET setting_value = :val WHERE setting_key = 'secret_key'");
        $setStmt2->execute([':val' => $up_key]);

        header("Location: admin.php?status=settings_updated");
        exit();
    }

    // Handle Admin Broadcast Message
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'admin_post_broadcast') {
        if (!validate_csrf($_POST['csrf_token'] ?? '')) die("CSRF validation failed");
        $name = strip_tags($_POST['admin_name']);
        $tier = strip_tags($_POST['admin_tier']);
        $msg = strip_tags($_POST['admin_message']);
        $stmt = $db->prepare("INSERT INTO admin_broadcasts (name, tier, message) VALUES (:name, :tier, :msg)");
        $stmt->execute([':name' => $name, ':tier' => $tier, ':msg' => $msg]);
        header("Location: admin.php?status=broadcasted");
        exit();
    }

    // Handle Admin Posting to Index
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'admin_post_comment') {
        if (!validate_csrf($_POST['csrf_token'] ?? '')) die("CSRF validation failed");
        
        $name = $_POST['comment_name'];
        $tier = strip_tags($_POST['comment_tier']);
        $txt = $_POST['comment_txt'];
        $avatar = $name_icons[$name] ?? '👤'; // Auto-select icon
        
        $flag = "User"; 
        $stmt = $db->prepare("INSERT INTO application_comments (name, flag, tier, txt, avatar_icon) VALUES (:name, :flag, :tier, :txt, :avatar)");
        $stmt->execute([':name' => $name, ':flag' => $flag, ':tier' => $tier, ':txt' => $txt, ':avatar' => $avatar]);
        header("Location: admin.php?status=broadcasted");
        exit();
    }

    // Handle Comment Deletion
    if (isset($_GET['delete_comment_id'])) {
        if (validate_csrf($_GET['token'] ?? '')) {
            $deleteId = intval($_GET['delete_comment_id']);
            $stmt = $db->prepare("DELETE FROM application_comments WHERE id = :id");
            $stmt->execute([':id' => $deleteId]);
            header("Location: admin.php?status=moderated");
            exit();
        }
    }

    // Global Clear Operations
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'admin_clear_all_logs') {
        if (!validate_csrf($_POST['csrf_token'] ?? '')) die("CSRF validation failed");
        $target_table = $_POST['target_table'];
        if ($target_table === 'application_comments') {
            $db->exec("DELETE FROM application_comments");
            $db->exec("DELETE FROM sqlite_sequence WHERE name='application_comments'");
            header("Location: admin.php?status=comments_cleared");
            exit();
        } elseif ($target_table === 'momo_transactions') {
            $db->exec("DELETE FROM momo_transactions");
            $db->exec("DELETE FROM sqlite_sequence WHERE name='momo_transactions'");
            header("Location: admin.php?status=momo_cleared");
            exit();
        }
    }

    // Inline Edit
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'admin_edit_comment_inline') {
        if (!validate_csrf($_POST['csrf_token'] ?? '')) die("CSRF validation failed");
        $comment_id = intval($_POST['comment_id']);
        $new_name = strip_tags($_POST['edit_name']);
        $new_tier = strip_tags($_POST['edit_tier']);
        $new_txt = strip_tags($_POST['edit_txt']);
        
        $update_stmt = $db->prepare("UPDATE application_comments SET name = :name, tier = :tier, txt = :txt WHERE id = :id");
        $update_stmt->execute([
            ':name' => $new_name,
            ':tier' => $new_tier,
            ':txt'  => $new_txt,
            ':id'   => $comment_id
        ]);
        header("Location: admin.php?status=entry_updated");
        exit();
    }

    $totalComments = $db->query("SELECT COUNT(*) FROM application_comments")->fetchColumn();
    $allComments = $db->query("SELECT * FROM application_comments ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);
    $allUsers = $db->query("SELECT * FROM user_registrations ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);

    $db->exec("CREATE TABLE IF NOT EXISTS momo_transactions (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        phone TEXT,
        amount REAL,
        frequency TEXT,
        status TEXT DEFAULT 'Pending',
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )");

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'admin_momo_payout') {
        if (!validate_csrf($_POST['csrf_token'] ?? '')) die("CSRF validation failed");
        $phone = strip_tags($_POST['phone']);
        $amount = floatval($_POST['amount']);
        $frequency = strip_tags($_POST['frequency']);
        
        $settQuery = $db->query("SELECT setting_key, setting_value FROM app_feed_settings")->fetchAll(PDO::FETCH_KEY_PAIR);
        $api_url = !empty($settQuery['api_url']) ? $settQuery['api_url'] : "https://api.gateway.com/webhook"; 
        $secret_key = !empty($settQuery['secret_key']) ? $settQuery['secret_key'] : "YOUR_GATEWAY_SECRET_KEY"; 

        $payment_data = [
            "amount" => $amount,
            "currency" => "USD",
            "user_identifier" => $phone,
            "tx_ref" => "tx-" . uniqid(),
            "email" => "user@example.com"
        ];

        $ch = curl_init($api_url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payment_data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "Authorization: Bearer " . $secret_key,
            "Content-Type: application/json"
        ]);

        $response = curl_exec($ch);
        curl_close($ch);
        $result = json_decode($response, true);

        $status = (is_array($result) && isset($result['status']) && $result['status'] === 'success') ? 'Completed (Admin Triggered)' : 'Failed (Gateway Rejected)';
        $redirect_status = (strpos($status, 'Completed') !== false) ? "momo_fired" : "momo_failed";

        $momoStmt = $db->prepare("INSERT INTO momo_transactions (phone, amount, frequency, status) VALUES (:phone, :amount, :frequency, :status)");
        $momoStmt->execute([':phone' => $phone, ':amount' => $amount, ':frequency' => $frequency, ':status' => $status]);

        header("Location: admin.php?status=" . $redirect_status);
        exit();
    }

    $totalVolume = $db->query("SELECT SUM(amount) FROM momo_transactions WHERE status LIKE '%Completed%'")->fetchColumn() ?: 0;
    $allTransactions = $db->query("SELECT * FROM momo_transactions ORDER BY id DESC LIMIT 50")->fetchAll(PDO::FETCH_ASSOC);
    $currentSettings = $db->query("SELECT setting_key, setting_value FROM app_feed_settings")->fetchAll(PDO::FETCH_KEY_PAIR);

} catch (PDOException $e) {
    die("Critical Admin Oversight Database Connection Error: " . $e->getMessage());
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Central Control Panel - Admin Oversight</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&display=swap');
        body { font-family: 'Plus Jakarta Sans', sans-serif; background: #0b0f19; color: #f3f4f6; margin: 0; padding: 40px 20px; display: flex; justify-content: center; }
        .admin-wrapper { width: 100%; max-width: 900px; background: linear-gradient(145deg, rgba(22, 30, 49, 0.9) 0%, rgba(15, 22, 36, 1) 100%); border: 1px solid rgba(255, 255, 255, 0.05); border-radius: 20px; padding: 32px; box-shadow: 0 20px 50px rgba(0,0,0,0.5); }
        h1 { font-size: 28px; font-weight: 800; margin-top: 0; background: linear-gradient(135deg, #ffffff 40%, #a7f3d0 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; display: flex; align-items: center; gap: 12px; }
        .analytics-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 32px; margin-top: 24px; }
        .card { background: rgba(10, 15, 26, 0.6); border: 1px solid rgba(255, 255, 255, 0.06); padding: 20px; border-radius: 14px; }
        .card h3 { margin: 0 0 8px 0; font-size: 12px; color: #9ca3af; text-transform: uppercase; letter-spacing: 1px; }
        .card .metric { font-size: 32px; font-weight: 800; color: #10b981; }
        .section-title { font-size: 18px; font-weight: 700; margin-bottom: 16px; color: #ffffff; border-bottom: 1px solid rgba(255, 255, 255, 0.08); padding-bottom: 8px; display: flex; justify-content: space-between; align-items: center; }
        table { width: 100%; border-collapse: collapse; text-align: left; margin-top: 12px; }
        th { padding: 14px; font-size: 12px; text-transform: uppercase; color: #9ca3af; letter-spacing: 0.5px; background: rgba(255, 255, 255, 0.02); border-bottom: 2px solid rgba(255, 255, 255, 0.05); }
        td { padding: 14px; font-size: 14px; border-bottom: 1px solid rgba(255, 255, 255, 0.04); color: #e5e7eb; }
        tr:hover td { background: rgba(255, 255, 255, 0.01); }
        .badge { font-size: 11px; font-weight: 700; padding: 4px 8px; border-radius: 6px; background: rgba(16, 185, 129, 0.15); color: #a7f3d0; }
        .btn-delete { background: rgba(239, 68, 68, 0.15); color: #fca5a5; border: 1px solid rgba(239, 68, 68, 0.3); padding: 6px 12px; border-radius: 8px; text-decoration: none; font-size: 12px; font-weight: 600; cursor: pointer; }
        .btn-delete:hover { background: #ef4444; color: #ffffff; }
        .btn-edit-trigger { background: rgba(245, 158, 11, 0.15); color: #fcd34d; border: 1px solid rgba(245, 158, 11, 0.3); padding: 6px 12px; border-radius: 8px; cursor: pointer; font-size: 12px; font-weight: 600; }
        .btn-clear-global { background: linear-gradient(135deg, #dc2626 0%, #7f1d1d 100%) !important; border: none; color: white; padding: 6px 12px; font-size: 11px; font-weight: 700; text-transform: uppercase; border-radius: 6px; cursor: pointer; }
        .inline-edit-row input { background: #090d16; border: 1px solid rgba(255,255,255,0.2); color: #fff; padding: 4px 8px; border-radius: 6px; font-family: inherit; font-size: 13px; width: 90%; }
        .btn-inline-save { background: #10b981; color: #fff; border: none; padding: 4px 8px; border-radius: 4px; font-weight: 700; cursor: pointer; font-size: 11px; }
        .alert-success { padding: 12px 16px; background: rgba(16, 185, 129, 0.15); border: 1px solid #10b981; color: #a7f3d0; border-radius: 10px; font-size: 14px; margin-bottom: 20px; }
        .alert-danger { padding: 12px 16px; background: rgba(239, 68, 68, 0.15); border: 1px solid #ef4444; color: #fca5a5; border-radius: 10px; font-size: 14px; margin-bottom: 20px; }
        .dashboard-split-grid { display: grid; grid-template-columns: 1fr; gap: 32px; margin-top: 24px; margin-bottom: 32px; }
        @media (min-width: 850px) { .dashboard-split-grid { grid-template-columns: 320px 1fr; } }
        .admin-form-box { background: rgba(10, 15, 26, 0.4); border: 1px dashed rgba(16, 185, 129, 0.3); border-radius: 14px; padding: 20px; }
        .form-group { margin-bottom: 16px; }
        .form-group label { display: block; font-size: 11px; color: #9ca3af; text-transform: uppercase; margin-bottom: 6px; font-weight: 600; }
        .admin-form-box input, .admin-form-box select { width: 100%; padding: 10px 12px; background: #090d16; border: 1px solid rgba(255,255,255,0.1); color: #fff; border-radius: 8px; box-sizing: border-box; }
        .admin-form-box button { width: 100%; padding: 12px; background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%); color: #fff; border: none; font-weight: 700; border-radius: 8px; cursor: pointer; }
        .momo-badge { font-size: 10px; font-weight: 700; padding: 2px 6px; border-radius: 4px; background: rgba(59, 130, 246, 0.15); color: #93c5fd; }
    </style>
</head>
<body>

<div class="admin-wrapper">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
        <h1>⚙️ Platform Control Dashboard</h1>
        <div style="display: flex; align-items: center; white-space: nowrap;">
            <a href="manage_branding.php" style="background: #8b5cf6; color: white; padding: 8px 15px; text-decoration: none; font-size: 14px; font-weight: 600; border-radius: 5px; margin-right: 15px;">Branding</a>
            <a href="manage_region.php" style="background: #10b981; color: white; padding: 8px 15px; text-decoration: none; font-size: 14px; font-weight: 600; border-radius: 5px; margin-right: 15px;">Manage Regions</a>
            <a href="dashboard.php?view=admin" style="color: #60a5fa; text-decoration: none; font-size: 14px; font-weight: 600; margin-right: 15px;">Login</a>
            <a href="index.php" style="color: #60a5fa; text-decoration: none; font-size: 14px; font-weight: 600; margin-right: 15px;">← Back to App</a>
            <a href="logout.php" style="background: #f87171; color: white; padding: 8px 15px; text-decoration: none; font-size: 14px; font-weight: 600; border-radius: 5px;">Logout</a>
        </div>
    </div>



    <?php if (isset($_GET['status'])): ?>
        <?php if ($_GET['status'] == 'user_approved'): ?> <div class="alert-success">✓ User account approved.</div> <?php endif; ?>
        <?php if ($_GET['status'] == 'user_suspended'): ?> <div class="alert-danger">⚠️ User account suspended.</div> <?php endif; ?>
        <?php if ($_GET['status'] == 'user_deleted'): ?> <div class="alert-danger">🗑️ User deleted.</div> <?php endif; ?>
        <?php if ($_GET['status'] == 'moderated'): ?> <div class="alert-success">✓ Entry purged.</div> <?php endif; ?>
        <?php if ($_GET['status'] == 'comments_cleared'): ?> <div class="alert-success">🗑️ Comments wiped.</div> <?php endif; ?>
        <?php if ($_GET['status'] == 'momo_cleared'): ?> <div class="alert-success">🗑️ MoMo logs cleared.</div> <?php endif; ?>
        <?php if ($_GET['status'] == 'entry_updated'): ?> <div class="alert-success">✏️ Profile updated.</div> <?php endif; ?>
        <?php if ($_GET['status'] == 'settings_updated'): ?> <div class="alert-success">⚙️ Gateway updated.</div> <?php endif; ?>
        <?php if ($_GET['status'] == 'momo_fired'): ?> <div class="alert-success">⚡ MoMo request fired.</div> <?php endif; ?>
        <?php if ($_GET['status'] == 'momo_failed'): ?> <div class="alert-danger">❌ Transaction failed.</div> <?php endif; ?>
        <?php if ($_GET['status'] == 'broadcasted'): ?> <div class="alert-success">📢 Message broadcasted.</div> <?php endif; ?>
    <?php endif; ?>

<div class="analytics-grid">
        <div class="card"><h3>Total Feed Logs</h3><div class="metric"><?php echo $totalComments; ?></div></div>
        <div class="card"><h3>System Status</h3><div class="metric" style="color: #3b82f6;"><?php echo htmlspecialchars($currentSettings['system_status'] ?? 'Operational'); ?></div></div>
        <div class="card"><h3>Database</h3><div class="metric" style="color: #f59e0b;">SQLite3</div></div>
        <div class="card"><h3>Volume</h3><div class="metric" style="color: #10b981;">$<?php echo number_format($totalVolume, 2); ?></div></div>
    </div>

    <div class="section-title">Admin Broadcast (To Index Comments)</div>
    <div class="admin-form-box" style="margin-bottom: 32px; border-color: rgba(59, 130, 246, 0.4);">
        <form action="admin.php" method="POST">
            <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
            <input type="hidden" name="action" value="admin_post_comment">
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                <div class="form-group">
                    <label>Display Name</label>
                    <select name="comment_name" required>
                        <?php foreach ($names as $n): ?>
                            <option value="<?php echo htmlspecialchars($n); ?>"><?php echo htmlspecialchars($n); ?> <?php echo $name_icons[$n] ?? '👤'; ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>Display Tier</label>
                    <select name="comment_tier" required>
                        <option value="Silver Member">Silver Member</option>
                        <option value="Gold Member">Gold Member</option>
                        <option value="Premier Member">Premier Member</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label>Message</label>
                <select name="comment_txt" required>
                    <?php foreach ($comments as $c): ?>
                        <option value="<?php echo htmlspecialchars($c); ?>"><?php echo htmlspecialchars($c); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <button type="submit" style="background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);">Send Broadcast</button>
        </form>
    </div>

    <div class="section-title">User Accounts</div>
    <div class="admin-form-box" style="margin-bottom: 32px;">
        <table>
            <thead><tr><th>Username</th><th>Email</th><th>Phone</th><th>Status</th><th>Action</th></tr></thead>
            <tbody>
                <?php foreach ($allUsers as $user): ?>
                    <tr>
                        <td><strong><?php echo htmlspecialchars($user['username'] ?? ''); ?></strong></td>
                        <td><?php echo htmlspecialchars($user['email'] ?? ''); ?></td>
                        <td><?php echo htmlspecialchars($user['phone'] ?? ''); ?></td>
                        <td><span class="badge"><?php echo htmlspecialchars($user['status'] ?? ''); ?></span></td>
                        <td>
                            <?php if (($user['status'] ?? '') !== 'Active'): ?>
                                <a href="admin.php?approve_user_id=<?php echo $user['id']; ?>&token=<?php echo $_SESSION['csrf_token']; ?>" class="btn-inline-save" style="text-decoration:none;">Approve</a>
                            <?php endif; ?>
                            <?php if (($user['status'] ?? '') !== 'Suspended'): ?>
                                <a href="admin.php?suspend_user_id=<?php echo $user['id']; ?>&token=<?php echo $_SESSION['csrf_token']; ?>" class="btn-delete" style="text-decoration:none; background:rgba(245, 158, 11, 0.15); color:#fcd34d; border-color:rgba(245, 158, 11, 0.3);">Suspend</a>
                            <?php endif; ?>
                            <a href="admin.php?delete_user_id=<?php echo $user['id']; ?>&token=<?php echo $_SESSION['csrf_token']; ?>" class="btn-delete" style="text-decoration:none;" onclick="return confirm('Delete this user?');">Delete</a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>


<div class="card" style="margin-top:20px;">
    <h3>Global Security Adjustments</h3>
    <form method="POST" class="admin-form-inline">
        <input type="hidden" name="action" value="admin_update_settings">
        <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
        
        <select name="min_withdrawal_tier" style="padding: 10px; border-radius: 8px;">
            <option value="Bronze Tier" <?php echo (($currentSettings['min_withdrawal_tier'] ?? '') == 'Bronze Tier') ? 'selected' : ''; ?>>Bronze Tier</option>
            <option value="Silver Tier" <?php echo (($currentSettings['min_withdrawal_tier'] ?? '') == 'Silver Tier') ? 'selected' : ''; ?>>Silver Tier</option>
            <option value="Gold Tier" <?php echo (($currentSettings['min_withdrawal_tier'] ?? '') == 'Gold Tier') ? 'selected' : ''; ?>>Gold Tier</option>
            <option value="Platinum VIP" <?php echo (($currentSettings['min_withdrawal_tier'] ?? '') == 'Platinum VIP') ? 'selected' : ''; ?>>Platinum VIP</option>
        </select>
        
        <button type="submit" class="btn-action btn-enabled" style="width:auto; padding: 10px 20px;">Save Policy</button>
    </form>
</div>


<div class="section-title">Gateway Configurations</div>
<div class="admin-form-box" style="margin-bottom: 32px; border-color: rgba(245, 158, 11, 0.4);">
    <form action="admin.php" method="POST">
        <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
        <input type="hidden" name="action" value="admin_update_settings">
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
            <div class="form-group">
                <label>API URL</label>
                <div style="position: relative; display: flex; align-items: center;">
                    <input type="password" id="api_url_field" name="api_url" value="<?php echo htmlspecialchars($currentSettings['api_url'] ?? ''); ?>" required style="padding-right: 40px; width: 100%;">
                    <span id="toggle_url" onclick="toggleVisibility('api_url_field', 'toggle_url')" style="position: absolute; right: 10px; cursor: pointer; font-size: 1.2rem;">🔒</span>
                </div>
            </div>
            <div class="form-group">
                <label>Secret Key</label>
                <div style="position: relative; display: flex; align-items: center;">
                    <input type="password" id="secret_key_field" name="secret_key" value="<?php echo htmlspecialchars($currentSettings['secret_key'] ?? ''); ?>" required style="padding-right: 40px; width: 100%;">
                    <span id="toggle_key" onclick="toggleVisibility('secret_key_field', 'toggle_key')" style="position: absolute; right: 10px; cursor: pointer; font-size: 1.2rem;">🔒</span>
                </div>
            </div>
        </div>
        <button type="submit" style="background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); width: auto; padding: 10px 24px; margin-top: 15px;">Update API Gateway</button>
    </form>
</div>
<script>
function toggleVisibility(fieldId, toggleId) {
    const field = document.getElementById(fieldId);
    const toggle = document.getElementById(toggleId);
    if (field.type === "password") {
        field.type = "text";
        toggle.textContent = "🔓";
    } else {
        field.type = "password";
        toggle.textContent = "🔒";
    }
}
</script>
<form method="POST" action="admin.php" class="admin-form-box">
    <input type="hidden" name="action" value="admin_update_settings">
    <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">

    <label>API URL:</label><br>
    <input type="text" name="api_url" value="<?php echo htmlspecialchars($currentSettings['api_url'] ?? ''); ?>"><br>

    <label>Secret Key:</label><br>
    <input type="text" name="secret_key" value="<?php echo htmlspecialchars($currentSettings['secret_key'] ?? ''); ?>"><br>

    <label>System Status:</label><br>
    <select name="system_status">
        <option value="Operational" <?php echo ($systemStatus === 'Operational') ? 'selected' : ''; ?>>Operational</option>
        <option value="Maintenance" <?php echo ($systemStatus === 'Maintenance') ? 'selected' : ''; ?>>Maintenance</option>
    </select><br><br>

    <button type="submit">Save Changes</button>
</form>

<div class="dashboard-split-grid">
    <div>
        <div class="section-title">Trigger MoMo Execution</div>
        <div class="admin-form-box">
            <form action="admin.php" method="POST">
                <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                <input type="hidden" name="action" value="admin_momo_payout">
                <div class="form-group"><label>User ID / Registered Phone</label><input type="tel" name="phone" required></div>
                <div class="form-group"><label>Amount ($)</label><input type="number" name="amount" step="any" min="1" required></div>
                <div class="form-group"><label>Frequency</label>
                    <select name="frequency"><option value="instant_admin">Instant</option><option value="daily">Daily</option><option value="weekly">Weekly</option></select>
                </div>
                <button type="submit">Fire API</button>
            </form>
        </div>
    </div>

    <div>
        <div class="section-title">Audit Ledger
            <form action="admin.php" method="POST" onsubmit="return confirm('Wipe out logs?');">
                <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                <input type="hidden" name="action" value="admin_clear_all_logs">
                <input type="hidden" name="target_table" value="momo_transactions">
                <button type="submit" class="btn-clear-global">Clear All</button>
            </form>
        </div>
        <div style="max-height: 245px; overflow-y: auto; border: 1px solid rgba(255,255,255,0.05); border-radius: 14px; background: rgba(10, 15, 26, 0.2);">
            <table>
                <thead><tr><th>ID</th><th>Phone</th><th>Value</th><th>Status</th></tr></thead>
                <tbody>
                    <?php foreach ($allTransactions as $tx): ?>
                        <tr><td>#<?php echo $tx['id']; ?></td><td><?php echo htmlspecialchars($tx['phone']); ?></td><td style="color:#10b981;">$<?php echo number_format($tx['amount'], 2); ?></td><td><span class="momo-badge"><?php echo htmlspecialchars($tx['status']); ?></span></td></tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="section-title">Moderation Engine
    <form action="admin.php" method="POST" onsubmit="return confirm('Clear all comments?');">
        <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
        <input type="hidden" name="action" value="admin_clear_all_logs">
        <input type="hidden" name="target_table" value="application_comments">
        <button type="submit" class="btn-clear-global">Clear All</button>
    </form>
</div>

<table>
    <thead><tr><th>Icon</th><th>Origin</th><th>Author</th><th>Badge</th><th>Text</th><th style="text-align: right;">Action</th></tr></thead>
    <tbody>
        <?php foreach ($allComments as $row): ?>
            <tr id="row-view-<?php echo $row['id']; ?>">
                <td style="font-size: 24px;"><?php echo $row['avatar_icon']; ?></td>
                <td><?php echo htmlspecialchars($row['flag']); ?></td>
                <td><?php echo htmlspecialchars($row['name']); ?></td>
                <td><span class="badge"><?php echo htmlspecialchars($row['tier']); ?></span></td>
                <td style="font-style:italic;">"<?php echo htmlspecialchars($row['txt']); ?>"</td>
                <td style="text-align: right;">
                    <button type="button" class="btn-edit-trigger" onclick="toggleInlineEdit(<?php echo $row['id']; ?>)">Edit</button>
                    <a href="admin.php?delete_comment_id=<?php echo $row['id']; ?>&token=<?php echo $_SESSION['csrf_token']; ?>" class="btn-delete" onclick="return confirm('Purge this item?');">Purge</a>
                </td>
            </tr>
            <tr id="row-edit-<?php echo $row['id']; ?>" style="display: none;" class="inline-edit-row">
                <form action="admin.php" method="POST">
                    <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                    <input type="hidden" name="action" value="admin_edit_comment_inline">
                    <input type="hidden" name="comment_id" value="<?php echo $row['id']; ?>">
                    <td><?php echo $row['avatar_icon']; ?></td>
                    <td><?php echo htmlspecialchars($row['flag']); ?></td>
                    <td><input type="text" name="edit_name" value="<?php echo htmlspecialchars($row['name']); ?>"></td>
                    <td><input type="text" name="edit_tier" value="<?php echo htmlspecialchars($row['tier']); ?>"></td>
                    <td><input type="text" name="edit_txt" value="<?php echo htmlspecialchars($row['txt']); ?>"></td>
                    <td style="text-align: right;">
                        <button type="submit" class="btn-inline-save">Save</button>
                        <button type="button" class="btn-delete" onclick="toggleInlineEdit(<?php echo $row['id']; ?>)">Cancel</button>
                    </td>
                </form>
            </tr>
        <?php endforeach; ?>
    </tbody>
</table>

<script>
function toggleInlineEdit(rowId) {
    var v = document.getElementById('row-view-' + rowId);
    var e = document.getElementById('row-edit-' + rowId);
    v.style.display = (v.style.display === 'none') ? '' : 'none';
    e.style.display = (e.style.display === 'none') ? '' : 'none';
}
</script>
</html>


<style>
    /* Dashboard Modern Styling */
    .admin-form-box { background: rgba(255, 255, 255, 0.05); padding: 20px; border-radius: 12px; margin-bottom: 20px; border: 1px solid rgba(255, 255, 255, 0.1); }
    .form-group { margin-bottom: 15px; }
    .form-group label { display: block; margin-bottom: 5px; color: #aaa; font-size: 0.9em; }
    .form-group input, .form-group select { width: 100%; padding: 10px; background: #1a1a1a; border: 1px solid #333; color: white; border-radius: 6px; }
    .dashboard-split-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 30px; }
    .section-title { font-weight: bold; font-size: 1.2em; margin-bottom: 15px; display: flex; justify-content: space-between; align-items: center; }
    table { width: 100%; border-collapse: collapse; margin-top: 10px; }
    th { text-align: left; padding: 10px; border-bottom: 2px solid #333; color: #888; }
    td { padding: 12px; border-bottom: 1px solid #222; }
    button { padding: 10px 20px; background: #3b82f6; color: white; border: none; border-radius: 6px; cursor: pointer; }
    button:hover { background: #2563eb; }
    .btn-clear-global { background: #ef4444; font-size: 0.8em; }
    @media (max-width: 768px) { .dashboard-split-grid { grid-template-columns: 1fr; } }
</style>