<?php
if (!file_exists("core/system/system_file/install.lock"))
{
        if (file_exists('core/system/system_file/setup.php') && !isset($_SESSION['install_rtl']) && !isset($_COOKIE['install_rtl']))
        {
                $percheck = "IDPAL";
                include('core/system/system_file/setup.php');
                exit;
        } else {
                $percheck = "IDPAL";
                include('core/system/system_file/install.php');
                exit;
        }
}

/* ------------------------------------------------------------------------
 * IDPAL v3.1 - UNIVERSAL FRONT-CONTROLLER ROUTER
 * ------------------------------------------------------------------------
 * The original routing relied on the web-server rewrite rule mapping
 * "/panel/login" to "panel/login.php". On servers where that per-file
 * rule does not fire (nginx without a matching try_files, IIS, php -S
 * without a router, PATH_INFO style handling, trailing slashes ...),
 * every URL fell through to index.php and the homepage was displayed
 * instead of the requested page (login / register / panels ...).
 *
 * This router reproduces the exact .htaccess behaviour in pure PHP, so
 * the application works identically on ANY server - with or without
 * working mod_rewrite:
 *   - it NEVER trusts SCRIPT_NAME (some SAPIs rewrite it, e.g. the
 *     PHP built-in server turns "/panel/login" into script
 *     "/panel/index.php" + PATH_INFO "/login");
 *   - it walks the URL from the longest suffix to the shortest, so
 *     sub-directory installs ("/shop/panel/login") also work;
 *   - it only ever dispatches to REAL page files inside whitelisted
 *     application directories - nothing else is ever executed.
 * ---------------------------------------------------------------------- */
if (!function_exists('idpal_front_router'))
{
        function idpal_front_router()
        {
                if (!isset($_SERVER['REQUEST_URI'])) { return null; }

                $uri_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
                $uri_path = urldecode((string) $uri_path);
                $uri_path = trim($uri_path, '/');
                if ($uri_path === '') { return null; } // homepage - classic flow

                // Accept ONLY safe URL characters; dots are allowed solely as
                // an optional ".php" suffix. This blocks traversal & injection.
                if (!preg_match('#^[A-Za-z0-9_\-]+(?:/[A-Za-z0-9_\-]+){0,3}(\.php)?$#', $uri_path)) { return null; }

                $root = __DIR__;

                // Security whitelist: only application entry directories may
                // ever be dispatched through this router.
                $allowed_dirs = array('panel', 'manage', 'public', 'webservice');

                $segments = explode('/', $uri_path);
                $total    = count($segments);

                for ($i = 0; $i < $total; $i++)
                {
                        $top = $segments[$i];
                        if (!in_array($top, $allowed_dirs, true)) { continue; }

                        $sub = implode('/', array_slice($segments, $i));
                        $base_file = $root . '/' . $sub;

                        if (substr($sub, -4) === '.php')
                        {
                                $candidates = array($base_file);          // explicit "x.php" URL
                        }
                        else
                        {
                                $candidates = array($base_file . '.php'); // /panel/login -> panel/login.php

                                if ($i === $total - 1)
                                {
                                        $candidates[] = $base_file . '/index.php'; // /panel -> panel/index.php
                                }
                        }

                        foreach ($candidates as $target)
                        {
                                if (is_file($target) && !is_dir($target))
                                {
                                        // IMPORTANT: do NOT require() here! We are
                                        // inside a function - requiring the page here
                                        // would run its whole bootstrap in function
                                        // scope, breaking every "global" variable
                                        // (like $db). Return the path instead; the
                                        // caller requires it at TOP level - exactly
                                        // like Apache does.
                                        return $target;
                                }
                        }
                }

                // No match -> fall through to the classic index.php flow
                // (payment routes, private links, homepage).
                return null;
        }
}

$idpal_route_target = idpal_front_router();

if ($idpal_route_target !== null)
{
        chdir(dirname($idpal_route_target)); // pages use Apache-style relative includes
        require $idpal_route_target;         // TOP-LEVEL require = Apache parity
        exit;
}

require_once('include/function.php');

if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] != "")
{
        $webservice_uri = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https" : "http";  
        $webservice_uri = "{$webservice_uri}://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";       
        $webservice_uri = str_replace($CONF['site_url'], "", $webservice_uri);
        $webservice_uri = str_replace($CONF['webservice_url'], "", $webservice_uri);
        $webservice_uri = ltrim($webservice_uri, "/");
        $webservice_uri = rtrim($webservice_uri, "/");
        $webservice_uri = explode("/",$webservice_uri);
        
        if (isset($webservice_uri[0]) && strtolower($webservice_uri[0]) == "startpay" && isset($webservice_uri[1]) && $webservice_uri[1] != "")
        {
                //redirect("{$CONF['webservice_url']}/webservice/startPayment.php?au={$webservice_uri[1]}");
                $payment_au             = $webservice_uri[1];
                $payment_switch         = (isset($webservice_uri[2]) && $webservice_uri[2] != "") ? $webservice_uri[2] : "";

                include("webservice/startPayment.php");
                exit;
        }

        if (isset($webservice_uri[0]) && $webservice_uri[0] == "invoice" && isset($webservice_uri[1]) && $webservice_uri[1] == "request")
        {
                require_once("webservice/invoice/request.php");
                exit;
        }

        if (isset($webservice_uri[0]) && $webservice_uri[0] == "invoice" && isset($webservice_uri[1]) && $webservice_uri[1] == "check")
        {
                require_once("webservice/invoice/check.php");
                exit;
        }

        if (isset($webservice_uri[0]) && $webservice_uri[0] == "invoice" && isset($webservice_uri[1]) && $webservice_uri[1] == "pay")
        {
                //redirect("{$CONF['webservice_url']}/webservice/startPayment.php?au={$webservice_uri[2]}");
                $payment_au             = $webservice_uri[2];
                $payment_switch         = (isset($webservice_uri[3]) && $webservice_uri[3] != "") ? $webservice_uri[3] : "";

                include("webservice/startPayment.php");
                exit;
        }

        // bitpay.ir
        if (isset($webservice_uri[0]) && $webservice_uri[0] == "payment" && isset($webservice_uri[1]) && $webservice_uri[1] == "gateway-send")
        {
                require_once("webservice/payment/gateway-send.php");
                exit;
        }

        if (isset($webservice_uri[0]) && $webservice_uri[0] == "payment" && isset($webservice_uri[1]) && $webservice_uri[1] == "gateway-result-second")
        {
                require_once("webservice/payment/gateway-result-second.php");
                exit;
        }
        
        if (isset($webservice_uri[0]) && $webservice_uri[0] == "payment" && isset($webservice_uri[1]) && substr($webservice_uri[1], 0, 8) === "gateway-")
        {
                $webservice_uri_2 = str_replace("gateway-", "", $webservice_uri[1]);
                redirect("{$CONF['webservice_url']}/webservice/startPayment.php?au={$webservice_uri_2}");
                $payment_au             = $webservice_uri_2;
                $payment_switch         = (isset($webservice_uri[2]) && $webservice_uri[2] != "") ? $webservice_uri[2] : "";

                include("webservice/startPayment.php");
                exit;
        }
        // bitpay.ir

        // zarinpal
        if (isset($webservice_uri[0]) && $webservice_uri[0] == "pg" && isset($webservice_uri[1]) && $webservice_uri[1] == "services")
        {
                header("HTTP/1.1 301 Moved Permanently");
                header("Location: {$CONF['webservice_url']}/webservice/soap/?wsdl"); 
                redirect("{$CONF['webservice_url']}/webservice/soap/?wsdl");
                exit;
        }

        if (isset($webservice_uri[0]) && $webservice_uri[0] == "pg" && isset($webservice_uri[1]) && $webservice_uri[1] == "StartPay")
        {
                //redirect("{$CONF['webservice_url']}/webservice/startPayment.php?au={$webservice_uri[2]}");
                $payment_au             = $webservice_uri[2];
                $payment_switch         = (isset($webservice_uri[3]) && $webservice_uri[3] != "") ? $webservice_uri[3] : "";

                include("webservice/startPayment.php");
                exit;
        }

        if (isset($webservice_uri[0]) && $webservice_uri[0] == "pg" && isset($webservice_uri[3]) && $webservice_uri[3] == "PaymentRequest.json")
        {
                require_once("webservice/rest/PaymentReques.php");
                exit;
        }

        if (isset($webservice_uri[0]) && $webservice_uri[0] == "pg" && isset($webservice_uri[3]) && $webservice_uri[3] == "PaymentVerification.json")
        {
                require_once("webservice/rest/PaymentVerification.php");
                exit;
        }
        // zarinpal
        
        // pay.ir NEW
        if (isset($webservice_uri[0]) && $webservice_uri[0] == "pg" && isset($webservice_uri[1]) && $webservice_uri[1] == "send")
        {
                require_once("webservice/pg/send.php");
                exit;
        }

        if (isset($webservice_uri[0]) && $webservice_uri[0] == "pg" && isset($webservice_uri[1]) && $webservice_uri[1] == "verify")
        {
                require_once("webservice/pg/verify.php");
                exit;
        }
        
        if (isset($webservice_uri[0]) && $webservice_uri[0] == "pg" && isset($webservice_uri[1]) && $webservice_uri[1] != "")
        {
                //redirect("{$CONF['webservice_url']}/webservice/startPayment.php?au={$webservice_uri[2]}");
                $payment_au             = $webservice_uri[1];
                $payment_switch         = (isset($webservice_uri[2]) && $webservice_uri[2] != "") ? $webservice_uri[2] : "";

                include("webservice/startPayment.php");
                exit;
        }
        // pay.ir NEW
}

$link_code              = $_SERVER['REQUEST_URI'];
$link_code              = str_replace('/', '', $link_code);

$pv_id                  = explode("@",$link_code);
$pv_id                  = (isset($pv_id[1]) && $pv_id[1] != '') ? $pv_id[1] : '';

if (isset($_GET['linkBack']) && $_GET['linkBack'] > 0)
{
        $InvoiceNumber          = $_GET['linkBack'];

        $db_private_trans       = $db->query("SELECT * FROM `private_trans` WHERE `InvoiceNumber` = '{$InvoiceNumber}' LIMIT 1");
        $private_trans          = $db_private_trans->fetch_assoc();
        
        $db_private_link        = $db->query("SELECT * FROM `private_link` WHERE `user` = '{$private_trans['user']}' LIMIT 1");
        $private_link           = $db_private_link->fetch_assoc();
        
        $db_pvl_user            = $db->query("SELECT * FROM `users` WHERE `id` = '{$private_link['user']}' LIMIT 1");
        $pvl_user                       = $db_pvl_user->fetch_assoc();

        require_once("panel/pay_back.php");
        exit;
}

if (isset($pv_id) && $pv_id != '')
{       
        $db_private_link        = $db->query("SELECT * FROM `private_link` WHERE `pay_id` = '{$pv_id}' LIMIT 1");
        $private_link           = $db_private_link->fetch_assoc();
        
        $db_pvl_user            = $db->query("SELECT * FROM `users` WHERE `id` = '{$private_link['user']}' LIMIT 1");
        $pvl_user                       = $db_pvl_user->fetch_assoc();
        
        require_once("panel/pay.php");
        exit;
}

$cms_type_setting = setting('cms');

if (isset($cms_type_setting) && $cms_type_setting == "wordpress")
{
        if (file_exists(dirname( __FILE__ ) . '/wp-blog-header.php'))
        {
                define('WP_USE_THEMES', true);
                require( dirname( __FILE__ ) . '/wp-blog-header.php' );
        } else {
                die("Error include wordpress file's");
        }
} else {
        $site_tpl = setting('site_template');
        $site_tpl = (isset($site_tpl) && $site_tpl != "") ? $site_tpl : "default";
        $template = "template/". $site_tpl;

        require_once("template/". $site_tpl ."/header.php");
        require_once("template/". $site_tpl ."/home.php");
        require_once("template/". $site_tpl ."/footer.php");
}
?>
