<?php
session_start();

function getConnection() {
    $server = "206.0.29.132";
    $database = "gc";
    $username = "sa";
    $password = "gc@123";
    
    try {
        $pdo = new PDO("sqlsrv:server=$server;Database=$database", $username, $password);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $pdo;
    } catch(PDOException $e) {
        die("Erro na conexão: " . $e->getMessage());
    }
}

$isLoggedIn = isset($_SESSION['user_id']);

// Processar login via GET (URL)
if (isset($_GET['action']) && $_GET['action'] === 'login' && isset($_GET['login_user']) && isset($_GET['login_password'])) {
    $pdo = getConnection();
    
    try {
        $login = trim($_GET['login_user']);
        $password = trim($_GET['login_password']);
        $password_md5 = md5($password);
        
        $stmt = $pdo->prepare("SELECT * FROM users WHERE Login = ?");
        $stmt->execute([$login]);
        $user = $stmt->fetch();
        
        if ($user && $password_md5 === $user['passwd']) {
            $stmt_cash = $pdo->prepare("SELECT Cash FROM cashusers WHERE Login = ?");
            $stmt_cash->execute([$login]);
            $cashData = $stmt_cash->fetch();
            $userCash = $cashData ? $cashData['Cash'] : 0;
            
            $_SESSION['user_id'] = $user['LoginUID'];
            $_SESSION['user_login'] = $user['Login'];
            $_SESSION['user_cash'] = $userCash;
            
            header("Location: index.php");
            exit();
        } else {
            $error = "Login ou senha incorretos!";
        }
        
    } catch(PDOException $e) {
        $error = "Erro no banco de dados: " . $e->getMessage();
    }
}

if (isset($_POST['action'])) {
    $pdo = getConnection();
    
    switch($_POST['action']) {
        case 'login':
            header('Content-Type: application/json');
            
            try {
                $login = trim($_POST['login_user']);
                $password = trim($_POST['login_password']);
                $password_md5 = md5($password);
                
                if (empty($login) || empty($password)) {
                    echo json_encode(['success' => false, 'message' => 'Todos os campos são obrigatórios!']);
                    break;
                }
                
                $stmt = $pdo->prepare("SELECT * FROM users WHERE Login = ?");
                $stmt->execute([$login]);
                $user = $stmt->fetch();
                
                if ($user && $password_md5 === $user['passwd']) {
                    $stmt_cash = $pdo->prepare("SELECT Cash FROM cashusers WHERE Login = ?");
                    $stmt_cash->execute([$login]);
                    $cashData = $stmt_cash->fetch();
                    $userCash = $cashData ? $cashData['Cash'] : 0;
                    
                    $_SESSION['user_id'] = $user['LoginUID'];
                    $_SESSION['user_login'] = $user['Login'];
                    $_SESSION['user_cash'] = $userCash;
                    echo json_encode(['success' => true, 'message' => 'Login realizado com sucesso!']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Login ou senha incorretos!']);
                }
                
            } catch(PDOException $e) {
                echo json_encode(['success' => false, 'message' => 'Erro no banco de dados: ' . $e->getMessage()]);
            }
            break;
            
        case 'register':
            header('Content-Type: application/json');
            
            try {
                $login = trim($_POST['reg_login']);
                $password = trim($_POST['reg_password']);
                $confirm_password = trim($_POST['confirm_password']);
                
                if (empty($login) || empty($password)) {
                    echo json_encode(['success' => false, 'message' => 'Todos os campos são obrigatórios!']);
                    break;
                }
                
                if ($password !== $confirm_password) {
                    echo json_encode(['success' => false, 'message' => 'Senhas não coincidem!']);
                    break;
                }
                
                $stmt = $pdo->prepare("SELECT * FROM users WHERE Login = ?");
                $stmt->execute([$login]);
                if ($stmt->fetch()) {
                    echo json_encode(['success' => false, 'message' => 'Usuário já existe!']);
                    break;
                }
                
                $email = trim($_POST['reg_email']);
                $password_md5 = md5($password);
                
                $stmt = $pdo->prepare("INSERT INTO users (
                    Login, passwd, sex, firstLogin, lastConnect, lastLogin, 
                    playTime, gamePoint, IPAddress, Connecting, ModeLevel, 
                    ChannelingID, CASH, email
                ) VALUES (?, ?, 0, GETDATE(), GETDATE(), GETDATE(), 0, 0, '127.0.0.1', 0, 0x00, 0, 0, ?)");
                
                $result = $stmt->execute([$login, $password_md5, $email]);
                
                if ($result) {
                    echo json_encode(['success' => true, 'message' => 'Conta criada com sucesso! Faça login para continuar.']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Erro ao criar conta. Tente novamente.']);
                }
                
            } catch(PDOException $e) {
                echo json_encode(['success' => false, 'message' => 'Erro no banco de dados: ' . $e->getMessage()]);
            }
            break;
            
        case 'claim_cash':
            header('Content-Type: application/json');
            
            error_log('Claim cash action received. User logged in: ' . ($isLoggedIn ? 'yes' : 'no'));
            
            if (!$isLoggedIn) {
                echo json_encode(['success' => false, 'message' => 'Usuário não está logado']);
                exit;
            }
                
            try {
                error_log('Starting cash claim process...');
                $today = date('Y-m-d');
                error_log('Today date: ' . $today);
                error_log('User ID: ' . $_SESSION['user_id']);
                error_log('User login: ' . $_SESSION['user_login']);
                
                // Verificar se tabela daily_claims existe, se não, criar
                $stmt = $pdo->prepare("SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'daily_claims'");
                $stmt->execute();
                $tableExists = $stmt->fetchColumn();
                
                if (!$tableExists) {
                    $pdo->exec("CREATE TABLE daily_claims (
                        id INT IDENTITY(1,1) PRIMARY KEY,
                        user_id INT NOT NULL,
                        claim_date DATE NOT NULL,
                        claimed_at DATETIME DEFAULT GETDATE(),
                        UNIQUE(user_id, claim_date)
                    )");
                }
                
                $stmt = $pdo->prepare("SELECT * FROM daily_claims WHERE user_id = ? AND claim_date = ?");
                $stmt->execute([$_SESSION['user_id'], $today]);
                
                if (!$stmt->fetch()) {
                    $stmt = $pdo->prepare("SELECT * FROM cashusers WHERE Login = ?");
                    $stmt->execute([$_SESSION['user_login']]);
                    $cashUser = $stmt->fetch();
                    
                    if ($cashUser) {
                        $stmt = $pdo->prepare("UPDATE cashusers SET Cash = Cash + 550 WHERE Login = ?");
                        $stmt->execute([$_SESSION['user_login']]);
                    } else {
                        $stmt = $pdo->prepare("INSERT INTO cashusers (Login, Cash) VALUES (?, 550)");
                        $stmt->execute([$_SESSION['user_login']]);
                    }
                    
                    $stmt = $pdo->prepare("INSERT INTO daily_claims (user_id, claim_date) VALUES (?, ?)");
                    $stmt->execute([$_SESSION['user_id'], $today]);
                    
                    // Buscar o valor atualizado do banco
                    $stmt = $pdo->prepare("SELECT Cash FROM cashusers WHERE Login = ?");
                    $stmt->execute([$_SESSION['user_login']]);
                    $cashData = $stmt->fetch();
                    $newCash = $cashData ? $cashData['Cash'] : 0;
                    
                    // Atualizar a sessão com o valor correto
                    $_SESSION['user_cash'] = $newCash;
                    
                    error_log('Cash after claim - New value: ' . $newCash);
                    error_log('Cash before claim was: ' . ($newCash - 550));
                    
                    echo json_encode(['success' => true, 'message' => 'Cash resgatado com sucesso! +550 Cash', 'new_cash' => (int)$newCash]);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Você já resgatou seu cash diário hoje!']);
                }
                    
            } catch(PDOException $e) {
                error_log('PDO Error in claim_cash: ' . $e->getMessage());
                echo json_encode(['success' => false, 'message' => 'Erro no banco de dados: ' . $e->getMessage()]);
            }
            break;
    }
    exit;
}

if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: index.php");
    exit();
}
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Painel Cash - Launcher</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container<?php echo $isLoggedIn ? ' logged-in' : ''; ?>">
        <div class="panel">
            <div class="header">
                <h1>💰 Painel Cash</h1>
                <?php if ($isLoggedIn): ?>
                    <div class="user-info">
                        <span>👤 <?php echo htmlspecialchars($_SESSION['user_login']); ?></span>
                        <span>💎 <?php echo $_SESSION['user_cash']; ?> Cash</span>
                    </div>
                <?php endif; ?>
            </div>

            <?php if (isset($error)): ?>
                <div class="alert alert-error"><?php echo $error; ?></div>
            <?php endif; ?>

            <?php if (isset($success)): ?>
                <div class="alert alert-success"><?php echo $success; ?></div>
            <?php endif; ?>

            <?php if (!$isLoggedIn): ?>
                <div class="auth-container">
                    <!-- Login Form -->
                    <div class="auth-form">
                        <h2>🔐 Login</h2>
                        <form id="loginForm">
                            <input type="hidden" name="action" value="login">
                            <div class="form-group">
                                <input type="text" name="login_user" placeholder="Usuário" required>
                            </div>
                            <div class="form-group">
                                <input type="password" name="login_password" placeholder="Senha" required>
                            </div>
                            <button type="submit" class="btn btn-primary">Entrar</button>
                        </form>
                        <div id="loginMessage"></div>
                    </div>

                    <!-- Register Form -->
                    <div class="auth-form">
                        <h2>📝 Registrar</h2>
                        <form id="registerForm">
                            <input type="hidden" name="action" value="register">
                            <div class="form-group">
                                <input type="text" name="reg_login" placeholder="Usuário" required>
                            </div>
                            <div class="form-group">
                                <input type="password" name="reg_password" placeholder="Senha" required>
                            </div>
                            <div class="form-group">
                                <input type="password" name="confirm_password" placeholder="Confirmar Senha" required>
                            </div>
                            <div class="form-group">
                                <input type="email" name="reg_email" placeholder="Email" required>
                            </div>
                            <button type="submit" class="btn btn-secondary">Registrar</button>
                        </form>
                        <div id="registerMessage"></div>
                    </div>
                </div>
            <?php else: ?>
                <!-- Dashboard Logado -->
                <div class="dashboard">
                    <div class="cash-display">
                        <div class="cash-amount">
                            <span class="cash-icon">💎</span>
                            <span class="cash-value"><?php echo $_SESSION['user_cash']; ?></span>
                            <span class="cash-label">Cash</span>
                        </div>
                    </div>

                    <div class="actions">
                        <form class="claim-form">
                            <button type="submit" class="btn btn-success btn-large">
                                <span class="btn-icon">🎁</span>
                                Resgatar Cash Diário
                                <span class="btn-bonus">+550</span>
                            </button>
                        </form>

                        <div class="daily-info">
                            <p>💰 Resgate seu cash diário e ganhe 550 cash por dia!</p>
                            <p>⏰ Reset diário às 00:00</p>
                        </div>
                    </div>

                    <div class="logout-section">
                        <a href="?logout=1" class="btn btn-danger">🚪 Sair</a>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script src="script.js"></script>
</body>
</html>

