<?php
require_once __DIR__ . '/core/Session.php';  // Include the Session class
require_once __DIR__ . '/core/Csrf.php';
require_once __DIR__ . '/core/Config.php';


$config = Config::getInstance();
$currency = Config::getInstance()->get('APP_CURRENCY');
$platform_name = Config::getInstance()->get('APP_PLATFORM_NAME');
$apidomain = Config::getInstance()->get('APP_DOMAIN');

/*
// At the top of index.php
Session::start();

echo "Session ID Before Logout: " . session_id() . "<br>";
print_r($_SESSION);

// Call logout
Session::logout();

// Start a new session
Session::start();
echo "Session ID After Logout: " . session_id() . "<br>";
print_r($_SESSION);

echo "Session Cookie: " . ($_COOKIE[session_name()] ?? 'No cookie set') . "<br>";

echo "Session Save Path: " . ini_get('session.save_path'). "<br>";;

echo "Cookie Lifetime: " . ini_get('session.cookie_lifetime') . "<br>";
echo "Use Cookies: " . ini_get('session.use_cookies') . "<br>";
echo "Use Trans SID: " . ini_get('session.use_trans_sid') . "<br>";
echo "GC Max Lifetime: " . ini_get('session.gc_maxlifetime') . "<br>";
*/

Session::start();  // This now handles starting the session and setting cookie parameters
$csrf = new Csrf();
// Disable error display, enable error logging
putenv('APP_ENV=development');

// Access:
$env = getenv('APP_ENV');

if ($env === 'development') {
    // Prevent Chrome from showing stale local templates or styles during development.
    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
    header('Pragma: no-cache');
    header('Expires: 0');
    ini_set('display_errors', 1);
    error_reporting(E_ALL);
} else {
    ini_set('display_errors', 0);
}
ini_set('error_log', __DIR__ . '/logs/code_errors.log'); // Path to error log file

// Place headers at the top of the file
header('X-Powered-By: Express');
header('Server: Node.js');

// CSRF Token generation (for security)
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = $csrf->generateToken();
}
$csrf_token = $_SESSION['csrf_token'];

//print_r($_SESSION);
//print_r(session_id());
//die();
//echo '<br/>isunverfied--->'.Session::isVerified().'<----';


// Core imports
//require_once __DIR__ . '/core/ErrorHandler.php'; // Error handling
require_once __DIR__ . '/core/Router.php';

// Enable output buffering
ob_start('minifyOutput');

// Minification function
function minifyOutput($buffer) {
    // Remove comments, tabs, and unnecessary spaces
    $buffer = preg_replace('/<!--.*?-->/s', '', $buffer); // Remove HTML comments
    $buffer = preg_replace('/\s+/', ' ', $buffer);       // Collapse whitespace
    $buffer = preg_replace('/>\s+</', '><', $buffer);    // Remove spaces between HTML tags
    return $buffer;
}

// Log errors to mimic a React/Node.js application
function logToConsole($message) {
    echo "<script>console.error('Error: " . addslashes($message) . "');</script>";
}

// Initialize Router
$router = new Router();

// Get route
$requestUri = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
$requestUri = rtrim($requestUri, '/');


// Handle routes like /api/users/{action}/{params...}
if (preg_match('/^api\/users\/([^\/]+)(\/.*)?$/', $requestUri, $matches)) {
    $action = $matches[1]; // Extract the action, e.g., 'getUserById', 'updateProfile', etc.
    $params = isset($matches[2]) ? explode('/', trim($matches[2], '/')) : []; // Extract additional parameters

    // Ensure the user is authenticated
    if (!Session::isLoggedIn()) {
        http_response_code(403);
        echo json_encode(['status' => 'error', 'message' => 'Unauthorized access']);
        exit;
    }

    // Map resource to specific API file
    $apiFile = __DIR__ . '/api/UserManageAPI.php';

    // Check if the resolved file exists
    if (!file_exists($apiFile)) {
        http_response_code(404);
        echo json_encode(['status' => 'error', 'message' => 'API file not found for the requested resource']);
        exit;
    }

    // Set the route and action for the API
    $_GET['route'] = "users/$action";
    $_GET['action'] = $action;

    // Convert parameters into key-value pairs for $_GET
    foreach ($params as $index => $param) {
        $_GET["param$index"] = htmlspecialchars($param);
    }

    // Include the API file
    require $apiFile;
    exit;
}





if (preg_match('/^api\/admin\/([^\/]+)\/([^\/]+)(\/.*)?$/', $requestUri, $matches)) {
    $resource = $matches[1]; // e.g., 'users' or 'ips'
    $action = $matches[2];   // e.g., 'getAllUsers', 'delete', etc.
    $params = isset($matches[3]) ? explode('/', trim($matches[3], '/')) : []; // Extract additional parameters


    // Ensure the user is authenticated and has admin privileges
    $usesActionAuthorization = in_array($resource, ['access','directory'], true);
    if (!Session::isLoggedIn() || (!$usesActionAuthorization && !Session::isAdmin())) {
        http_response_code(403);
        echo json_encode(['status' => 'error', 'message' => 'Unauthorized access']);
        exit;
    }
 
    // Map resource to specific API file
    $resourceToFileMap = [
        'users' => 'UserManageAPI.php',
        'ips' => 'IPListingAPI.php',
        'orgmanage' => 'OrgManageAPI.php', 
        'deal' => 'DealAPI.php',
        'operations' => 'AdminOperationsAPI.php',
        'access' => 'AdminAccessAPI.php',
        'directory' => 'AdminDirectoryAPI.php',
        // Add other resources as needed
    ];

    // Check if the resource exists in the map
    if (!array_key_exists($resource, $resourceToFileMap)) {
        http_response_code(404);
        echo json_encode(['status' => 'error', 'message' => 'Resource not found']);
        exit;
    }

    // Resolve the correct API file
    $apiFile = __DIR__ . '/api/' . $resourceToFileMap[$resource];

    // Check if the resolved file exists
    if (!file_exists($apiFile)) {
        http_response_code(404);
        echo json_encode(['status' => 'error', 'message' => 'API file not found for the requested resource']);
        exit;
    }

    // Set required variables and include the API file
    $_GET['route'] = "admin/$resource/$action";
    $_GET['action'] = $action;

    require $apiFile;
    exit;
}

// Handle routes like /api/orgmanage/getAllOrganisations/{page}/{perPage}/{status}/{type}/{search}
if (preg_match('/^api\/orgmanage\/getAllOrganisations\/(\d+)\/(\d+)\/([^\/]*)\/([^\/]*)\/([^\/]*)$/', $requestUri, $matches)) {
    $_GET['route'] = 'api/orgmanage/getAllOrganisations';
    $_GET['action'] = 'getAllOrganisations';
    $_GET['page'] = (int) $matches[1];
    $_GET['perPage'] = (int) $matches[2];
    $_GET['status'] = htmlspecialchars($matches[3]);
    $_GET['type'] = htmlspecialchars($matches[4]);
    $_GET['search'] = htmlspecialchars($matches[5]);

    // Call the Org API file
    require __DIR__ . '/api/OrgManageAPI.php';
    exit;
}

// Check if the request is an OrgManage API call
if (strpos($requestUri, 'api/orgmanage/') === 0) {
    $segments = explode('/', $requestUri);
    $action = $segments[2] ?? null;
    $params = array_slice($segments, 3);

    if ($action) {
        // Map parameters to $_GET for the controller to read
        foreach ($params as $index => $param) {
            $_GET["param{$index}"] = htmlspecialchars($param);
        }

        $_GET['route'] = 'api/orgmanage/' . $action;
        $_GET['action'] = $action;

        // Ensure Admin access
        if (!Session::isLoggedIn() || !Session::isAdmin()) {
            http_response_code(403);
            echo json_encode(['status' => 'error', 'message' => 'Unauthorized access']);
            exit;
        }

        require __DIR__ . '/api/OrgManageAPI.php';
        exit;
    }
}

// Handle routes like /api/iplisting/valuationRequests/{page}/{perPage}/{status}/{search}
if (preg_match('/^api\/iplisting\/valuationRequests\/(\d+)\/(\d+)\/([^\/]*)\/([^\/]*)$/', $requestUri, $matches)) {
    $_GET['route'] = 'api/iplisting/valuationRequests';
    $_GET['action'] = 'valuationRequests';
    $_GET['page'] = (int) $matches[1];
    $_GET['perPage'] = (int) $matches[2];
    $_GET['status'] = htmlspecialchars($matches[3]);
    $_GET['search'] = htmlspecialchars($matches[4]);

    // Call the API file or controller directly
    require __DIR__ . '/api/IPListingAPI.php';
    exit;
}

// --- ROUTE: api/deal/getDealMessages/{id} ---
if (strpos($requestUri, 'api/valuation-partner/') === 0) {
    $segments = explode('/', $requestUri);
    $action = $segments[2] ?? '';
    require __DIR__ . '/api/ValuationPartnerAPI.php';
    exit;
}

// --- ROUTE: api/deal/getDealMessages/{id} ---
if (preg_match('/^api\/deal\/getDealMessages\/(\d+)\/?$/', $requestUri, $matches)) {
    // Set variables for the API file to consume
    $action = 'getDealMessages';
    $params = [(int)$matches[1]]; // The ID 100

    // Force map to GET for compatibility with your existing structure
    $_GET['route'] = 'api/deal/getDealMessages';
    $_GET['action'] = $action;
    $_GET['param0'] = $params[0];

    $apiFile = __DIR__ . '/api/DealAPI.php';
    if (file_exists($apiFile)) {
        require $apiFile;
        exit;
    }
}

// --- ROUTE: General api/deal/ (for sendMessage, markVerified, etc.) ---
if (strpos($requestUri, 'api/deal/') === 0) {
    $segments = explode('/', $requestUri);
    $action = $segments[2] ?? null;
    $params = array_slice($segments, 3);

    if ($action) {
        $_GET['route'] = 'api/deal/' . $action;
        $_GET['action'] = $action;
        foreach ($params as $index => $param) {
            $_GET["param{$index}"] = htmlspecialchars($param);
        }

        require __DIR__ . '/api/DealAPI.php';
        exit;
    }
}



// Handle routes like /api/iplisting/insuranceRequests/{page}/{perPage}/{status}/{search}
if (preg_match('/^api\/iplisting\/insuranceRequests\/(\d+)\/(\d+)\/([^\/]*)\/([^\/]*)$/', $requestUri, $matches)) {
    $_GET['route'] = 'api/iplisting/insuranceRequests';
    $_GET['action'] = 'insuranceRequests';
    $_GET['page'] = (int) $matches[1];
    $_GET['perPage'] = (int) $matches[2];
    $_GET['status'] = htmlspecialchars($matches[3]);
    $_GET['search'] = htmlspecialchars($matches[4]);

    // Call the API file or controller directly
    require __DIR__ . '/api/IPListingAPI.php';
    exit;
}

// Handle routes like /api/iplisting/getStates/{page}/{perPage}/{countryId}/{query}
if (preg_match('/^api\/iplisting\/getStates\/(\d+)\/(\d+)\/([^\/]+)\/([^\/]+)$/', $requestUri, $matches)) {
    $_GET['route'] = 'api/iplisting/getStates';
    $_GET['action'] = 'getStates';
    $_GET['page'] = (int) $matches[1];
    $_GET['perPage'] = (int) $matches[2];
    $_GET['countryId'] = htmlspecialchars($matches[3]);
    // No query parameter – set to null
    $_GET['query'] = null;

    // Call the API file or controller directly
    require __DIR__ . '/api/IPListingAPI.php';
    exit;
}

// Handle GET request for /iplisting/shortlist/{ipId}
if (preg_match('#^api/iplisting/shortlist/(\d+)$#', $requestUri, $matches) && $_SERVER['REQUEST_METHOD'] === 'GET') {
    $ipListingId = intval($matches[1]); // Extract IP listing ID from URL

    // Set the route and action for the API
    $_GET['route'] = 'iplisting/shortlist';
    $_GET['action'] = 'shortlist';
    $_GET['ip_listing_id'] = $ipListingId; // Pass the ID to API handler

    // Include the IPListingAPI file to handle the request
    require __DIR__ . '/api/IPListingAPI.php';
    exit;
}

// Handle GET request for /iplisting/getConversations/{ipId}
if (preg_match('#^api/iplisting/getConversations/(\d+)$#', $requestUri, $matches) && $_SERVER['REQUEST_METHOD'] === 'GET') {
    $ipListingId = intval($matches[1]); // Extract IP listing ID from URL

    // Set the route and action for the API
    $_GET['route'] = 'iplisting/getConversations';
    $_GET['action'] = 'getConversations';
    $_GET['ip_listing_id'] = $ipListingId; // Pass the ID to API handler

    // Include the IPListingAPI file to handle the request
    require __DIR__ . '/api/IPListingAPI.php';
    exit;
}


// Handle routes like /api/iplisting/getAll/{page}/{perPage}/{status}/{search}
if (preg_match('/^api\/iplisting\/getAll\/(\d+)\/(\d+)\/([^\/]*)\/([^\/]*)$/', $requestUri, $matches)) {
    $_GET['route'] = 'api/iplisting/getAll';
    $_GET['action'] = 'getAll';
    $_GET['page'] = (int) $matches[1];
    $_GET['perPage'] = (int) $matches[2];
    $_GET['status'] = htmlspecialchars($matches[3]);
    $_GET['search'] = htmlspecialchars($matches[4]);
    
    // Call the API file or controller directly
    require __DIR__ . '/api/IPListingAPI.php';
    exit;
}

// Check if the request is an API call
if (strpos($requestUri, 'api/iplisting/') === 0) {
    $segments = explode('/', $requestUri); // Break down the URI into parts
    $action = $segments[2] ?? null;       // Extract the action
    $params = array_slice($segments, 3);  // Extract any additional parameters

    if ($action) {
        // Convert parameters into key-value pairs for $_GET
        foreach ($params as $index => $param) {
            $_GET["param{$index}"] = htmlspecialchars($param);
        }

        // Set the route and action for the controller
        $_GET['route'] = 'api/iplisting/' . $action;
        $_GET['action'] = $action;

        // Call the API file directly
        require __DIR__ . '/api/IPListingAPI.php';
        exit;
    }
}

// Handle routes like /api/investment/submit or /api/investment/getMyRequests
if (strpos($requestUri, 'api/investment/') === 0) {
    $segments = explode('/', $requestUri);
    $action = $segments[2] ?? null;
    $params = array_slice($segments, 3);

    if ($action) {
        $_GET['route'] = 'api/investment/' . $action;
        $_GET['action'] = $action;
        foreach ($params as $index => $param) {
            $_GET["param{$index}"] = htmlspecialchars($param);
        }
        require __DIR__ . '/api/InvestmentAPI.php';
        exit;
    }
}

if (isset($_GET['route']) && $_GET['route'] === 'search') {
    $requestUri = 'search';
}

// Handle verify/{type}/{token} explicitly
if (preg_match('/^verify\/([^\/]+)\/([^\/]+)$/', $requestUri, $matches)) {
    $_GET['route'] = 'verify';
    $_GET['type'] = htmlspecialchars($matches[1]);
    $_GET['token'] = htmlspecialchars($matches[2]);
    $requestUri = 'verify';
}

$route = empty($requestUri) ? 'home' : $requestUri;
 // Resolve the route
$pageDetails = $router->resolve($route);

 
// If route exists
if ($pageDetails) {
    // Extract key and path from the resolved route
    $pageKey = $pageDetails['key'];
    $page = $pageDetails['path'];
    $check_role = Session::getRole();

    /// Capture all parameters
    $type = isset($_GET['type']) ? htmlspecialchars($_GET['type']) : null;
    $location = isset($_GET['location']) ? htmlspecialchars($_GET['location']) : null;
    $query = isset($_GET['query']) ? htmlspecialchars($_GET['query']) : null;
    $date_period = isset($_GET['date_period']) ? htmlspecialchars($_GET['date_period']) : null;
    $from_date = isset($_GET['from_date']) ? htmlspecialchars($_GET['from_date']) : null;
    $to_date = isset($_GET['to_date']) ? htmlspecialchars($_GET['to_date']) : null;
    $search_in = isset($_GET['search_in']) ? htmlspecialchars($_GET['search_in']) : null;

   /* // Debugging (remove in production)
    echo "Type: " . ($type ?? 'N/A') . "<br>";
    echo "Location: " . ($location ?? 'N/A') . "<br>";
    echo "Query: " . ($query ?? 'N/A') . "<br>";
    echo "Date Period: " . ($date_period ?? 'N/A') . "<br>";
    echo "From Date: " . ($from_date ?? 'N/A') . "<br>";
    echo "To Date: " . ($to_date ?? 'N/A') . "<br>";
    echo "Search In: " . ($search_in ?? 'N/A') . "<br>";*/

    $isUserPanel = 0;
    $usePremiumHomepageTemplate = ($pageKey === 'home');
    $premiumPublicInnerPages = [
        'search', 'ipdetails', 'ipcategories', 'trademarks', 'copyrights', 'patents',
        'ourstory', 'aboutus', 'ourteam', 'careers', 'leadership', 'ourmission',
        'ourvision', 'gamechange', 'media', 'press-releases', 'brand-guidelines',
        'news-events', 'growthpartnerships', 'becomeaninvestor', 'globalreach',
        'whypartner', 'ourpartners', 'contactus', 'buildingtheecosystem',
        'ipindustryinsights', 'investorrelations', 'marketplace', 'howitworks',
        'ipowners', 'licensorsearchers', 'insurancepartners', 'valuationservices',
        'cantfind', 'faqs', 'termsofuse', 'privacypolicy', 'marketplacepolicies',
        'legaldisclosure', 'copyrighttrademark', 'cookiepreferences', 'refund-policy'
    ];
    $usePremiumPublicInnerTemplate = in_array($pageKey, $premiumPublicInnerPages, true);
    if ($usePremiumHomepageTemplate) {
        $publicTemplateVariant = 'homepage';
        $publicBodyClass = 'ipr-homepage';
        include __DIR__ . '/templates/public/homepage-header.php';
        include __DIR__ . '/pages/homepage-v2.php';
        include __DIR__ . '/templates/public/homepage-footer.php';
    } elseif ($usePremiumPublicInnerTemplate) {
        $publicTemplateVariant = 'inner';
        $publicBodyClass = 'public-inner-page public-page-' . preg_replace('/[^a-z0-9-]/', '-', strtolower((string)$pageKey));
        include __DIR__ . '/templates/public/homepage-header.php';
        include __DIR__ . $page;
        include __DIR__ . '/templates/public/homepage-footer.php';
    } else {
        include __DIR__ . '/templates/header.php';
        include __DIR__ . $page;
        include __DIR__ . '/templates/footer.php';
    }
    //if($isfooter) {
        
    //} else {
     //   include __DIR__ . '/templates/panelfooter.php'; // Include footer
    //}
  //  include __DIR__ . '/templates/cookie.php';
} else {
    // Serve 404 error for invalid routes
    http_response_code(404);
    include __DIR__ . '/error-pages/404.html';
    logToConsole("404 Error: Page '{$requestUri}' not found.");
    exit;
}

// Simulate a 500 Internal Server Error for testing purposes
if ($requestUri === 'test500') {
    http_response_code(500);
    include __DIR__ . '/error-pages/500.html';
    logToConsole("500 Error: Internal Server Error on '{$requestUri}'.");
    exit;
}

// Send the output and stop buffering
ob_end_flush();
?>
