<?php
session_start();
// require_once '../config/database.php'; // Commented out - file doesn't exist on server
// require_once '../config/api.php'; // Commented out - file doesn't exist

// API Configuration Constants
define('API_HASH', 'e053f5520dd5ac9f9436941627c40ade414afc17bd4f13c4286a07ddcf71caad');
define('JWT_SECRET', 'your-jwt-secret-key-here-change-this-in-production');

// Database Configuration
if (!defined('DB_HOST')) define('DB_HOST', 'localhost');
if (!defined('DB_NAME')) define('DB_NAME', 'memberxa_api');
if (!defined('DB_USER')) define('DB_USER', 'memberxa_api');
if (!defined('DB_PASS')) define('DB_PASS', 'C2ivPRSt,qwuZw(J');

try {
    $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4", DB_USER, DB_PASS);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// JWT Functions
function generateJWT($payload) {
    $header = json_encode(['typ' => 'JWT', 'alg' => 'HS256']);
    $payload = json_encode($payload);
    
    $base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));
    $base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload));
    
    $signature = hash_hmac('sha256', $base64UrlHeader . "." . $base64UrlPayload, JWT_SECRET, true);
    $base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));
    
    return $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;
}

function verifyJWT($token) {
    $parts = explode('.', $token);
    if (count($parts) !== 3) {
        return false;
    }
    
    $header = base64_decode(str_replace(['-', '_'], ['+', '/'], $parts[0]));
    $payload = base64_decode(str_replace(['-', '_'], ['+', '/'], $parts[1]));
    $signature = base64_decode(str_replace(['-', '_'], ['+', '/'], $parts[2]));
    
    $expectedSignature = hash_hmac('sha256', $parts[0] . "." . $parts[1], JWT_SECRET, true);
    
    if (hash_equals($signature, $expectedSignature)) {
        return json_decode($payload, true);
    }
    
    return false;
}

// Token verification function for API authentication
function verifyToken($token) {
    global $pdo;
    
    try {
        // First try to verify as JWT
        $jwtPayload = verifyJWT($token);
        if ($jwtPayload && isset($jwtPayload['user_id'])) {
            // Check if user exists and is active
            $stmt = $pdo->prepare("SELECT id FROM users WHERE id = ? AND is_active = 1");
            $stmt->execute([$jwtPayload['user_id']]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($user) {
                return $jwtPayload['user_id'];
            }
        }
        
        // If JWT verification fails, try to verify as simple token
        $stmt = $pdo->prepare("SELECT user_id FROM user_tokens WHERE token = ? AND expires_at > NOW()");
        $stmt->execute([$token]);
        $tokenData = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($tokenData) {
            // Check if user exists and is active
            $stmt = $pdo->prepare("SELECT id FROM users WHERE id = ? AND is_active = 1");
            $stmt->execute([$tokenData['user_id']]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($user) {
                return $tokenData['user_id'];
            }
        }
        
        return false;
    } catch (Exception $e) {
        error_log("Token verification error: " . $e->getMessage());
        return false;
    }
}

// API Hash Verification
function verifyAPIHash() {
    $headers = getallheaders();
    $apiHash = $headers['X-API-Hash'] ?? $headers['x-api-hash'] ?? '';
    
    if (empty($apiHash) || $apiHash !== API_HASH) {
        sendError('Invalid API Hash', 403);
    }
}

// Enhanced API Hash Verification for problematic servers
function verifyAPIHashEnhanced() {
    // Try multiple ways to get headers
    $headers = [];
    
    // Method 1: getallheaders()
    if (function_exists('getallheaders')) {
        $headers = getallheaders();
    }
    
    // Method 2: $_SERVER variables
    if (empty($headers)) {
        foreach ($_SERVER as $name => $value) {
            if (substr($name, 0, 5) == 'HTTP_') {
                $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
            }
        }
    }
    
    // Method 3: apache_request_headers()
    if (empty($headers) && function_exists('apache_request_headers')) {
        $headers = apache_request_headers();
    }
    
    $apiHash = $headers['X-API-Hash'] ?? $headers['x-api-hash'] ?? '';
    
    // Debug logging
    error_log("API Hash Debug - Received: " . $apiHash);
    error_log("API Hash Debug - Expected: " . API_HASH);
    error_log("API Hash Debug - Headers: " . json_encode($headers));
    
    if (empty($apiHash) || $apiHash !== API_HASH) {
        sendError('Invalid API Hash', 403);
    }
}

// Response Functions
function sendResponse($data, $status = 200) {
    http_response_code($status);
    header('Content-Type: application/json');
    
    // If data is already wrapped in success/message structure, use it as is
    if (isset($data['success'])) {
        echo json_encode($data);
    } else {
        // Wrap data in standard response structure
        $response = [
            'success' => true,
            'message' => 'Success',
            'data' => $data
        ];
        echo json_encode($response);
    }
    exit;
}

function sendError($message, $status = 400) {
    $response = [
        'success' => false,
        'message' => $message,
        'data' => null
    ];
    sendResponse($response, $status);
}

// Validation Functions
function validateEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL);
}

function validatePhone($phone) {
    return preg_match('/^[0-9+\-\s()]+$/', $phone);
}

// Authentication Functions
function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

function isAdmin() {
    return isset($_SESSION['admin_id']);
}

function requireAuth() {
    if (!isLoggedIn()) {
        sendError('Authentication required', 401);
    }
}

function requireAdmin() {
    if (!isAdmin()) {
        sendError('Admin access required', 403);
    }
}

// Database Helper Functions
function getUserById($id) {
    global $pdo;
    $stmt = $pdo->prepare("
        SELECT id, username, email, full_name, phone, coins, free_coins,
               telegram_sync_code, telegram_user_id, telegram_username, telegram_first_name,
               telegram_linked_at, welcome_reward_claimed, welcome_reward_claimed_at,
               is_active, created_at
        FROM users
        WHERE id = ?
    ");
    $stmt->execute([$id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Convert is_active to boolean
    if ($user) {
        $user['is_active'] = (bool)$user['is_active'];
        $user['welcome_reward_claimed'] = (bool)$user['welcome_reward_claimed'];
    }
    
    return $user;
}

function getUserByEmail($email) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Convert is_active to boolean
    if ($user) {
        $user['is_active'] = (bool)$user['is_active'];
    }
    
    return $user;
}

function updateUserCoins($userId, $amount) {
    global $pdo;
    $stmt = $pdo->prepare("UPDATE users SET coins = coins + ? WHERE id = ?");
    return $stmt->execute([$amount, $userId]);
}

function addTransaction($userId, $type, $amount, $description = '') {
    global $pdo;
    $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description) VALUES (?, ?, ?, ?)");
    return $stmt->execute([$userId, $type, $amount, $description]);
}

// CORS Headers
function setCORSHeaders() {
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type, Authorization, X-API-Hash');
    
    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
        http_response_code(200);
        exit;
    }
}

// Comprehensive Logging Function
function logApiCall($endpoint, $additionalData = []) {
    $logData = [
        'timestamp' => date('Y-m-d H:i:s'),
        'endpoint' => $endpoint,
        'method' => $_SERVER['REQUEST_METHOD'] ?? 'UNKNOWN',
        'uri' => $_SERVER['REQUEST_URI'] ?? 'UNKNOWN',
        'ip' => $_SERVER['REMOTE_ADDR'] ?? 'UNKNOWN',
        'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'UNKNOWN',
        'headers' => getallheaders(),
        'query_params' => $_GET,
        'post_data' => $_POST,
        'raw_input' => file_get_contents('php://input'),
        'additional_data' => $additionalData
    ];
    
    error_log("=== API CALL LOG ===");
    error_log("Endpoint: " . $endpoint);
    error_log("Full Log Data: " . json_encode($logData, JSON_PRETTY_PRINT));
    error_log("=== END API CALL LOG ===");
}

// Enhanced Error Logging
function logError($message, $context = []) {
    $errorData = [
        'timestamp' => date('Y-m-d H:i:s'),
        'message' => $message,
        'context' => $context,
        'file' => debug_backtrace()[0]['file'] ?? 'UNKNOWN',
        'line' => debug_backtrace()[0]['line'] ?? 'UNKNOWN'
    ];
    
    error_log("=== ERROR LOG ===");
    error_log("Error: " . $message);
    error_log("Context: " . json_encode($context));
    error_log("File: " . $errorData['file'] . ":" . $errorData['line']);
    error_log("=== END ERROR LOG ===");
}
?>
