<?php
/**
 * API Entry Point
 * RESTful API for Mobile App and Third-Party Integrations
 * Kenyan Pension & Life Insurance Management System
 */

header('Content-Type: application/json');
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-Key');

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

require_once __DIR__ . '/../includes/dbconn.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../classes/ApiAuth.php';
require_once __DIR__ . '/../classes/ApiResponse.php';

// Initialize API
$apiAuth = new ApiAuth($conn);
$apiResponse = new ApiResponse();

// Get request method and path
$method = $_SERVER['REQUEST_METHOD'];
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$path = str_replace('/api', '', $path);
$path = trim($path, '/');
$segments = explode('/', $path);

// Get request data
$input = json_decode(file_get_contents('php://input'), true) ?? [];
$queryParams = $_GET;

// Authenticate request (skip for auth endpoint)
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$isAuthEndpoint = strpos($path, '/api/v1/auth') !== false && $_SERVER['REQUEST_METHOD'] === 'POST';

if (!$isAuthEndpoint) {
    $authResult = $apiAuth->authenticate();
    if (!$authResult['success']) {
        $apiResponse->error($authResult['message'], 401);
        exit();
    }
    $user = $authResult['user'];
} else {
    $user = null;
}

// Route requests
// Remove empty segments
$segments = array_filter($segments, function($s) { return !empty($s); });
$segments = array_values($segments);

$version = $segments[0] ?? 'v1';
$endpoint = $segments[1] ?? '';

// API Version 1
if ($version === 'v1') {
    // Make segments available to endpoint files
    $GLOBALS['segments'] = $segments;
    
    switch ($endpoint) {
        case 'auth':
            require __DIR__ . '/v1/auth.php';
            break;
            
        case 'members':
            require __DIR__ . '/v1/members.php';
            break;
            
        case 'contributions':
            require __DIR__ . '/v1/contributions.php';
            break;
            
        case 'withdrawals':
            require __DIR__ . '/v1/withdrawals.php';
            break;
            
        case 'policies':
            require __DIR__ . '/v1/policies.php';
            break;
            
        case 'premiums':
            require __DIR__ . '/v1/premiums.php';
            break;
            
        case 'claims':
            require __DIR__ . '/v1/claims.php';
            break;
            
        case 'statements':
            require __DIR__ . '/v1/statements.php';
            break;
            
        case 'notifications':
            require __DIR__ . '/v1/notifications.php';
            break;
            
        case 'beneficiaries':
            require __DIR__ . '/v1/beneficiaries.php';
            break;
            
        case 'payments':
            require __DIR__ . '/v1/payments.php';
            break;
            
        case 'analytics':
            require __DIR__ . '/v1/analytics.php';
            break;
            
        default:
            $apiResponse->error('Endpoint not found', 404);
    }
} else {
    $apiResponse->error('API version not supported', 400);
}
