<?php
// ════════════════════════════════════════════════════════
// GET CURRENT USER INFO
// Place in: Triangle_Tree_Life_Number/api/me.php
// ════════════════════════════════════════════════════════

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 'config/db.php';
require_once 'config/helpers.php';

// Only allow GET
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed - use GET']);
    exit();
}

// Get authorization token
$headers = getallheaders();
$token = isset($headers['Authorization']) ? str_replace('Bearer ', '', $headers['Authorization']) : null;

if (!$token) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized - No token provided']);
    exit();
}

// Verify token and get user
$user = verifyToken($token);
if (!$user) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized - Invalid token']);
    exit();
}

try {
    // Fetch full user details from database
    $stmt = $pdo->prepare("
        SELECT 
            id, 
            name, 
            email, 
            phone, 
            role, 
            is_active,
            email_verified,
            phone_verified,
            registered_by,
            created_at
        FROM users 
        WHERE id = ? AND is_active = 1
    ");
    $stmt->execute([$user['id']]);
    $userData = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$userData) {
        http_response_code(404);
        echo json_encode(['error' => 'User not found or inactive']);
        exit();
    }
    
    // Make sure email is included
    if (empty($userData['email'])) {
        http_response_code(400);
        echo json_encode(['error' => 'User account has no email address']);
        exit();
    }
    
    // Return user data
    echo json_encode([
        'id' => (int)$userData['id'],
        'name' => $userData['name'] ?: '',
        'email' => $userData['email'],
        'phone' => $userData['phone'] ?: '',
        'role' => $userData['role'],
        'is_active' => (int)$userData['is_active'],
        'email_verified' => isset($userData['email_verified']) ? (int)$userData['email_verified'] : 0,
        'phone_verified' => isset($userData['phone_verified']) ? (int)$userData['phone_verified'] : 0,
        'registered_by' => $userData['registered_by'],
        'created_at' => $userData['created_at']
    ]);
    
} catch (Exception $e) {
    error_log('Error fetching user: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'error' => 'Failed to fetch user data',
        'details' => $e->getMessage()
    ]);
}
?>
