<?php
if ( ! defined( 'ABSPATH' ) ) exit;

/**
 * VMO Cloudflare Manager
 * Handles API interactions with Cloudflare for DNS automation and Email Routing.
 * 
 * Capability:
 * - Detects Zone ID for a domain
 * - Sets up MX, SPF, DKIM records automatically
 * - Configures Cloudflare Email Routing rules (forwarding)
 */

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

class VMO_Cloudflare_Manager {

    private static $api_url = 'https://api.cloudflare.com/client/v4/';
    private $api_token;
    
    public function __construct() {
        // Token should be stored in VMO settings
        $this->api_token = get_option('vmo_cloudflare_api_token', '');
    }

    /**
     * Set the API token (e.g. from user input during setup)
     */
    public function set_token($token) {
        $this->api_token = $token;
    }

    /**
     * Configure email DNS for a specific provider
     */
    public function configure_email_dns($domain, $provider = 'zoho', $config = []) {
        if (empty($this->api_token)) {
            return new WP_Error('no_token', 'Cloudflare API Token is missing. Please add it in VMO Settings > Integrations.');
        }

        $zone_id = $this->get_zone_id($domain);
        if (is_wp_error($zone_id)) return $zone_id;

        $records = [];
        
        // Define records based on provider
        switch ($provider) {
            case 'zoho':
                // MX
                $records[] = ['type' => 'MX', 'name' => '@', 'content' => 'mx.zoho.com', 'priority' => 10];
                $records[] = ['type' => 'MX', 'name' => '@', 'content' => 'mx2.zoho.com', 'priority' => 20];
                $records[] = ['type' => 'MX', 'name' => '@', 'content' => 'mx3.zoho.com', 'priority' => 50];
                // SPF
                $records[] = ['type' => 'TXT', 'name' => '@', 'content' => 'v=spf1 include:zoho.com ~all'];
                break;
                
            case 'google':
                // Google Workspace
                $records[] = ['type' => 'MX', 'name' => '@', 'content' => 'smtp.google.com', 'priority' => 1];
                $records[] = ['type' => 'TXT', 'name' => '@', 'content' => 'v=spf1 include:_spf.google.com ~all'];
                break;
        }

        $results = [];
        foreach ($records as $record) {
            $results[] = $this->add_dns_record($zone_id, $record['type'], $record['name'], $record['content'], $record['priority'] ?? 0);
        }

        return $results;
    }

    /**
     * Enable Cloudflare Email Routing for the zone
     */
    public function enable_email_routing($domain) {
        $zone_id = $this->get_zone_id($domain);
        if (is_wp_error($zone_id)) return $zone_id;

        // 1. Enable Email Routing
        $endpoint = "zones/{$zone_id}/email/routing/enabled";
        $response = $this->call_api('POST', $endpoint, ['enabled' => true]);

        if (is_wp_error($response)) return $response;
        
        return true; 
    }

    /**
     * Create a routing rule (Match -> Destination)
     */
    public function create_routing_rule($domain, $matcher_type, $matcher_value, $destination_email) {
        $zone_id = $this->get_zone_id($domain);
        if (is_wp_error($zone_id)) return $zone_id;

        $endpoint = "zones/{$zone_id}/email/routing/rules";
        $data = [
            'matchers' => [[
                'type' => $matcher_type,
                'field' => 'to',
                'value' => $matcher_value
            ]],
            'actions' => [[
                'type' => 'forward',
                'value' => [$destination_email]
            ]],
            'enabled' => true,
            'name' => "VMO Auto Route: " . ($matcher_value ?: 'Catch-All')
        ];

        return $this->call_api('POST', $endpoint, $data);
    }

    // --- Private Helpers ---

    public function get_zone_id($domain) {
        // Check cache
        $cached = get_transient('vmo_cf_zone_' . md5($domain));
        if ($cached) return $cached;

        $response = $this->call_api('GET', 'zones', ['name' => $domain]);
        
        if (is_wp_error($response)) return $response;
        
        if (empty($response['result'])) {
            return new WP_Error('zone_not_found', "Domain $domain not found in this Cloudflare account.");
        }

        $id = $response['result'][0]['id'];
        set_transient('vmo_cf_zone_' . md5($domain), $id, HOUR_IN_SECONDS);
        return $id;
    }

    private function add_dns_record($zone_id, $type, $name, $content, $priority = 0, $proxied = false) {
        $data = [
            'type' => $type,
            'name' => $name,
            'content' => $content,
            'ttl' => 1,
            'proxied' => $proxied
        ];
        if ($type === 'MX') {
            $data['priority'] = $priority;
        }

        return $this->call_api('POST', "zones/{$zone_id}/dns_records", $data);
    }

    private function call_api($method, $endpoint, $data = []) {
        $url = self::$api_url . $endpoint;
        
        $args = [
            'method' => $method,
            'headers' => [
                'Authorization' => 'Bearer ' . $this->api_token,
                'Content-Type' => 'application/json'
            ],
            'timeout' => 30
        ];

        if ($method === 'GET' && !empty($data)) {
            $url = add_query_arg($data, $url);
        } else if (!empty($data)) {
            $args['body'] = json_encode($data);
        }

        $response = wp_remote_request($url, $args);

        if (is_wp_error($response)) {
            return $response;
        }

        $code = wp_remote_retrieve_response_code($response);
        $body = json_decode(wp_remote_retrieve_body($response), true);

        if ($code >= 400 || (isset($body['success']) && !$body['success'])) {
            $msg = $body['errors'][0]['message'] ?? 'Unknown Cloudflare Error';
            return new WP_Error('cf_api_error', $msg);
        }

        return $body;
    }
}
