<?php
/**
 * WordPress Plugin - Plugin Management API Endpoints
 * إدارة البلاجنز - واجهة APIs
 */

class CSM_Plugin_Management_API {
    
    private $plugin_manager;
    private $auth_manager;
    
    public function __construct() {
        $this->plugin_manager = new CSM_Plugin_Manager();
        $this->auth_manager = new CSM_Auth_Manager();
        add_action('rest_api_init', array($this, 'register_routes'));
    }
    
    /**
     * تسجيل المسارات API
     */
    public function register_routes() {
        $namespace = 'csm/v1';
        
        // جلب قائمة البلاجنز المثبتة
        register_rest_route($namespace, '/plugins-control/list', array(
            'methods' => 'GET',
            'callback' => array($this, 'get_plugins'),
            'permission_callback' => '__return_true'
        ));

        // تفعيل/إلغاء تفعيل بلاجن
        register_rest_route($namespace, '/plugins-control/toggle', array(
            'methods' => 'POST',
            'callback' => array($this, 'toggle_plugin'),
            'permission_callback' => '__return_true'
        ));
        
        
        // تفعيل/إلغاء تفعيل بلاجن
        register_rest_route($namespace, '/plugins-control/auto-update-toggle', array(
            'methods' => 'POST',
            'callback' => array($this, 'auto_update_toggle_plugin'),
            'permission_callback' => '__return_true'
        ));

        // تحديث بلاجن من رابط خارجي
        register_rest_route($namespace, '/plugins-control/update-from-url', array(
            'methods' => 'POST',
            'callback' => array($this, 'update_plugin_from_url'),
            'permission_callback' => '__return_true'
        ));
        
        // إعادة تنصيب بلاجن من المتجر
        register_rest_route($namespace, '/plugins-control/reinstall', array(
            'methods' => 'POST',
            'callback' => array($this, 'reinstall_plugin'),
            'permission_callback' => '__return_true'
        ));
        
        // حذف بلاجن
        register_rest_route($namespace, '/plugins-control/delete', array(
            'methods' => 'POST',
            'callback' => array($this, 'delete_plugin'),
            'permission_callback' => '__return_true'
        ));
    }
    
    /**
     * فحص الصلاحية المضمن
     */
    private function check_auth_inline($request) {
        return $this->auth_manager->validate_request($request);
    }
    
    /**
     * جلب قائمة البلاجنز المثبتة مع فلترة
     */
    public function get_plugins($request) {
        if (is_wp_error($check = $this->check_auth_inline($request))) {
            return $check;
        }
        
        $args = array(
            'status' => $request->get_param('status'),
            'search' => $request->get_param('search'),
            'page' => $request->get_param('page') ?: 1,
            'per_page' => $request->get_param('per_page') ?: 50,
            'orderby' => $request->get_param('orderby') ?: 'name',
            'order' => $request->get_param('order') ?: 'ASC'
        );
        
        $result = $this->plugin_manager->get_installed_plugins($args);
        
        return $this->success_response($result, 'Successfully');
    }

    /**
     * تفعيل/إلغاء تفعيل بلاجن
     */
    public function toggle_plugin($request) {
        if (is_wp_error($check = $this->check_auth_inline($request))) {
            return $check;
        }
        
        $plugin_file = $this->decode_plugin_file($request->get_param('plugin_file'));
        $plugin_status = in_array($request->get_param('plugin_status'), ['active','deactive', 'toggle']) ? $request->get_param('plugin_status') : 'deactive';

        $network_wide = filter_var($request->get_param('network_wide'), FILTER_VALIDATE_BOOLEAN);
        
        $result = $this->plugin_manager->toggle_plugin($plugin_file, $plugin_status, $network_wide);
        
        if (is_wp_error($result)) {
            return $this->error_response($result->get_error_message(), 400);
        }
        
        $this->log_activity('plugin_toggle', null, $result);
        
        return $this->success_response($result, 'Plugin status changed successfully');
    }

    /**
     * تفعيل/إلغاء تفعيل التحديث التلقائي
     */
    public function auto_update_toggle_plugin($request) {
        if (is_wp_error($check = $this->check_auth_inline($request))) {
            return $check;
        }
        
        $plugin_file = $this->decode_plugin_file($request->get_param('plugin_file'));
        $plugin_status = in_array($request->get_param('plugin_status'), ['active','deactive', 'toggle']) ? $request->get_param('plugin_status') : 'deactive';

        $network_wide = filter_var($request->get_param('network_wide'), FILTER_VALIDATE_BOOLEAN);
        
        $result = $this->plugin_manager->auto_update_toggle_plugin($plugin_file, $plugin_status, $network_wide);
        
        if (is_wp_error($result)) {
            return $this->error_response($result->get_error_message(), 400);
        }
        
        $this->log_activity('plugin_toggle', null, $result);
        
        return $this->success_response($result, 'Plugin Auto Update status changed successfully');
    }
    
    /**
     * تحديث بلاجن من رابط خارجي
     */
    public function update_plugin_from_url($request) {
        if (is_wp_error($check = $this->check_auth_inline($request))) {
            return $check;
        }
        
        $plugin_file        = $this->decode_plugin_file($request->get_param('plugin_file'));
        $download_url       = $request->get_param('download_url');
        $backup             = filter_var($request->get_param('backup'), FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
        $backup             = $backup !== null ? $backup : false;
        
        // التحقق من صحة الرابط
        if (empty($download_url) || !filter_var($download_url, FILTER_VALIDATE_URL)) {
            return $this->error_response('Valid download URL is required', 400);
        }
        
        // التحقق من امتداد الملف
        if (!$this->is_valid_plugin_file($download_url)) {
            return $this->error_response('Invalid plugin file format. Only .zip files are allowed', 400);
        }
        
        $result = $this->plugin_manager->update_plugin_from_url($plugin_file, $download_url, $backup);
        
        if (is_wp_error($result)) {
            return $this->error_response($result->get_error_message(), 400);
        }
        
        $this->log_activity('plugin_update_external', null, array(
            'plugin' => $plugin_file,
            'download_url' => $download_url,
            'backup_created' => $backup
        ));
        
        return $this->success_response($result, 'Plugin updated successfully from external URL');
    }
    
    /**
     * إعادة تنصيب بلاجن من المتجر
     */
    public function reinstall_plugin($request) {
        if (is_wp_error($check = $this->check_auth_inline($request))) {
            return $check;
        }
        
        $plugin_file    = $this->decode_plugin_file($request->get_param('plugin_file'));
        $force          = filter_var($request->get_param('force'), FILTER_VALIDATE_BOOLEAN);
        
        $result = $this->plugin_manager->reinstall_plugin($plugin_file, $force);
        
        if (is_wp_error($result)) {
            return $this->error_response($result->get_error_message(), 400);
        }
        
        $this->log_activity('plugin_reinstall', null, array(
            'plugin' => $plugin_file,
            'force' => $force
        ));
        
        return $this->success_response($result, 'Plugin reinstalled successfully');
    }
    
    /**
     * حذف بلاجن
     */
    public function delete_plugin($request) {
        if (is_wp_error($check = $this->check_auth_inline($request))) {
            return $check;
        }
        
        $plugin_file = $this->decode_plugin_file($request->get_param('plugin_file'));
        $force      = filter_var($request->get_param('force'), FILTER_VALIDATE_BOOLEAN);
        
        $result = $this->plugin_manager->delete_plugin($plugin_file, $force);
        
        if (is_wp_error($result)) {
            return $this->error_response($result->get_error_message(), 400);
        }
        
        $this->log_activity('plugin_delete', null, array(
            'plugin' => $plugin_file
        ));
        
        return $this->success_response($result, 'Plugin Deleted successfully');
    }
        
    /**
     * فك تشفير اسم ملف البلاجن من URL
     */
    private function decode_plugin_file($encoded_file) {
        // فك التشفير base64 إذا كان مشفراً
        $decoded = base64_decode($encoded_file, true);
        if ($decoded !== false && base64_encode($decoded) === $encoded_file) {
            return $decoded;
        }
        
        // أو استخدام urldecode للرموز المشفرة في URL
        return urldecode($encoded_file);
    }

    
    
    /**
     * التحقق من صحة ملف البلاجن
     */
    private function is_valid_plugin_file($url) {
        $parsed_url = parse_url($url);
        $path = isset($parsed_url['path']) ? $parsed_url['path'] : '';
        $extension = pathinfo($path, PATHINFO_EXTENSION);
        
        return strtolower($extension) === 'zip';
    }
    
    /**
     * إرسال استجابة نجاح
     */
    private function success_response($data, $message = 'Success', $status = 200) {
        return new WP_REST_Response(array(
            'success' => true,
            'message' => $message,
            'data' => $data,
            'timestamp' => current_time('mysql')
        ), $status);
    }
    
    /**
     * إرسال استجابة خطأ
     */
    private function error_response($message, $status = 400, $code = null) {
        return new WP_REST_Response(array(
            'success' => false,
            'message' => $message,
            'error_code' => $code,
            'timestamp' => current_time('mysql')
        ), $status);
    }

    /**
     * تسجيل الأنشطة (للمراجعة)
     */
    private function log_activity($action, $plugin_file = null, $details = array()) {
        $log_data = array(
            'action' => $action,
            'plugin_file' => $plugin_file,
            'admin_id' => get_current_user_id(),
            'timestamp' => current_time('mysql'),
            'ip_address' => $_SERVER['REMOTE_ADDR'],
            'user_agent' => $_SERVER['HTTP_USER_AGENT'],
            'details' => wp_json_encode($details)
        );
        
        // يمكن حفظ هذه البيانات في جدول منفصل للمراجعة
        do_action('csm_plugin_activity_logged', $log_data);
    }
   
}

new CSM_Plugin_Management_API();