<?php
// ════════════════════════════════════════════════════════
// SESSION VALIDATION API
// Place in: Triangle_Tree_Life_Number/api/validate-session.php
// ════════════════════════════════════════════════════════

error_reporting(E_ALL);
ini_set('display_errors', 0);

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

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

require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/config/helpers.php';

// Get Authorization header
$headers = getallheaders();
$authHeader = $headers['Authorization'] ?? '';

if (empty($authHeader) || !preg_match('/Bearer\s+(.*)$/i', $authHeader, $matches)) {
    http_response_code(401);
    echo json_encode(['valid' => false, 'reason' => 'No token provided']);
    exit();
}

$token = $matches[1];
$jwtSecret = getenv('JWT_SECRET') ?: 'default_secret_change_this';

try {
    // Decode JWT
    $payload = verifyJWT($token, $jwtSecret);
    
    if (!$payload) {
        http_response_code(401);
        echo json_encode(['valid' => false, 'reason' => 'Invalid token']);
        exit();
    }
    
    $userId = $payload['userId'];
    $sessionToken = $payload['st'] ?? null; // Session token from JWT
    
    if (!$sessionToken) {
        http_response_code(401);
        echo json_encode(['valid' => false, 'reason' => 'No session token in JWT']);
        exit();
    }
    
    // Check if session token matches database
    $stmt = $pdo->prepare("SELECT session_token, is_active FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$user) {
        http_response_code(401);
        echo json_encode(['valid' => false, 'reason' => 'User not found']);
        exit();
    }
    
    if ($user['is_active'] != 1) {
        http_response_code(401);
        echo json_encode(['valid' => false, 'reason' => 'Account deactivated']);
        exit();
    }
    
    // Compare session tokens
    if ($user['session_token'] !== $sessionToken) {
        // Session was taken over by another device
        // Get current session info from database
        $stmt = $pdo->prepare("
            SELECT 
                session_browser, 
                session_os, 
                session_device, 
                session_ip, 
                session_created_at
            FROM users 
            WHERE id = ?
        ");
        $stmt->execute([$userId]);
        $sessionInfo = $stmt->fetch(PDO::FETCH_ASSOC);
        
        http_response_code(401);
        echo json_encode([
            'valid' => false, 
            'reason' => 'session_taken_over',
            'message' => 'You have been logged out because you logged in from another device or browser.',
            'session' => [
                'browser' => $sessionInfo['session_browser'] ?? 'Unknown',
                'os' => $sessionInfo['session_os'] ?? 'Unknown',
                'device' => $sessionInfo['session_device'] ?? 'Unknown',
                'ip' => $sessionInfo['session_ip'] ?? 'Unknown',
                'since' => $sessionInfo['session_created_at'] ?? null
            ]
        ]);
        exit();
    }
    
    // Session is valid
    echo json_encode(['valid' => true]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['valid' => false, 'reason' => 'Server error', 'error' => $e->getMessage()]);
}
?>
