<?php
// --- CUSTOM SESSION PATH FIX START (লগইন লুপ এবং /tmp এরর সমাধান) ---
$sessionPath = __DIR__ . '/sessions';
if (!file_exists($sessionPath)) { 
    @mkdir($sessionPath, 0755, true); 
}
if (is_writable($sessionPath)) {
    ini_set('session.save_path', $sessionPath);
}
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
// --- CUSTOM SESSION PATH FIX END ---

include 'config.php';

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

$user_id = $_SESSION['user_id'];
$user_data = $conn->query("SELECT * FROM users WHERE id=$user_id")->fetch_assoc();

if (!$user_data) { session_destroy(); header("Location: login.php"); exit(); }

$is_admin = ($user_data['email'] === 'tamimhasan1281@gmail.com');
$user_email = $user_data['email'];

// নিজের লগ ক্লিয়ার করার লজিক
if(isset($_POST['clear_my_logs'])) {
    $conn->query("DELETE FROM styled_names WHERE user_id=$user_id");
    header("Location: index.php");
    exit();
}

// স্টাইল জেনারেটর ফাংশন
function generateStyledName($text, $len) {
    $map = ['a'=>'ᴀ','b'=>'ʙ','c'=>'ᴄ','d'=>'ᴅ','e'=>'ᴇ','f'=>'ꜰ','g'=>'ɢ','h'=>'ʜ','i'=>'ɪ','j'=>'ᴊ','k'=>'ᴋ','l'=>'ʟ','m'=>'ᴍ','n'=>'ɴ','o'=>'ᴏ','p'=>'ᴘ','q'=>'ǫ','r'=>'ʀ','t'=>'ᴛ','u'=>'ᴜ','v'=>'ᴠ','w'=>'ᴡ','x'=>'x','y'=>'ʏ','z'=>'ᴢ'];
    
    // ১. প্রথম লেটারটি আলাদা করা এবং বড় হাতের করা (S হলেও বড় S হবে)
    $firstChar = mb_substr($text, 0, 1, "UTF-8");
    $firstCharStyled = mb_strtoupper($firstChar, "UTF-8");
    
    // ২. বাকি অংশ প্রসেস করা
    $remaining = mb_substr($text, 1, NULL, "UTF-8");
    $conv = "";
    $chars = preg_split('//u', $remaining, -1, PREG_SPLIT_NO_EMPTY);
    
    foreach ($chars as $char) {
        $lchar = mb_strtolower($char, "UTF-8");
        // প্রথম অক্ষরের পরে 's' আসলে সেটি ছোট হাতের 's' থাকবে
        if ($lchar == 's') { 
            $conv .= 's'; 
        } elseif (isset($map[$lchar])) { 
            $conv .= $map[$lchar]; 
        } else { 
            $conv .= $char; 
        }
    }
    
    // ৩. ৬ লেটার হলে লোগো থাকবে না, ৫ বা কম হলে লোগো থাকবে
    $prefix = ($len == 6) ? "" : "";
    return $prefix . $firstCharStyled . $conv . "┊1280모";
}

$output = ""; $msg = "";
if (isset($_POST['convert'])) {
    $raw_name = trim($_POST['player_name']);
    $name_len = mb_strlen($raw_name, "UTF-8");

    if (!$is_admin && $user_data['tokens'] < 10) {
        $msg = "<span style='color:#ff3333; display:block; margin-bottom:10px;'>Insufficient Tokens!</span>";
    } elseif ($name_len > 0 && $name_len <= 6) {
        $output = generateStyledName($raw_name, $name_len);
        if (!$is_admin) { $conn->query("UPDATE users SET tokens = tokens - 10 WHERE id = $user_id"); }
        
        $safe_out = mysqli_real_escape_string($conn, $output);
        $conn->query("INSERT INTO styled_names (user_id, original_name, final_output) VALUES ($user_id, '$raw_name', '$safe_out')");
        header("Location: index.php?out=".urlencode($output)); 
        exit();
    }
}
$display_out = $_GET['out'] ?? "";
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Solo System Interface</title>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Orbitron&family=Rajdhani:wght@500;700&display=swap">
    <style>
        :root { --primary: #00eaff; --secondary: #0051ff; --bg: #050505; }
        body { background: var(--bg); color: white; font-family: 'Rajdhani', sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; margin:0; background-image: radial-gradient(circle at 50% 50%, #0a1525 0%, #000000 80%); }
        .container { width: 90%; max-width: 450px; background: rgba(10,20,30,0.85); border: 1px solid var(--secondary); border-top: 2px solid var(--primary); border-bottom: 2px solid var(--primary); padding: 30px; border-radius: 8px; text-align: center; backdrop-filter: blur(10px); }
        .status-bar { display: flex; justify-content: space-between; font-size: 11px; color: var(--primary); margin-bottom: 20px; font-family: 'Orbitron'; }
        input { width: 100%; padding: 12px; background: #000; border: 1px solid #333; border-left: 3px solid var(--primary); color: #fff; outline:none; margin-bottom: 10px; box-sizing: border-box;}
        button { width: 100%; padding: 12px; background: transparent; border: 1px solid var(--primary); color: var(--primary); font-family: 'Orbitron'; cursor: pointer; transition: 0.3s; }
        button:hover { background: var(--primary); color: #000; box-shadow: 0 0 15px var(--primary); }
        .token-info { background: rgba(0,234,255,0.1); padding: 5px 10px; border-radius: 4px; border: 1px solid rgba(0,234,255,0.3); }
        .result-box { margin-top: 20px; padding: 15px; border: 1px dashed var(--primary); background: rgba(0,0,0,0.5); }
        .log-container { margin-top: 30px; text-align: left; }
        .log-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; border-bottom: 1px solid #222; padding-bottom: 5px; }
        .log-title { color: var(--primary); font-size: 11px; font-family: 'Orbitron'; }
        .clear-btn { background: none; border: 1px solid #ff3333; color: #ff3333; font-size: 9px; padding: 2px 6px; cursor: pointer; font-family: 'Orbitron'; width: auto; }
        .recent-item { font-size: 14px; color: #ccc; padding: 8px 0; border-bottom: 1px solid #111; letter-spacing: 1px; }
        .order-box { margin-top: 25px; padding: 15px; background: rgba(0, 81, 255, 0.1); border: 1px solid var(--secondary); border-radius: 5px; }
        .order-btn { display: inline-block; text-decoration: none; color: #000; background: var(--primary); padding: 8px 20px; font-family: 'Orbitron'; font-size: 12px; font-weight: bold; border-radius: 3px; }
        .footer-nav { display: flex; justify-content: center; gap: 15px; margin-top: 25px; }
        .admin-link { color: #00eaff; text-decoration: none; font-size: 11px; border: 1px solid #00eaff; padding: 3px 8px; font-family: 'Orbitron'; }
        .logout-link { color: #ff3333; text-decoration: none; font-size: 11px; font-family: 'Orbitron'; border: 1px solid #ff3333; padding: 3px 8px; }
    </style>
</head>
<body>
    <div class="container">
        <!-- Status Bar -->
        <div class="status-bar">
            <span>USER: <?php echo strtoupper(explode('@', $user_email)[0]); ?></span>
            <span class="token-info">TOKENS: <?php echo ($is_admin) ? "INFINITY" : $user_data['tokens']; ?></span>
        </div>
        
        <h2 style="font-family: 'Orbitron'; color: var(--primary); margin-top: 0; text-shadow: 0 0 10px var(--primary);">👑 TAMIM 1280 👑</h2>
        
        <form method="POST">
            <input type="text" name="player_name" placeholder="Enter Name (Max 6)" maxlength="6" required autocomplete="off">
            <button type="submit" name="convert">DESIGN</button>
        </form>
        
        <?php echo $msg; ?>

        <!-- Result Box -->
        <?php if($display_out): ?>
            <div class="result-box">
                <label style="font-size: 10px; color: var(--primary);">UPGRADE SUCCESSFUL</label>
                <div id="styledText" style="font-size: 22px; margin: 15px 0;"><?php echo htmlspecialchars($display_out); ?></div>
                <button onclick="copyToClipboard()" style="width: auto; font-size: 11px; padding: 6px 20px;">COPY NAME</button>
            </div>
        <?php endif; ?>

        <!-- History -->
        <div class="log-container">
            <div class="log-header">
                <span class="log-title">RECENT ARCHIVES</span>
                <form method="POST" onsubmit="return confirm('Clear archives?');">
                    <button type="submit" name="clear_my_logs" class="clear-btn">CLEAR</button>
                </form>
            </div>
            <?php
            $recent = $conn->query("SELECT final_output FROM styled_names WHERE user_id=$user_id ORDER BY id DESC LIMIT 5");
            while($row = $recent->fetch_assoc()) {
                echo "<div class='recent-item'>» " . htmlspecialchars($row['final_output']) . "</div>";
            }
            ?>
        </div>

        <!-- Token Order -->
        <div class="order-box">
            <div style="font-size:12px; margin-bottom:8px; color:#aaa;">Contact for Tokens</div>
            <a href="mailto:yhub.official@gmail.com?subject=Token Request&body=User:<?php echo $user_email; ?>" class="order-btn">ORDER TOKENS</a>
        </div>

        <div class="footer-nav">
            <?php if($is_admin): ?><a href="admin_setup.php" class="admin-link">ADMIN PANEL</a><?php endif; ?>
            <a href="logout.php" class="logout-link">LOGOUT</a>
        </div>
    </div>

    <script>
    function copyToClipboard() {
        var text = document.getElementById("styledText").innerText;
        navigator.clipboard.writeText(text).then(function() { alert('Copied to system!'); });
    }
    </script>
</body>
</html>