<?php
/**
 * NROI Get Profile API
 * Fetches the latest user data to keep the mobile app in sync.
 */
ob_start();
error_reporting(0);
@ini_set('display_errors', 0);

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

header('Content-Type: application/json');

$response = ['success' => false, 'message' => 'Unknown error'];

try {
    $user_id = $_GET['user_id'] ?? '';

    if (empty($user_id)) {
        $response = ['success' => false, 'message' => 'User ID is required'];
    } else {
        $stmt = $pdo->prepare("
            SELECT u.*,
                   COALESCE(
                      (SELECT a1.area_name FROM areas a1 WHERE a1.area_name = u.area LIMIT 1),
                      (SELECT a2.area_name FROM areas a2 WHERE a2.id = u.area LIMIT 1),
                      u.area
                   ) AS area_display
            FROM users u
            WHERE u.id = ?
        ");
        $stmt->execute([$user_id]);
        $user = $stmt->fetch();

        if ($user) {
            // Remove sensitive password field
            unset($user['password']);
            // Replace raw area id with human-readable area name
            if (isset($user['area_display'])) {
                $user['area'] = $user['area_display'];
                unset($user['area_display']);
            }

            $response = [
                'success' => true,
                'data' => $user
            ];
        } else {
            $response = ['success' => false, 'message' => 'User not found'];
        }
    }
} catch (Throwable $e) {
    $response = ['success' => false, 'message' => 'System error: ' . $e->getMessage()];
}

ob_end_clean();
echo json_encode($response);
exit;
