<?php
session_start();

// ==========================================
// CONFIGURATION
// ==========================================
$db_host = 'localhost';
$db_user = 'yaar734828_mizan';
$db_pass = 'yaar734828_mizan';
$db_name = 'yaar734828_mizan';

// Database Table & Column mapping
$table_users    = 'shonu_subjects';
$col_uid        = 'id';       // User ID column
$col_phone      = 'mobile';    // Phone number column
$col_password   = 'pwd';       // Password column
$table_balance  = 'shonu_kaichila'; // Table storing balances
$col_bal_uid    = 'balakedara';     // UID in balance table
$col_balance    = 'motta';          // Balance column

// Admin Panel Login Credentials
$admin_user = 'admin';
$admin_pass = 'admin123';

// ==========================================
// NO AUTHENTICATION (REMOVED AS REQUESTED)
// ==========================================

// ==========================================
// DATABASE CONNECTION (AUTO-FINDER)
// ==========================================
$message = '';
$msg_type = 'success';
$pdo = null;

// List of all your known databases and passwords from your source code
$db_credentials = [
    ['host' => 'localhost', 'user' => 'yaar734828_mizan', 'pass' => 'yaar734828_mizan', 'name' => 'yaar734828_mizan'],
    ['host' => 'localhost', 'user' => 'teac11783_yarwin_1ani30', 'pass' => 'teac11783_yarwin_1ani30', 'name' => 'teac11783_yarwin_1ani30'],
    ['host' => 'localhost', 'user' => 'teac11783_6club', 'pass' => 'teac11783_6club', 'name' => 'teac11783_6club'],
    ['host' => 'localhost', 'user' => 'teac11783_tashanwin', 'pass' => 'teac11783_tashanwin', 'name' => 'teac11783_tashanwin'],
    ['host' => 'localhost', 'user' => 'teac11783_jaiclub', 'pass' => 'teac11783_jaiclub', 'name' => 'teac11783_jaiclub'],
    ['host' => 'localhost', 'user' => 'teac11783_jaiclub01', 'pass' => 'teac11783_jaiclub01', 'name' => 'teac11783_jaiclub01'],
    ['host' => 'localhost', 'user' => 'teac11783_13lgame', 'pass' => 'teac11783_13lgame', 'name' => 'teac11783_13lgame'],
    ['host' => 'localhost', 'user' => 'root', 'pass' => '', 'name' => 'yaar734828_mizan'], // local fallback
    ['host' => 'localhost', 'user' => 'root', 'pass' => '', 'name' => 'teac11783_yarwin_1ani30'], // local fallback
];

$connected_db = "";

foreach ($db_credentials as $cred) {
    try {
        $pdo = new PDO("mysql:host={$cred['host']};dbname={$cred['name']};charset=utf8mb4", $cred['user'], $cred['pass']);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $connected_db = $cred['name'];
        break; // Successfully connected, exit loop
    } catch (PDOException $e) {
        // Ignore and try the next one
        $pdo = null;
    }
}

if (!$pdo) {
    $message = "Auto-Connection Failed! None of your known database passwords worked. Please check cPanel and update the credentials manually.";
    $msg_type = 'error';
} else {
    // Optionally display which database we connected to for debugging
    // $message = "Connected successfully to database: " . $connected_db;
}

// ==========================================
// HANDLE ACTIONS
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($pdo)) {
    
    // Action: Update Balance
    if (isset($_POST['action']) && $_POST['action'] === 'update_balance') {
        $identifier_type = $_POST['identifier_type']; // 'uid' or 'phone'
        $identifier_val = trim($_POST['identifier_val']);
        $new_balance = floatval($_POST['new_balance']);
        
        $col = ($identifier_type === 'uid') ? $col_uid : $col_phone;
        
        try {
            // First find the User ID (UID)
            $stmt = $pdo->prepare("SELECT `$col_uid` FROM `$table_users` WHERE `$col` = :ident LIMIT 1");
            $stmt->execute(['ident' => $identifier_val]);
            $user_id = $stmt->fetchColumn();
            
            if ($user_id) {
                // Now update the balance in shonu_kaichila
                $stmt2 = $pdo->prepare("UPDATE `$table_balance` SET `$col_balance` = :balance WHERE `$col_bal_uid` = :uid");
                $stmt2->execute(['balance' => $new_balance, 'uid' => $user_id]);
                
                if ($stmt2->rowCount() > 0) {
                    $message = "Balance updated successfully for $identifier_type: $identifier_val";
                    $msg_type = 'success';
                } else {
                    // It's possible the user doesn't have a record in shonu_kaichila yet, let's insert it
                    $stmt3 = $pdo->prepare("INSERT INTO `$table_balance` (`$col_bal_uid`, `$col_balance`) VALUES (:uid, :balance)");
                    $stmt3->execute(['uid' => $user_id, 'balance' => $new_balance]);
                    $message = "Balance updated (new wallet created) for $identifier_type: $identifier_val";
                    $msg_type = 'success';
                }
            } else {
                $message = "User not found with $identifier_type: $identifier_val";
                $msg_type = 'error';
            }
        } catch (PDOException $e) {
            $message = "Error updating balance: " . $e->getMessage();
            $msg_type = 'error';
        }
    }
    
    // Action: Create Demo ID
    if (isset($_POST['action']) && $_POST['action'] === 'create_demo') {
        $demo_username = trim($_POST['demo_username']);
        $demo_password = trim($_POST['demo_password']); // Note: In production you might want password_hash()
        $initial_balance = floatval($_POST['initial_balance']);
        $demo_phone = trim($_POST['demo_phone']);
        
        try {
            // Check if username exists
            $check = $pdo->prepare("SELECT COUNT(*) FROM `$table_users` WHERE `$col_phone` = :user");
            $check->execute(['user' => $demo_username]);
            if ($check->fetchColumn() > 0) {
                $message = "Username/Mobile already exists!";
                $msg_type = 'error';
            } else {
                $status = 1;
                $createdate = date('Y-m-d H:i:s');
                $ip = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
                $code = rand(100000, 999999);
                $md5pass = md5($demo_password);

                // Insert new demo user
                $stmt = $pdo->prepare("INSERT INTO `$table_users` (`$col_phone`, `$col_password`, `status`, `createdate`, `ip`, `code`) VALUES (:user, :pass, :status, :cdate, :ip, :code)");
                $stmt->execute([
                    'user' => $demo_username, // Using mobile field as username
                    'pass' => $md5pass,
                    'status' => $status,
                    'cdate' => $createdate,
                    'ip' => $ip,
                    'code' => $code
                ]);
                $new_uid = $pdo->lastInsertId();
                
                // Set initial balance
                $stmt2 = $pdo->prepare("INSERT INTO `$table_balance` (`$col_bal_uid`, `$col_balance`) VALUES (:uid, :bal)");
                $stmt2->execute(['uid' => $new_uid, 'bal' => $initial_balance]);

                $message = "Demo account '$demo_username' created successfully!";
                $msg_type = 'success';
            }
        } catch (PDOException $e) {
            $message = "Error creating demo ID: " . $e->getMessage();
            $msg_type = 'error';
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Independent Admin Panel</title>
    <style>
        :root { --bg: #121212; --panel: #1e1e1e; --text: #e0e0e0; --primary: #007bff; --primary-hover: #0056b3; --success: #28a745; --error: #dc3545; --border: #333; }
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: var(--bg); color: var(--text); margin: 0; padding: 20px; }
        .container { max-width: 800px; margin: 0 auto; }
        .header { display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid var(--border); padding-bottom: 20px; margin-bottom: 20px; }
        h1 { margin: 0; font-size: 24px; }
        .logout-btn { background: #dc3545; color: white; text-decoration: none; padding: 8px 16px; border-radius: 4px; font-size: 14px; }
        .logout-btn:hover { background: #c82333; }
        
        .card { background: var(--panel); border-radius: 8px; padding: 25px; margin-bottom: 20px; box-shadow: 0 4px 6px rgba(0,0,0,0.3); border: 1px solid var(--border); }
        .card h3 { margin-top: 0; margin-bottom: 20px; border-bottom: 1px solid var(--border); padding-bottom: 10px; }
        
        .form-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; font-size: 14px; color: #bbb; }
        input[type="text"], input[type="password"], input[type="number"], select { width: 100%; padding: 10px; background: var(--bg); border: 1px solid var(--border); color: var(--text); border-radius: 4px; box-sizing: border-box; font-size: 15px; }
        input:focus, select:focus { outline: none; border-color: var(--primary); }
        
        .btn { background: var(--primary); color: white; border: none; padding: 10px 20px; border-radius: 4px; cursor: pointer; font-size: 15px; font-weight: bold; width: 100%; }
        .btn:hover { background: var(--primary-hover); }
        
        .alert { padding: 15px; border-radius: 4px; margin-bottom: 20px; font-weight: bold; }
        .alert-success { background: rgba(40, 167, 69, 0.2); color: #4dd86e; border: 1px solid var(--success); }
        .alert-error { background: rgba(220, 53, 69, 0.2); color: #ff6b7b; border: 1px solid var(--error); }
        
        .grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; }
    </style>
</head>
<body>

<div class="container">
    <div class="header">
        <h1>🛠️ Independent Admin</h1>
        <a href="?logout=1" class="logout-btn">Logout</a>
    </div>

    <?php if ($message): ?>
        <div class="alert alert-<?php echo $msg_type; ?>">
            <?php echo htmlspecialchars($message); ?>
        </div>
    <?php endif; ?>

    <!-- UPDATE BALANCE SECTION -->
    <div class="card">
        <h3>💰 Update User Balance</h3>
        <form method="POST">
            <input type="hidden" name="action" value="update_balance">
            <div class="grid-2">
                <div class="form-group">
                    <label>Search By</label>
                    <select name="identifier_type">
                        <option value="uid">User ID (UID)</option>
                        <option value="phone">Phone Number</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>ID or Phone Number</label>
                    <input type="text" name="identifier_val" required placeholder="Enter UID or Phone">
                </div>
            </div>
            <div class="form-group">
                <label>New Balance Amount</label>
                <input type="number" step="0.01" name="new_balance" required placeholder="0.00">
            </div>
            <button type="submit" class="btn">Update Balance</button>
        </form>
    </div>

    <!-- CREATE DEMO ID SECTION -->
    <div class="card">
        <h3>👤 Create Demo ID</h3>
        <form method="POST">
            <input type="hidden" name="action" value="create_demo">
            <div class="grid-2">
                <div class="form-group">
                    <label>Username</label>
                    <input type="text" name="demo_username" required placeholder="Demo username">
                </div>
                <div class="form-group">
                    <label>Password</label>
                    <input type="text" name="demo_password" required placeholder="Password">
                </div>
                <div class="form-group">
                    <label>Initial Balance</label>
                    <input type="number" step="0.01" name="initial_balance" required placeholder="0.00" value="0">
                </div>
                <div class="form-group">
                    <label>Phone Number (Optional)</label>
                    <input type="text" name="demo_phone" placeholder="Phone number">
                </div>
            </div>
            <button type="submit" class="btn" style="background: var(--success);">Create Account</button>
        </form>
    </div>
</div>

</body>
</html>
