<?php

class ChainPay_Admin {
    
    private $license;
    private $subscription;
    private $usage;
    
    public function __construct() {
        $this->license = new ChainPay_License();
        $this->subscription = new ChainPay_Subscription();
        $this->usage = new ChainPay_Usage_Tracker();
        
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_assets'));
    }
    
    public function add_admin_menu() {
        add_menu_page(
            'ChainPay License',
            'ChainPay License',
            'manage_options',
            'chainpay-license',
            array($this, 'render_dashboard'),
            'dashicons-yes-alt',
            30
        );
        
        add_submenu_page(
            'chainpay-license',
            'Dashboard',
            'Dashboard',
            'manage_options',
            'chainpay-license',
            array($this, 'render_dashboard')
        );
        
        add_submenu_page(
            'chainpay-license',
            'Licenses',
            'Licenses',
            'manage_options',
            'chainpay-licenses',
            array($this, 'render_licenses_page')
        );
        
        add_submenu_page(
            'chainpay-license',
            'Subscriptions',
            'Subscriptions',
            'manage_options',
            'chainpay-subscriptions',
            array($this, 'render_subscriptions_page')
        );
        
        add_submenu_page(
            'chainpay-license',
            'Plans',
            'Plans',
            'manage_options',
            'chainpay-plans',
            array($this, 'render_plans_page')
        );
        
        add_submenu_page(
            'chainpay-license',
            'Settings',
            'Settings',
            'manage_options',
            'chainpay-settings',
            array($this, 'render_settings_page')
        );
    }
    
    public function enqueue_assets($hook) {
        if (strpos($hook, 'chainpay') === false) {
            return;
        }
        
        wp_enqueue_style(
            'chainpay-admin',
            CHAINPAY_LICENSE_URL . 'assets/css/admin.css',
            array(),
            CHAINPAY_LICENSE_VERSION
        );
        
        wp_enqueue_script(
            'chainpay-admin',
            CHAINPAY_LICENSE_URL . 'assets/js/admin.js',
            array('jquery'),
            CHAINPAY_LICENSE_VERSION,
            true
        );
    }
    
    public function render_dashboard() {
        $stats = $this->get_dashboard_stats();
        include CHAINPAY_LICENSE_PATH . 'admin/views/dashboard.php';
    }
    
    public function render_licenses_page() {
        $action = isset($_GET['action']) ? sanitize_text_field($_GET['action']) : 'list';
        $license_id = isset($_GET['id']) ? absint($_GET['id']) : 0;
        
        if ($action === 'edit' && $license_id) {
            $license = $this->license->get($license_id);
            include CHAINPAY_LICENSE_PATH . 'admin/views/license-edit.php';
        } elseif ($action === 'create') {
            include CHAINPAY_LICENSE_PATH . 'admin/views/license-create.php';
        } elseif ($action === 'view' && $license_id) {
            $license = $this->license->get($license_id);
            $usage = $this->usage->get_all_usage($license_id);
            include CHAINPAY_LICENSE_PATH . 'admin/views/license-view.php';
        } else {
            $licenses = $this->license->get_all(array('limit' => 50));
            $total = $this->license->count();
            $active = $this->license->count(array('status' => 'active'));
            $inactive = $this->license->count(array('status' => 'inactive'));
            include CHAINPAY_LICENSE_PATH . 'admin/views/licenses-list.php';
        }
    }
    
    public function render_subscriptions_page() {
        $subscriptions = $this->subscription->get_all(array('limit' => 50));
        $total = $this->subscription->count();
        $active = $this->subscription->count(array('status' => 'active'));
        $canceled = $this->subscription->count(array('status' => 'canceled'));
        include CHAINPAY_LICENSE_PATH . 'admin/views/subscriptions-list.php';
    }
    
    public function render_plans_page() {
        global $wpdb;
        $plans_table = $wpdb->prefix . 'chainpay_plans';
        $plans = $wpdb->get_results("SELECT * FROM {$plans_table} ORDER BY price ASC");
        include CHAINPAY_LICENSE_PATH . 'admin/views/plans-list.php';
    }
    
    public function render_settings_page() {
        $api_key = get_option('chainpay_api_key', '');
        $api_secret = get_option('chainpay_api_secret', '');
        $webhook_url = get_option('chainpay_webhook_url', '');
        $auto_renew = get_option('chainpay_auto_renew', true);
        
        if (isset($_POST['chainpay_save_settings']) && wp_verify_nonce($_POST['chainpay_nonce'], 'chainpay_settings')) {
            update_option('chainpay_api_key', sanitize_text_field($_POST['api_key']));
            update_option('chainpay_api_secret', sanitize_text_field($_POST['api_secret']));
            update_option('chainpay_webhook_url', esc_url_raw($_POST['webhook_url']));
            update_option('chainpay_auto_renew', (bool) $_POST['auto_renew']);
            echo '<div class="notice notice-success"><p>Settings saved successfully.</p></div>';
        }
        
        include CHAINPAY_LICENSE_PATH . 'admin/views/settings.php';
    }
    
    private function get_dashboard_stats() {
        global $wpdb;
        $plans_table = $wpdb->prefix . 'chainpay_plans';
        $licenses_table = $wpdb->prefix . 'chainpay_licenses';
        $subscriptions_table = $wpdb->prefix . 'chainpay_subscriptions';
        
        return array(
            'total_licenses' => $this->license->count(),
            'active_licenses' => $this->license->count(array('status' => 'active')),
            'total_subscriptions' => $this->subscription->count(),
            'active_subscriptions' => $this->subscription->count(array('status' => 'active')),
            'total_plans' => $wpdb->get_var("SELECT COUNT(*) FROM {$plans_table} WHERE is_active = 1"),
            'monthly_revenue' => $wpdb->get_var($wpdb->prepare(
                "SELECT SUM(amount) FROM {$subscriptions_table} WHERE status = 'active' AND billing_cycle = %s",
                'monthly'
            )) ?: 0
        );
    }
    
    public function ajax_create_license() {
        check_ajax_referer('chainpay_admin_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Permission denied');
        }
        
        $result = $this->license->create(array(
            'user_email' => sanitize_email($_POST['email']),
            'user_domain' => sanitize_text_field($_POST['domain']),
            'plan_id' => absint($_POST['plan_id']),
            'max_domains' => absint($_POST['max_domains']),
            'expiration_date' => sanitize_text_field($_POST['expiration_date'])
        ));
        
        if (is_wp_error($result)) {
            wp_send_json_error($result->get_error_message());
        }
        
        $license = $this->license->get($result);
        
        wp_send_json_success(array(
            'message' => 'License created successfully',
            'license' => $license
        ));
    }
    
    public function ajax_delete_license() {
        check_ajax_referer('chainpay_admin_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Permission denied');
        }
        
        $license_id = absint($_POST['license_id']);
        $result = $this->license->delete($license_id);
        
        if (!$result) {
            wp_send_json_error('Failed to delete license');
        }
        
        wp_send_json_success('License deleted successfully');
    }
}
