<?php
/**
 * Simple Direct Authentication for EasyStream
 * No redirects, direct processing
 */

define('_ISVALID', true);
session_start();

// Database connection
try {
    $pdo = new PDO(
        "mysql:host=db;dbname=easystream;charset=utf8mb4",
        "easystream",
        "easystream",
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]
    );
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

$message = '';
$messageType = '';

// Handle form submission
if ($_POST) {
    if (isset($_POST['action']) && $_POST['action'] === 'signin') {
        $username = trim($_POST['username']);
        $password = $_POST['password'];
        
        if (empty($username) || empty($password)) {
            $message = "Please enter both username and password.";
            $messageType = 'error';
        } else {
            // Check user in database
            $stmt = $pdo->prepare("
                SELECT usr_id, usr_user, usr_email, usr_password, usr_fname, usr_lname, usr_active 
                FROM db_accountuser 
                WHERE (usr_user = ? OR usr_email = ?) AND usr_active = 1
            ");
            $stmt->execute([$username, $username]);
            $user = $stmt->fetch();
            
            if ($user && password_verify($password, $user['usr_password'])) {
                // Successful login
                $_SESSION['user_id'] = $user['usr_id'];
                $_SESSION['username'] = $user['usr_user'];
                $_SESSION['user_email'] = $user['usr_email'];
                $_SESSION['user_name'] = $user['usr_fname'] . ' ' . $user['usr_lname'];
                $_SESSION['logged_in'] = true;
                $_SESSION['USER_ID'] = $user['usr_id'];
                $_SESSION['USER_NAME'] = $user['usr_user'];
                $_SESSION['USER_DNAME'] = $user['usr_fname'] . ' ' . $user['usr_lname'];
                
                // Set admin session if user is admin
                if ($user['usr_user'] === 'admin' || strpos($user['usr_user'], 'admin') !== false) {
                    $_SESSION['admin_logged_in'] = true;
                    $_SESSION['admin_user'] = $user['usr_user'];
                    $_SESSION['ADMIN_NAME'] = trim($user['usr_fname'] . ' ' . $user['usr_lname']) ?: $user['usr_user'];
                }
                
                // Update last login
                $updateStmt = $pdo->prepare("UPDATE db_accountuser SET usr_lastlogin = NOW() WHERE usr_id = ?");
                $updateStmt->execute([$user['usr_id']]);
                
                if (!empty($_SESSION['admin_logged_in'])) {
                    $checkStmt = $pdo->prepare("SELECT cfg_data FROM db_settings WHERE cfg_name = 'token_setup_complete' LIMIT 1");
                    $checkStmt->execute();
                    $tokenSetup = $checkStmt->fetchColumn();
                    if ($tokenSetup !== '1') {
                        header("Location: /admin_token_setup.php");
                        exit;
                    }
                }
                
                $message = "Login successful! Welcome back, " . htmlspecialchars($user['usr_fname']) . "!";
                $messageType = 'success';
                
            } else {
                $message = "Invalid username/email or password.";
                $messageType = 'error';
            }
        }
        
    } elseif (isset($_POST['action']) && $_POST['action'] === 'signup') {
        $username = trim($_POST['username']);
        $email = trim($_POST['email']);
        $password = $_POST['password'];
        $confirm_password = $_POST['confirm_password'];
        $first_name = trim($_POST['first_name']);
        $last_name = trim($_POST['last_name']);
        
        // Validation
        if (empty($username) || empty($email) || empty($password) || empty($first_name) || empty($last_name)) {
            $message = "All fields are required.";
            $messageType = 'error';
        } elseif ($password !== $confirm_password) {
            $message = "Passwords do not match.";
            $messageType = 'error';
        } elseif (strlen($password) < 6) {
            $message = "Password must be at least 6 characters long.";
            $messageType = 'error';
        } else {
            // Check if username or email already exists
            $checkStmt = $pdo->prepare("SELECT usr_id FROM db_accountuser WHERE usr_user = ? OR usr_email = ?");
            $checkStmt->execute([$username, $email]);
            
            if ($checkStmt->fetch()) {
                $message = "Username or email already exists.";
                $messageType = 'error';
            } else {
                // Create new user
                $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
                $userKey = 'usr_' . uniqid();
                
                $insertStmt = $pdo->prepare("
                    INSERT INTO db_accountuser (
                        usr_key, usr_user, usr_email, usr_password, usr_fname, usr_lname,
                        usr_active, usr_joindate, usr_lastlogin, usr_IP
                    ) VALUES (?, ?, ?, ?, ?, ?, 1, NOW(), NOW(), ?)
                ");
                
                $userIP = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
                
                if ($insertStmt->execute([$userKey, $username, $email, $hashedPassword, $first_name, $last_name, $userIP])) {
                    $message = "Account created successfully! You can now sign in.";
                    $messageType = 'success';
                } else {
                    $message = "Failed to create account. Please try again.";
                    $messageType = 'error';
                }
            }
        }
    }
}

// Check if user is already logged in
$isLoggedIn = isset($_SESSION['logged_in']) && $_SESSION['logged_in'];

// Determine current mode
$mode = $_GET['mode'] ?? 'signin';
$isSignup = ($mode === 'signup');

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $isSignup ? 'Sign Up' : 'Sign In' ?> - EasyStream</title>
    <style>
        body { 
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; 
            margin: 0; 
            background: linear-gradient(135deg, <?= $isSignup ? '#28a745 0%, #20c997 100%' : '#667eea 0%, #764ba2 100%' ?>); 
            min-height: 100vh; 
            display: flex; 
            align-items: center; 
            justify-content: center; 
        }
        .auth-container { 
            background: white; 
            padding: 40px; 
            border-radius: 12px; 
            box-shadow: 0 10px 30px rgba(0,0,0,0.2); 
            width: 100%; 
            max-width: 400px; 
        }
        .logo { text-align: center; margin-bottom: 30px; }
        .logo h1 { color: #333; margin: 0; font-size: 2rem; }
        .form-group { margin-bottom: 20px; }
        .form-label { display: block; margin-bottom: 8px; font-weight: 500; color: #333; }
        .form-input { 
            width: 100%; 
            padding: 12px; 
            border: 2px solid #e1e5e9; 
            border-radius: 8px; 
            font-size: 16px; 
            transition: border-color 0.3s; 
            box-sizing: border-box; 
        }
        .form-input:focus { outline: none; border-color: #667eea; }
        .btn { 
            width: 100%; 
            padding: 12px; 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
            color: white; 
            border: none; 
            border-radius: 8px; 
            font-size: 16px; 
            font-weight: 600; 
            cursor: pointer; 
            transition: transform 0.2s; 
        }
        .btn:hover { transform: translateY(-1px); }
        .btn.signup { background: linear-gradient(135deg, #28a745 0%, #20c997 100%); }
        .links { text-align: center; margin-top: 20px; }
        .links a { color: #667eea; text-decoration: none; margin: 0 10px; }
        .links a:hover { text-decoration: underline; }
        .message { 
            padding: 12px; 
            border-radius: 8px; 
            margin-bottom: 20px; 
            text-align: center;
        }
        .message.error { 
            background: #f8d7da; 
            color: #721c24; 
            border: 1px solid #f5c6cb; 
        }
        .message.success { 
            background: #d4edda; 
            color: #155724; 
            border: 1px solid #c3e6cb; 
        }
        .tab-switcher {
            display: flex; 
            margin-bottom: 30px; 
            background: #f8f9fa; 
            border-radius: 8px; 
            padding: 4px;
        }
        .tab-btn {
            flex: 1; 
            padding: 12px; 
            text-align: center; 
            border: none; 
            background: none; 
            cursor: pointer; 
            border-radius: 6px; 
            font-weight: 500;
            text-decoration: none;
            color: #666;
        }
        .tab-btn.active { background: white; color: #333; }
        .user-info {
            background: #d4edda;
            padding: 20px;
            border-radius: 8px;
            text-align: center;
        }
    </style>
</head>
<body>

<div class="auth-container">
    <div class="logo">
        <h1>🎬 EasyStream</h1>
        <p style="color: #666; margin: 0;">
            <?php if ($isLoggedIn): ?>
                Welcome back!
            <?php else: ?>
                <?= $isSignup ? 'Create your account' : 'Sign in to your account' ?>
            <?php endif; ?>
        </p>
    </div>

    <?php if ($message): ?>
        <div class="message <?= $messageType ?>"><?= htmlspecialchars($message) ?></div>
    <?php endif; ?>

    <?php if ($isLoggedIn): ?>
        <!-- User is logged in -->
        <div class="user-info">
            <h3>✅ You are signed in!</h3>
            <p><strong>Username:</strong> <?= htmlspecialchars($_SESSION['username']) ?></p>
            <p><strong>Name:</strong> <?= htmlspecialchars($_SESSION['user_name']) ?></p>
            <p><strong>Email:</strong> <?= htmlspecialchars($_SESSION['user_email']) ?></p>
            
            <div style="margin-top: 20px;">
                <a href="/" style="background: #007bff; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; margin: 5px;">Go to Platform</a>
                <a href="/admin.php" style="background: #28a745; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; margin: 5px;">Admin Panel</a>
            </div>
            
            <div style="margin-top: 15px;">
                <a href="?logout=1" style="color: #dc3545;">Sign Out</a>
            </div>
        </div>
        
    <?php else: ?>
        <!-- User is not logged in -->
        
        <!-- Tab switcher -->
        <div class="tab-switcher">
            <a href="?mode=signin" class="tab-btn <?= !$isSignup ? 'active' : '' ?>">Sign In</a>
            <a href="?mode=signup" class="tab-btn <?= $isSignup ? 'active' : '' ?>">Sign Up</a>
        </div>

        <?php if ($isSignup): ?>
            <!-- Signup Form -->
            <form method="POST">
                <input type="hidden" name="action" value="signup">
                
                <div style="display: flex; gap: 15px;">
                    <div class="form-group" style="flex: 1;">
                        <label class="form-label" for="first_name">First Name</label>
                        <input type="text" id="first_name" name="first_name" class="form-input" placeholder="First name" required>
                    </div>
                    <div class="form-group" style="flex: 1;">
                        <label class="form-label" for="last_name">Last Name</label>
                        <input type="text" id="last_name" name="last_name" class="form-input" placeholder="Last name" required>
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label" for="username">Username</label>
                    <input type="text" id="username" name="username" class="form-input" placeholder="Choose a username" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label" for="email">Email Address</label>
                    <input type="email" id="email" name="email" class="form-input" placeholder="Enter your email" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label" for="password">Password</label>
                    <input type="password" id="password" name="password" class="form-input" placeholder="Create a password" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label" for="confirm_password">Confirm Password</label>
                    <input type="password" id="confirm_password" name="confirm_password" class="form-input" placeholder="Confirm your password" required>
                </div>
                
                <button type="submit" class="btn signup">Create Account</button>
            </form>
            
        <?php else: ?>
            <!-- Signin Form -->
            <form method="POST">
                <input type="hidden" name="action" value="signin">
                
                <div class="form-group">
                    <label class="form-label" for="username">Username or Email</label>
                    <input type="text" id="username" name="username" class="form-input" placeholder="Enter your username or email" required>
                </div>

                <div class="form-group">
                    <label class="form-label" for="password">Password</label>
                    <input type="password" id="password" name="password" class="form-input" placeholder="Enter your password" required>
                </div>

                <button type="submit" class="btn">Sign In</button>
                
                <div class="links">
                    <a href="f_modules/m_frontend/m_auth/recovery.php">Forgot Password?</a>
                </div>
            </form>
        <?php endif; ?>

        <div class="links" style="margin-top: 30px; border-top: 1px solid #eee; padding-top: 20px;">
            <a href="/">← Back to Home</a>
            <a href="/create_test_user.php">Create Test Users</a>
        </div>
    <?php endif; ?>
</div>

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

</body>
</html>
