<?php

if (!defined('ABSPATH')) {
    exit;
}

class ShopCentral_Marketing_Controller
{
    private $namespace;

    public function __construct($namespace = 'shopcentral/v1')
    {
        $this->namespace = $namespace;
        add_action('rest_api_init', [$this, 'register_routes']);
    }

    public function register_routes()
    {
        register_rest_route($this->namespace, '/api/store-manager/marketing/global-coupon', [
            'methods' => WP_REST_Server::CREATABLE,
            'callback' => [$this, 'create_global_coupon'],
            'permission_callback' => [$this, 'check_permission'],
        ]);
    }

    public function check_permission()
    {
        return current_user_can('manage_options');
    }

    public function create_global_coupon($request)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'shopcentral_stores';
        $stores = $wpdb->get_results("SELECT * FROM $table");
        
        $params = $request->get_json_params() ?: $request->get_body_params();
        
        if (empty($params['code'])) {
            return new WP_Error('missing_code', 'Coupon code is required.', ['status' => 400]);
        }

        $store_api = new ShopCentral_Store_API($this->namespace);
        $results = [];

        foreach ($stores as $store) {
            $coupon_data = [
                'code' => $params['code'],
                'discount_type' => $params['discount_type'] ?? 'fixed_cart',
                'amount' => strval($params['amount'] ?? '0'),
                'description' => $params['description'] ?? '',
                'date_expires' => !empty($params['date_expires']) ? $params['date_expires'] : null,
                'minimum_amount' => !empty($params['minimum_amount']) ? strval($params['minimum_amount']) : '',
                'maximum_amount' => !empty($params['maximum_amount']) ? strval($params['maximum_amount']) : '',
                'usage_limit' => !empty($params['usage_limit']) ? intval($params['usage_limit']) : null,
                'usage_limit_per_user' => !empty($params['usage_limit_per_user']) ? intval($params['usage_limit_per_user']) : null,
                'individual_use' => !empty($params['individual_use']) ? true : false,
                'free_shipping' => !empty($params['free_shipping']) ? true : false,
                'exclude_sale_items' => !empty($params['exclude_sale_items']) ? true : false
            ];

            if ($store_api->is_store_local($store)) {
                // Local creation
                $coupon = new WC_Coupon();
                $coupon->set_code($coupon_data['code']);
                $coupon->set_discount_type($coupon_data['discount_type']);
                $coupon->set_amount($coupon_data['amount']);
                $coupon->set_description($coupon_data['description']);
                if ($coupon_data['date_expires']) $coupon->set_date_expires($coupon_data['date_expires']);
                $coupon->set_minimum_amount($coupon_data['minimum_amount']);
                $coupon->set_maximum_amount($coupon_data['maximum_amount']);
                $coupon->set_usage_limit($coupon_data['usage_limit']);
                $coupon->set_usage_limit_per_user($coupon_data['usage_limit_per_user']);
                $coupon->set_individual_use($coupon_data['individual_use']);
                $coupon->set_free_shipping($coupon_data['free_shipping']);
                $coupon->set_exclude_sale_items($coupon_data['exclude_sale_items']);
                
                try {
                    $coupon->save();
                    $results[] = [
                        'store_name' => $store->name,
                        'status' => 'success',
                        'message' => 'Created successfully locally'
                    ];
                } catch (Exception $e) {
                    $results[] = [
                        'store_name' => $store->name,
                        'status' => 'error',
                        'message' => $e->getMessage()
                    ];
                }
            } else {
                // Remote creation
                $response = $store_api->send_remote_wc_request($store, 'wc/v3/coupons', 'POST', $coupon_data);
                
                if (is_wp_error($response)) {
                    $results[] = [
                        'store_name' => $store->name,
                        'status' => 'error',
                        'message' => $response->get_error_message()
                    ];
                } else if (isset($response['code']) && isset($response['message'])) {
                    $results[] = [
                        'store_name' => $store->name,
                        'status' => 'error',
                        'message' => $response['message']
                    ];
                } else {
                    $results[] = [
                        'store_name' => $store->name,
                        'status' => 'success',
                        'message' => 'Synced to remote store'
                    ];
                }
            }
        }

        return new WP_REST_Response([
            'status' => 'success',
            'results' => $results,
            'message' => 'Global coupon successfully distributed'
        ], 200);
    }
}
