<?php
// ════════════════════════════════════════════════════════
// SIMPLE AUTH API FOR TESTING
// Place in: Triangle_Tree_Life_Number/api/auth.php
// ════════════════════════════════════════════════════════

error_reporting(E_ALL);
ini_set('display_errors', 0); // Don't output errors (breaks JSON)

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Include database and helpers
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/config/helpers.php';

// ════════════════════════════════════════════════════════
// DEVICE DETECTION HELPER
// ════════════════════════════════════════════════════════
function parseUserAgent($userAgent) {
    $browser = 'Unknown';
    $os = 'Unknown';
    $device = 'Desktop';
    
    // Detect Browser
    if (preg_match('/Edge\/([0-9.]+)/', $userAgent, $match)) {
        $browser = 'Edge ' . $match[1];
    } elseif (preg_match('/Edg\/([0-9.]+)/', $userAgent, $match)) {
        $browser = 'Edge ' . $match[1];
    } elseif (preg_match('/Chrome\/([0-9.]+)/', $userAgent, $match)) {
        $browser = 'Chrome ' . $match[1];
    } elseif (preg_match('/Safari\/([0-9.]+)/', $userAgent, $match)) {
        if (!preg_match('/Chrome/', $userAgent)) {
            $browser = 'Safari ' . $match[1];
        }
    } elseif (preg_match('/Firefox\/([0-9.]+)/', $userAgent, $match)) {
        $browser = 'Firefox ' . $match[1];
    } elseif (preg_match('/MSIE ([0-9.]+)/', $userAgent, $match)) {
        $browser = 'IE ' . $match[1];
    }
    
    // Detect OS
    if (preg_match('/Windows NT 10/', $userAgent)) {
        $os = 'Windows 10';
    } elseif (preg_match('/Windows NT 11/', $userAgent)) {
        $os = 'Windows 11';
    } elseif (preg_match('/Windows NT 6.3/', $userAgent)) {
        $os = 'Windows 8.1';
    } elseif (preg_match('/Windows NT 6.2/', $userAgent)) {
        $os = 'Windows 8';
    } elseif (preg_match('/Windows NT 6.1/', $userAgent)) {
        $os = 'Windows 7';
    } elseif (preg_match('/Mac OS X ([0-9_]+)/', $userAgent, $match)) {
        $os = 'macOS ' . str_replace('_', '.', $match[1]);
    } elseif (preg_match('/Android ([0-9.]+)/', $userAgent, $match)) {
        $os = 'Android ' . $match[1];
        $device = 'Mobile';
    } elseif (preg_match('/iPhone OS ([0-9_]+)/', $userAgent, $match)) {
        $os = 'iOS ' . str_replace('_', '.', $match[1]);
        $device = 'Mobile';
    } elseif (preg_match('/iPad/', $userAgent)) {
        $os = 'iPadOS';
        $device = 'Tablet';
    } elseif (preg_match('/Linux/', $userAgent)) {
        $os = 'Linux';
    }
    
    // Detect Device Type (if not already set by OS detection)
    if ($device === 'Desktop') {
        if (preg_match('/Mobile|Android|iPhone/', $userAgent)) {
            $device = 'Mobile';
        } elseif (preg_match('/Tablet|iPad/', $userAgent)) {
            $device = 'Tablet';
        }
    }
    
    return [
        'browser' => $browser,
        'os' => $os,
        'device' => $device
    ];
}

// Only handle POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['error' => 'Method not allowed']);
    exit();
}

// Get input
$input = json_decode(file_get_contents('php://input'), true);
$email = $input['email'] ?? '';
$password = $input['password'] ?? '';
$forceLogin = $input['forceLogin'] ?? false; // Allow forcing login to logout other sessions

if (empty($email) || empty($password)) {
    echo json_encode(['error' => 'Email and password required']);
    exit();
}

try {
    // Find user
    $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ? AND is_active = 1");
    $stmt->execute([$email]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$user) {
        echo json_encode(['error' => 'Invalid credentials']);
        exit();
    }
    
    // Verify password
    if (!password_verify($password, $user['password'])) {
        echo json_encode(['error' => 'Invalid credentials']);
        exit();
    }
    
    // ✅ CHECK FOR ACTIVE SESSION ON ANOTHER DEVICE
    // Only check if user already has a session_token AND forceLogin is not set
    if (!$forceLogin && !empty($user['session_token'])) {
        // Active session detected - return 409 status with real device info
        http_response_code(409);
        echo json_encode([
            'activeSession' => true,
            'session' => [
                'since' => $user['last_login'],
                'device' => $user['session_device'] ?? 'Unknown',
                'browser' => $user['session_browser'] ?? 'Unknown',
                'os' => $user['session_os'] ?? 'Unknown',
                'ip' => $user['session_ip'] ?? 'Unknown'
            ],
            'message' => 'This account is currently logged in from another device'
        ]);
        exit();
    }
    
    // ✅ NEW: Check if must change password (temp password)
    if (isset($user['must_change_password']) && $user['must_change_password'] == 1) {
        // Generate session for password change flow
        $changeToken = bin2hex(random_bytes(16));
        
        $stmt = $pdo->prepare("
            UPDATE users 
            SET session_token = ?, last_login = NOW() 
            WHERE id = ?
        ");
        $stmt->execute([$changeToken, $user['id']]);
        
        echo json_encode([
            'success' => true,
            'mustChangePassword' => true,
            'changeToken' => $changeToken,
            'userId' => $user['id'],
            'email' => $user['email'],
            'message' => 'You must change your temporary password'
        ]);
        exit();
    }
    
    // Generate JWT token
    $jwtSecret = getenv('JWT_SECRET') ?: 'default_secret_change_this';
    $sessionToken = bin2hex(random_bytes(16));
    
    $payload = [
        'userId' => $user['id'],
        'email' => $user['email'],
        'role' => $user['role'],
        'st' => $sessionToken
    ];
    
    // Create JWT token (expires in 7 days)
    $accessToken = createJWT($payload, $jwtSecret, '7d');
    
    // ✅ CAPTURE DEVICE INFORMATION
    $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';
    $ipAddress = $_SERVER['REMOTE_ADDR'] ?? 'Unknown';
    $deviceInfo = parseUserAgent($userAgent);
    
    // Update session token and device info in database
    $stmt = $pdo->prepare("
        UPDATE users 
        SET session_token = ?, 
            session_browser = ?,
            session_os = ?,
            session_ip = ?,
            session_device = ?,
            session_ua = ?,
            session_at = NOW(),
            last_login = NOW() 
        WHERE id = ?
    ");
    $stmt->execute([
        $sessionToken, 
        $deviceInfo['browser'],
        $deviceInfo['os'],
        $ipAddress,
        $deviceInfo['device'],
        $userAgent,
        $user['id']
    ]);
    
    // Return success
    echo json_encode([
        'success' => true,
        'accessToken' => $accessToken,
        'user' => [
            'id' => $user['id'],
            'name' => $user['name'],
            'email' => $user['email'],
            'role' => $user['role'],
            'emailVerified' => isset($user['email_verified']) ? (bool)$user['email_verified'] : false,
            'phoneVerified' => isset($user['phone_verified']) ? (bool)$user['phone_verified'] : false,
            'registeredBy' => $user['registered_by'] ?? null
        ]
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'error' => 'Login failed',
        'message' => $e->getMessage()
    ]);
}
?>
