<?php
require_once 'vendor/autoload.php';
require_once 'config/auth_config.php'; // For database connection
require_once 'api-functions-v1.php'; // Include API functions
use \Firebase\JWT\JWT;
use \Firebase\JWT\Key;

// JWT secret key - same as in verify-otp.php
$JWT_SECRET = '5489wd98wxs654fd8';

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

// Get the Authorization header
$headers = getallheaders();
$auth_header = isset($headers['Authorization']) ? $headers['Authorization'] : '';

// Default response structure
$response = [
    'success' => false,
    'errors' => 'Invalid Token',
    'urban_data' => [],
    'user' => null,
    'meta' => null
];

// Get user data from database
$conn = getDBConnection();
$sql = "SELECT * FROM cmsb_members WHERE num = '1'";
$result = $conn->query($sql);
if ($result && $result->num_rows > 0) {
    $response['user'] = $result->fetch_assoc();
}

// If no token provided, return default response
if (empty($auth_header)) {
    echo json_encode($response);
    exit();
}

// Use the API's token verification
$apiAccessToken = '';
$clientKeyId = '';
$isValid = verifyToken($headers, $apiAccessToken, $clientKeyId);

if ($isValid) {
    // Get user data based on token
    $decoded = JWT::decode($auth_header, new Key($JWT_SECRET, 'HS256'));
    $user_data = (array)$decoded;
    
    if (isset($user_data['sub'])) {
        $user_id = $conn->real_escape_string($user_data['sub']);
        $sql = "SELECT * FROM cmsb_members WHERE num = '$user_id'";
        $result = $conn->query($sql);
        if ($result && $result->num_rows > 0) {
            $response['user'] = $result->fetch_assoc();
        }
    }
    
    // Get listings data with proper headers
    $listings_url = "http://staging.cater4love.com/cmsb/apiv11.php?read&_section=listings&currentUserNum={$user_id}&num=2508&_latitude=&_longitude=&api_type=listing_profile_detail&_log=1";
    $opts = [
        'http' => [
            'method' => 'GET',
            'header' => [
                'Content-Type: application/json',
                'Authorization: ' . $auth_header
            ]
        ]
    ];
    $context = stream_context_create($opts);
    $listings_response = file_get_contents($listings_url, false, $context);
    $listings_data = json_decode($listings_response, true);

    if ($listings_data) {
        $response['urban_data'] = $listings_data;
    }
    
    $response['success'] = true;
    $response['errors'] = null;
}

// Return the response
echo json_encode($response); 