<?php
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');

// Handle preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

require_once '../config/database.php';
require_once '../includes/functions.php';

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(false, 'Only POST requests are allowed');
}

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);
$token = $input['token'] ?? '';

// Validate token
if (empty($token)) {
    sendResponse(false, 'Session token is required');
}

try {
    $conn = getDBConnection();
    
    // Check if session exists and is not expired
    $stmt = $conn->prepare("
        SELECT s.*, u.id, u.user_name, u.email, u.user_level, u.is_verified
        FROM user_sessions s
        JOIN users u ON s.user_id = u.id
        WHERE s.token = ? AND s.expires_at > NOW() AND u.is_deleted = 0
    ");
    $stmt->execute([$token]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($result) {
        // Return user data (no password)
        $userData = [
            'id' => $result['id'],
            'user_name' => $result['user_name'],
            'email' => $result['email'],
            'user_level' => $result['user_level'],
            'is_verified' => (bool)$result['is_verified'],
            'session_token' => $token,
            'expires_at' => $result['expires_at']
        ];
        
        sendResponse(true, 'Session is valid', $userData);
    } else {
        // Check if session exists but expired
        $stmt = $conn->prepare("SELECT id FROM user_sessions WHERE token = ?");
        $stmt->execute([$token]);
        
        if ($stmt->fetch()) {
            // Delete expired session
            $stmt = $conn->prepare("DELETE FROM user_sessions WHERE token = ?");
            $stmt->execute([$token]);
            sendResponse(false, 'Session expired. Please login again.');
        } else {
            sendResponse(false, 'Invalid session. Please login again.');
        }
    }
    
} catch (PDOException $e) {
    logError("Session validation error: " . $e->getMessage());
    sendResponse(false, 'Session validation failed');
}
