<?php

class ChainPay_API {
    
    private $namespace = 'chainpay-license/v1';
    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();
    }
    
    public function register_routes() {
        register_rest_route($this->namespace, '/validate', array(
            'methods' => 'POST',
            'callback' => array($this, 'validate_license'),
            'permission_callback' => '__return_true'
        ));
        
        register_rest_route($this->namespace, '/activate', array(
            'methods' => 'POST',
            'callback' => array($this, 'activate_license'),
            'permission_callback' => '__return_true'
        ));
        
        register_rest_route($this->namespace, '/deactivate', array(
            'methods' => 'POST',
            'callback' => array($this, 'deactivate_license'),
            'permission_callback' => '__return_true'
        ));
        
        register_rest_route($this->namespace, '/license', array(
            'methods' => 'GET',
            'callback' => array($this, 'get_license_info'),
            'permission_callback' => '__return_true'
        ));
        
        register_rest_route($this->namespace, '/usage', array(
            'methods' => 'POST',
            'callback' => array($this, 'track_usage'),
            'permission_callback' => '__return_true'
        ));
        
        register_rest_route($this->namespace, '/usage/check', array(
            'methods' => 'POST',
            'callback' => array($this, 'check_usage_limit'),
            'permission_callback' => '__return_true'
        ));
        
        register_rest_route($this->namespace, '/plans', array(
            'methods' => 'GET',
            'callback' => array($this, 'get_plans'),
            'permission_callback' => '__return_true'
        ));
        
        register_rest_route($this->namespace, '/subscribe', array(
            'methods' => 'POST',
            'callback' => array($this, 'create_subscription'),
            'permission_callback' => '__return_true'
        ));
        
        register_rest_route($this->namespace, '/subscription/cancel', array(
            'methods' => 'POST',
            'callback' => array($this, 'cancel_subscription'),
            'permission_callback' => '__return_true'
        ));
    }
    
    public function validate_license($request) {
        $license_key = sanitize_text_field($request->get_param('license_key'));
        $domain = sanitize_text_field($request->get_param('domain'));
        
        if (empty($license_key)) {
            return new WP_REST_Response(array(
                'success' => false,
                'error' => 'License key is required'
            ), 400);
        }
        
        $validation = $this->license->validate($license_key, $domain);
        
        if (is_wp_error($validation)) {
            return new WP_REST_Response(array(
                'success' => false,
                'error' => $validation->get_error_message()
            ), 400);
        }
        
        $plan = $this->get_plan($validation->plan_id);
        $limits = $plan ? maybe_unserialize($plan->limits) : array();
        
        return new WP_REST_Response(array(
            'success' => true,
            'valid' => true,
            'license' => array(
                'key' => $validation->license_key,
                'status' => $validation->status,
                'expiration' => $validation->expiration_date,
                'plan' => $plan ? $plan->name : 'N/A',
                'features' => $plan ? maybe_unserialize($plan->features) : array(),
                'limits' => $limits
            )
        ), 200);
    }
    
    public function activate_license($request) {
        $license_key = sanitize_text_field($request->get_param('license_key'));
        $domain = sanitize_text_field($request->get_param('domain'));
        $email = sanitize_email($request->get_param('email'));
        
        if (empty($license_key) || empty($domain)) {
            return new WP_REST_Response(array(
                'success' => false,
                'error' => 'License key and domain are required'
            ), 400);
        }
        
        $result = $this->license->activate($license_key, $domain, $email);
        
        if (is_wp_error($result)) {
            return new WP_REST_Response(array(
                'success' => false,
                'error' => $result->get_error_message()
            ), 400);
        }
        
        return new WP_REST_Response(array(
            'success' => true,
            'message' => 'License activated successfully',
            'activation_date' => $result->activation_date
        ), 200);
    }
    
    public function deactivate_license($request) {
        $license_key = sanitize_text_field($request->get_param('license_key'));
        $domain = sanitize_text_field($request->get_param('domain'));
        
        if (empty($license_key)) {
            return new WP_REST_Response(array(
                'success' => false,
                'error' => 'License key is required'
            ), 400);
        }
        
        $result = $this->license->deactivate($license_key, $domain);
        
        if (is_wp_error($result)) {
            return new WP_REST_Response(array(
                'success' => false,
                'error' => $result->get_error_message()
            ), 400);
        }
        
        return new WP_REST_Response(array(
            'success' => true,
            'message' => 'License deactivated successfully'
        ), 200);
    }
    
    public function get_license_info($request) {
        $license_key = sanitize_text_field($request->get_param('license_key'));
        
        if (empty($license_key)) {
            return new WP_REST_Response(array(
                'success' => false,
                'error' => 'License key is required'
            ), 400);
        }
        
        $license = $this->license->get_by_key($license_key);
        
        if (!$license) {
            return new WP_REST_Response(array(
                'success' => false,
                'error' => 'License not found'
            ), 404);
        }
        
        $plan = $this->get_plan($license->plan_id);
        
        return new WP_REST_Response(array(
            'success' => true,
            'license' => array(
                'key' => $license->license_key,
                'email' => $license->user_email,
                'domain' => $license->user_domain,
                'status' => $license->status,
                'activation_date' => $license->activation_date,
                'expiration_date' => $license->expiration_date,
                'plan' => $plan ? $plan->name : 'N/A',
                'plan_details' => $plan ? array(
                    'name' => $plan->name,
                    'price' => $plan->price,
                    'billing_period' => $plan->billing_period,
                    'features' => maybe_unserialize($plan->features),
                    'limits' => maybe_unserialize($plan->limits)
                ) : null
            )
        ), 200);
    }
    
    public function track_usage($request) {
        $license_key = sanitize_text_field($request->get_param('license_key'));
        $feature = sanitize_text_field($request->get_param('feature'));
        $count = absint($request->get_param('count') ?: 1);
        $period = sanitize_text_field($request->get_param('period') ?: 'daily');
        
        if (empty($license_key) || empty($feature)) {
            return new WP_REST_Response(array(
                'success' => false,
                'error' => 'License key and feature are required'
            ), 400);
        }
        
        $license = $this->license->get_by_key($license_key);
        
        if (!$license) {
            return new WP_REST_Response(array(
                'success' => false,
                'error' => 'Invalid license key'
            ), 400);
        }
        
        $new_count = $this->usage->track($license->id, $feature, $count);
        
        $plan = $this->get_plan($license->plan_id);
        $limits = $plan ? maybe_unserialize($plan->limits) : array();
        $limit = $limits[$feature] ?? -1;
        
        return new WP_REST_Response(array(
            'success' => true,
            'usage' => array(
                'feature' => $feature,
                'count' => $new_count,
                'limit' => $limit,
                'remaining' => $limit > 0 ? max(0, $limit - $new_count) : -1,
                'period' => $period
            )
        ), 200);
    }
    
    public function check_usage_limit($request) {
        $license_key = sanitize_text_field($request->get_param('license_key'));
        $feature = sanitize_text_field($request->get_param('feature'));
        
        if (empty($license_key) || empty($feature)) {
            return new WP_REST_Response(array(
                'success' => false,
                'error' => 'License key and feature are required'
            ), 400);
        }
        
        $license = $this->license->get_by_key($license_key);
        
        if (!$license) {
            return new WP_REST_Response(array(
                'success' => false,
                'error' => 'Invalid license key'
            ), 400);
        }
        
        $plan = $this->get_plan($license->plan_id);
        $limits = $plan ? maybe_unserialize($plan->limits) : array();
        $limit = $limits[$feature] ?? -1;
        
        $check = $this->usage->check_limit($license->id, $feature, $limit);
        
        return new WP_REST_Response(array(
            'success' => true,
            'limit_check' => $check
        ), 200);
    }
    
    public function get_plans($request) {
        global $wpdb;
        $plans_table = $wpdb->prefix . 'chainpay_plans';
        
        $plans = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$plans_table} WHERE is_active = 1 ORDER BY price ASC"
        ));
        
        $formatted_plans = array();
        
        foreach ($plans as $plan) {
            $formatted_plans[] = array(
                'id' => $plan->id,
                'name' => $plan->name,
                'slug' => $plan->slug,
                'description' => $plan->description,
                'price' => floatval($plan->price),
                'billing_period' => $plan->billing_period,
                'features' => maybe_unserialize($plan->features),
                'limits' => maybe_unserialize($plan->limits)
            );
        }
        
        return new WP_REST_Response(array(
            'success' => true,
            'plans' => $formatted_plans
        ), 200);
    }
    
    public function create_subscription($request) {
        $email = sanitize_email($request->get_param('email'));
        $plan_id = absint($request->get_param('plan_id'));
        $billing_cycle = sanitize_text_field($request->get_param('billing_cycle') ?: 'monthly');
        
        if (empty($email) || !$plan_id) {
            return new WP_REST_Response(array(
                'success' => false,
                'error' => 'Email and plan ID are required'
            ), 400);
        }
        
        $plan = $this->get_plan($plan_id);
        
        if (!$plan) {
            return new WP_REST_Response(array(
                'success' => false,
                'error' => 'Invalid plan'
            ), 400);
        }
        
        $subscription_id = $this->subscription->create(array(
            'user_email' => $email,
            'plan_id' => $plan_id,
            'billing_cycle' => $billing_cycle,
            'amount' => $plan->price,
            'status' => 'pending'
        ));
        
        if (is_wp_error($subscription_id)) {
            return new WP_REST_Response(array(
                'success' => false,
                'error' => $subscription_id->get_error_message()
            ), 400);
        }
        
        $subscription = $this->subscription->get($subscription_id);
        
        $license_key = $this->license->generate_license_key();
        
        $expiration = null;
        if ($billing_cycle === 'yearly') {
            $expiration = date('Y-m-d H:i:s', strtotime('+1 year'));
        } elseif ($billing_cycle === 'monthly') {
            $expiration = date('Y-m-d H:i:s', strtotime('+1 month'));
        }
        
        $license_id = $this->license->create(array(
            'license_key' => $license_key,
            'user_email' => $email,
            'plan_id' => $plan_id,
            'expiration_date' => $expiration,
            'max_domains' => $limits['domains'] ?? 1,
            'max_users' => $limits['users'] ?? 1,
            'metadata' => maybe_serialize(array(
                'subscription_id' => $subscription->subscription_id
            ))
        ));
        
        $this->subscription->update($subscription_id, array(
            'license_id' => $license_id,
            'status' => 'active'
        ));
        
        return new WP_REST_Response(array(
            'success' => true,
            'subscription' => array(
                'id' => $subscription->subscription_id,
                'status' => 'active',
                'plan' => $plan->name,
                'amount' => floatval($plan->price),
                'billing_cycle' => $billing_cycle
            ),
            'license' => array(
                'key' => $license_key,
                'expiration' => $expiration
            )
        ), 200);
    }
    
    public function cancel_subscription($request) {
        $subscription_id = sanitize_text_field($request->get_param('subscription_id'));
        $immediately = (bool) $request->get_param('immediately');
        
        if (empty($subscription_id)) {
            return new WP_REST_Response(array(
                'success' => false,
                'error' => 'Subscription ID is required'
            ), 400);
        }
        
        $subscription = $this->subscription->get_by_sub_id($subscription_id);
        
        if (!$subscription) {
            return new WP_REST_Response(array(
                'success' => false,
                'error' => 'Subscription not found'
            ), 404);
        }
        
        $result = $this->subscription->cancel($subscription->id, $immediately);
        
        if (is_wp_error($result)) {
            return new WP_REST_Response(array(
                'success' => false,
                'error' => $result->get_error_message()
            ), 400);
        }
        
        $message = $immediately 
            ? 'Subscription canceled immediately' 
            : 'Subscription will be canceled at the end of the billing period';
        
        return new WP_REST_Response(array(
            'success' => true,
            'message' => $message
        ), 200);
    }
    
    private function get_plan($plan_id) {
        global $wpdb;
        $plans_table = $wpdb->prefix . 'chainpay_plans';
        return $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$plans_table} WHERE id = %d",
            $plan_id
        ));
    }
}
