<?php
/**
 * Standalone entry point for ACC Engine (Without WordPress)
 */

// 1) تعریف ثابت‌های مسیر مشابه وردپرس
define('ABSPATH', __DIR__ . '/');
define('ACC_PATH', __DIR__ . '/');
define('ACC_URL', '/acc-engine/'); // اگر پوشه پروژه شما در htdocs/acc-engine است همین درست است

// سیستم مدیریت اکشن‌ها و فیلترهای سراسری (WordPress Hook Simulator)
global $wp_actions, $wp_filters;
$wp_actions = [];
$wp_filters = [];

// 2) شبیه‌سازی توابع پایه وردپرس که پلاگین به آن‌ها نیاز دارد
if (!function_exists('add_action')) {
    function add_action($tag, $callback, $priority = 10, $accepted_args = 1) {
        global $wp_actions;
        if (!isset($wp_actions[$tag])) {
            $wp_actions[$tag] = [];
        }
        $wp_actions[$tag][$priority][] = $callback;
    }
}

if (!function_exists('do_action')) {
    function do_action($tag, ...$args) {
        global $wp_actions;
        if (!isset($wp_actions[$tag])) {
            return;
        }
        
        // مرتب‌سازی هوک‌ها بر اساس اولویت اجرای آن‌ها
        ksort($wp_actions[$tag]);
        
        foreach ($wp_actions[$tag] as $priority => $callbacks) {
            foreach ($callbacks as $callback) {
                if (is_callable($callback)) {
                    call_user_func_array($callback, $args);
                }
            }
        }
    }
}

if (!function_exists('add_filter')) {
    function add_filter($tag, $callback, $priority = 10, $accepted_args = 1) {
        global $wp_filters;
        if (!isset($wp_filters[$tag])) {
            $wp_filters[$tag] = [];
        }
        $wp_filters[$tag][$priority][] = $callback;
    }
}

if (!function_exists('apply_filters')) {
    function apply_filters($tag, $value, ...$args) {
        global $wp_filters;
        if (!isset($wp_filters[$tag])) {
            return $value;
        }
        
        ksort($wp_filters[$tag]);
        
        foreach ($wp_filters[$tag] as $priority => $callbacks) {
            foreach ($callbacks as $callback) {
                if (is_callable($callback)) {
                    // آرگومان اول مقدار ورودی فیلتر است که بروزرسانی می‌شود
                    $value = call_user_func_array($callback, array_merge([$value], $args));
                }
            }
        }
        return $value;
    }
}

if (!function_exists('wp_redirect')) {
    function wp_redirect($location, $status = 302) {
        header('Location: ' . $location, true, (int) $status);
        exit;
    }
}

if (!function_exists('wp_footer')) {
    function wp_footer() {
        do_action('wp_footer');
    }
}

if (!function_exists('wp_head')) {
    function wp_head() {
        do_action('wp_head');
    }
}

if (!function_exists('rest_url')) {
    function rest_url($path = '') {
        return ACC_URL . 'api.php/' . ltrim($path, '/');
    }
}

if (!function_exists('get_rest_url')) {
    function get_rest_url($blog_id = null, $path = '', $scheme = 'rest') {
        return ACC_URL . 'api.php/' . ltrim($path, '/');
    }
}

if (!function_exists('plugin_dir_path')) {
    function plugin_dir_path($file) {
        return dirname($file) . '/';
    }
}

if (!function_exists('plugin_dir_url')) {
    function plugin_dir_url($file) {
        return ACC_URL;
    }
}

if (!function_exists('get_query_var')) {
    function get_query_var($var) {
        return true; // چون می‌خواهیم مستقیماً SPA لود شود
    }
}

if (!function_exists('wp_create_nonce')) {
    function wp_create_nonce($action) {
        return 'standalone_nonce';
    }
}

if (!function_exists('wp_verify_nonce')) {
    function wp_verify_nonce($nonce, $action) {
        return true;
    }
}

if (!function_exists('sanitize_text_field')) {
    function sanitize_text_field($str) {
        return is_string($str) ? trim($str) : $str;
    }
}

if (!function_exists('wp_unslash')) {
    function wp_unslash($value) {
        return $value;
    }
}

if (!function_exists('esc_html')) {
    function esc_html($text) {
        return htmlspecialchars((string)$text, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('esc_attr')) {
    function esc_attr($text) {
        return htmlspecialchars((string)$text, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('esc_url')) {
    function esc_url($url) {
        return filter_var($url, FILTER_SANITIZE_URL);
    }
}

if (!function_exists('wp_json_encode')) {
    function wp_json_encode($data, $options = 0, $depth = 512) {
        return json_encode($data, $options, $depth);
    }
}

if (!function_exists('home_url')) {
    function home_url($path = '') {
        return ACC_URL . ltrim($path, '/');
    }
}

if (!function_exists('site_url')) {
    function site_url($path = '') {
        return ACC_URL . ltrim($path, '/');
    }
}

if (!function_exists('__')) {
    function __($text, $domain = null) {
        return $text;
    }
}

if (!function_exists('_e')) {
    function _e($text, $domain = null) {
        echo $text;
    }
}

// 3) شبیه‌سازی توابع نصب و هوک‌های وردپرس جهت جلوگیری از Fatal Error
if (!function_exists('register_activation_hook')) {
    function register_activation_hook($file, $callback) {
        // در حالت مستقل نیازی به اجرای خودکار نیست
    }
}

if (!function_exists('register_deactivation_hook')) {
    function register_deactivation_hook($file, $callback) {
        // خالی جهت شبیه‌سازی
    }
}

if (!function_exists('add_shortcode')) {
    function add_shortcode($tag, $callback) {}
}

if (!function_exists('get_option')) {
    function get_option($option, $default = false) {
        global $wpdb;
        if (isset($wpdb)) {
            try {
                $safe = str_replace("'", "''", $option);
                $val  = $wpdb->get_var(
                    "SELECT option_value FROM {$wpdb->prefix}options WHERE option_name = '{$safe}' LIMIT 1"
                );
                if ($val !== null && $val !== false) {
                    return maybe_unserialize($val);
                }
            } catch (\Throwable $e) {}
        }
        return $default;
    }
}

if (!function_exists('update_option')) {
    function update_option($option, $value) {
        return true;
    }
}

if (!function_exists('delete_option')) {
    function delete_option($option) {
        return true;
    }
}

if (!function_exists('plugin_basename')) {
    function plugin_basename($file) {
        return basename($file);
    }
}

if (!function_exists('is_user_logged_in')) {
    function is_user_logged_in() {
        return false;
    }
}

if (!function_exists('get_current_user_id')) {
    function get_current_user_id() {
        return 0;
    }
}

if (!function_exists('is_admin')) {
    function is_admin() {
        return false;
    }
}

if (!function_exists('wp_get_current_user')) {
    function wp_get_current_user() {
        return (object)['ID' => 0, 'user_login' => '', 'display_name' => ''];
    }
}

if (!function_exists('maybe_unserialize')) {
    function maybe_unserialize($value) {
        if (is_string($value) && strlen($value) > 1 && $value[1] === ':') {
            $unserialized = @unserialize($value);
            return ($unserialized !== false) ? $unserialized : $value;
        }
        return $value;
    }
}

// 4) شبیه‌سازی کلاس دیتابیس وردپرس ($wpdb) با PDO
class Standalone_DB {
    private $pdo;
    public $prefix = 'wp_'; // اگر پیشوند جدول‌ها چیز دیگری است، اینجا تغییر بده

    public function __construct() {
        $host    = '127.0.0.1';
        $db      = 'sademlis_ostad51';
        $user    = 'root';
        $pass    = '';
        $charset = 'utf8mb4';

        $dsn = "mysql:host=$host;dbname=$db;charset=$charset";

        try {
            $this->pdo = new PDO($dsn, $user, $pass, [
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
            ]);
        } catch (\PDOException $e) {
            die('Database connection failed: ' . $e->getMessage());
        }
    }

    public function get_results($query) {
        $stmt = $this->pdo->query($query);
        return $stmt->fetchAll();
    }

    public function get_row($query) {
        $stmt = $this->pdo->query($query);
        return $stmt->fetch();
    }

    public function get_var($query) {
        $stmt = $this->pdo->query($query);
        return $stmt->fetchColumn();
    }

    public function query($query) {
        return $this->pdo->exec($query);
    }

    public function prepare($query, ...$args) {
        if (!$args) {
            return $query;
        }

        foreach ($args as &$arg) {
            if (is_string($arg)) {
                $arg = addslashes($arg);
            } elseif (is_null($arg)) {
                $arg = 'NULL';
            }
        }

        $query = str_replace('%s', "'%s'", $query);
        $query = str_replace('%d', '%u', $query);

        return vsprintf($query, $args);
    }

    public function insert($table, $data) {
        $columns = implode(', ', array_keys($data));
        $placeholders = implode(', ', array_fill(0, count($data), '?'));

        $sql = "INSERT INTO {$table} ({$columns}) VALUES ({$placeholders})";
        $stmt = $this->pdo->prepare($sql);
        return $stmt->execute(array_values($data));
    }

    public function update($table, $data, $where) {
        $setParts = [];
        foreach ($data as $key => $value) {
            $setParts[] = "{$key} = ?";
        }

        $whereParts = [];
        foreach ($where as $key => $value) {
            $whereParts[] = "{$key} = ?";
        }

        $sql = "UPDATE {$table} SET " . implode(', ', $setParts) . " WHERE " . implode(' AND ', $whereParts);
        $stmt = $this->pdo->prepare($sql);

        return $stmt->execute(array_merge(array_values($data), array_values($where)));
    }

    public function delete($table, $where) {
        $whereParts = [];
        foreach ($where as $key => $value) {
            $whereParts[] = "{$key} = ?";
        }

        $sql = "DELETE FROM {$table} WHERE " . implode(' AND ', $whereParts);
        $stmt = $this->pdo->prepare($sql);

        return $stmt->execute(array_values($where));
    }

    public function get_pdo() {
        return $this->pdo;
    }
}

global $wpdb;
$wpdb = new Standalone_DB();

// 5) لود کردن فایل‌های اصلی پلاگین
require_once ACC_PATH . 'includes/install.php';
require_once ACC_PATH . 'includes/helpers/InventoryIntegration.php';
require_once ACC_PATH . 'includes/helpers/acl-scope-registry.php';
require_once ACC_PATH . 'includes/helpers/acl-scope-enforce.php';
require_once ACC_PATH . 'includes/helpers/acl-functions.php';

require_once ACC_PATH . 'includes/controllers/class-acc-auth-controller.php';
require_once ACC_PATH . 'includes/controllers/class-acc-dashboard-controller.php';
require_once ACC_PATH . 'includes/controllers/class-acc-smartflow-controller.php';
require_once ACC_PATH . 'includes/controllers/ACC_Accounting_Controller.php';
require_once ACC_PATH . 'includes/controllers/ACC_Sales_Controller.php';
require_once ACC_PATH . 'includes/controllers/ACC_Purchase_Controller.php';
require_once ACC_PATH . 'includes/controllers/ACC_Payroll_Controller.php';
require_once ACC_PATH . 'includes/controllers/TileProxy_Controller.php';
require_once ACC_PATH . 'includes/controllers/CRM_Controller.php';
require_once ACC_PATH . 'includes/controllers/CPM_Calculator.php';
require_once ACC_PATH . 'includes/controllers/PC_Controller.php';
require_once ACC_PATH . 'includes/controllers/GIS_Controller.php';
require_once ACC_PATH . 'includes/controllers/Inventory_Controller.php';
require_once ACC_PATH . 'includes/controllers/UserPrefs_Controller.php';
require_once ACC_PATH . 'includes/controllers/ACL_Controller.php';
require_once ACC_PATH . 'includes/controllers/GIS_Locations_Controller.php';
require_once ACC_PATH . 'includes/controllers/HR_Controller.php';
require_once ACC_PATH . 'includes/controllers/Workflow_Controller.php';
require_once ACC_PATH . 'includes/controllers/Shipping_Controller.php';
require_once ACC_PATH . 'includes/controllers/Assets_Controller.php';
require_once ACC_PATH . 'includes/controllers/Commission_Controller.php';
require_once ACC_PATH . 'includes/controllers/Contract_Controller.php';
require_once ACC_PATH . 'includes/controllers/UnitSales_Controller.php';
require_once ACC_PATH . 'includes/controllers/Treasury_Controller.php';
require_once ACC_PATH . 'includes/controllers/Permits_Controller.php';
require_once ACC_PATH . 'includes/controllers/WP_Products_Controller.php';
require_once ACC_PATH . 'includes/controllers/WP_Orders_Controller.php';
require_once ACC_PATH . 'includes/controllers/Projects_Controller.php';
require_once ACC_PATH . 'includes/controllers/Chat_Controller.php';
require_once ACC_PATH . 'includes/controllers/SR_Controller.php';
require_once ACC_PATH . 'includes/controllers/Public_Auth_Controller.php';
require_once ACC_PATH . 'includes/controllers/CPM_Assignments_Controller.php';
require_once ACC_PATH . 'includes/controllers/CPM_Controller.php';
require_once ACC_PATH . 'includes/controllers/CPM_Dependencies_Controller.php';
require_once ACC_PATH . 'includes/controllers/CPM_Resources_Controller.php';
require_once ACC_PATH . 'includes/controllers/CPM_WBS_Controller.php';
require_once ACC_PATH . 'includes/runtime/ACC_Runtime_Industrial_REST_API_Full.php';
require_once ACC_PATH . 'includes/runtime/ACC_Runtime_Query_Engine.php';
require_once ACC_PATH . 'includes/runtime/ACC_Runtime_Permission_Engine.php';
require_once ACC_PATH . 'includes/runtime/ACC_Runtime_Workflow_API.php';

// لود کدهای مربوط به تزریق ویجت (که بالاتر ارسال کرده بودید و روی هوک wp_footer ثبت می‌شود)
// اگر کد تزریق ویجت در فایل جداگانه است مطمئن شوید قبل از قالب لود شده باشد.

// 6) لود مستقیم فایل قالب SPA
require_once ACC_PATH . 'templates/spa.php';
