<?php
use WHMCS\Database\Capsule;
if (!defined("WHMCS"))
{
    die("This file cannot be accessed directly");
}
require_once 'Net/DNS2.php';

const NS1 = '185.163.51.142';
const NS2 = '185.178.193.125';
const MX  = 'mail1.thurdata.ch';

function ZimbraEmail_ClientAreaCustomButtonArray ($params)
{
    $mxStatus = ZimbraEmailCheckMX($params);
    switch($mxStatus['action']) {
        case 'set':
            return array(
                'MX Info' => 'infoMX',
                'MX Setzen' => 'setMX',
            );
        case 'change':
            return array(
                'MX Info' => 'infoMX',
                'MX Ändern' => 'setMX',
            );
        default:
            return array(
                'MX Info' => 'infoMX',
            );
    }
}

function ZimbraEmail_infoMX($params)
{
    $mxStatus = ZimbraEmailCheckMX($params);
    return array(
        'breadcrumb' => array(
            'clientarea.php?action=productdetails&id=' . $params['serviceid'] . '&modop=custom&a=infoMX' => 'MX Info',
        ),
        'templatefile' => 'zimbraEmail_help_mx',
        'vars' => array(
            'maildomain' => $params['domain'],
            'action' => $mxStatus['action'],
            'mxtarget' => (isset($mxStatus['mxtarget']) ? $mxStatus['mxtarget'] : 'false'),
        ),
    );
}

function ZimbraEmailCheckMX($params)
{
    unset($zoneID);
    unset($mxStatus);
    $clientDomains = localAPI('GetClientsDomains', array('clientid' => $params['userid']));
    $nameserver = array(
        NS1,
        NS2);
    
    $resolver = new Net_DNS2_Resolver(array('nameservers' => $nameserver));
    try {
            $result = $resolver->query($params['domain'], 'MX');
            
    } catch(Net_DNS2_Exception $e) {
            
            echo "::query() failed: ", $e->getMessage(), "\n";
    }
    $domainMX = $result->answer;
    if(count($domainMX) > 1) {
        for($i=$clientDomains['startnumber'];$i<=$clientDomains['numreturned'];$i++) {
            if($params['domain'] == $clientDomains['domains']['domain'][$i]['domainname']) {
                return array('action' => 'manual', 'mxtarget' => $domainMX);
            }
        }
        return array('action' => 'manualext', 'mxtarget' => $domainMX);
    }
    if(empty($domainMX)){
        for($i=$clientDomains['startnumber'];$i<=$clientDomains['numreturned'];$i++) {
            if($params['domain'] == $clientDomains['domains']['domain'][$i]['domainname']) {
                return array('action' => 'set');
            }
        }
        return array('action' => 'noMX');
    } else {
        $domainMXrecord = array_shift($domainMX);
//        if($domainMXrecord['target'] == $params['serverhostname']) {
        if($domainMXrecord->exchange == MX) {
            return array('action' => 'show', 'mxtarget' => $domainMXrecord->exchange);
        }
        for($i=$clientDomains['startnumber'];$i<=$clientDomains['numreturned'];$i++) {
            if($params['domain'] == $clientDomains['domains']['domain'][$i]['domainname']) {
                return array('action' => 'change', 'mxtarget' => $domainMXrecord->exchange);
            }
        }
        return array('action' => 'wrongMX', 'mxtarget' => $domainMXrecord->exchange);
    }
}


function ZimbraEmail_setMX($params)
{
    $zoneIDcollection = Capsule::table('dns_manager2_zone')
        ->select('id')
        ->where('name', '=', $params['domain'])
        ->get();
    $zoneIDobj = $zoneIDcollection[0];
    $zoneID = $zoneIDobj->{'id'};
    if(!isset($zoneID)) {
        return 'Error: zone ID not found for domain ' . $params['domain'];
    }
    $dnsZone = localAPI('dnsmanager', array( 'dnsaction' => 'getZone', 'zone_id' => $zoneID));
    if($dnsZone['result'] != 'success') {
        return 'Error: cloud not fetch zone for ID ' . $zoneID;
    }
    $zoneRecords = array();
    $mxRecord = array(
        'line' => $params['domain'].'.|MX|0',
        'name' => '@',
        'type' => 'MX',
        'class' => 'IN',
        'data' => array(
            'preference' => '10',
//            'exchange' => $params['serverhostname'],
            'exchange' => MX,
        ),
    );
    array_push($zoneRecords, $mxRecord);
    foreach($dnsZone['data']->records as $record) {
        if($record->type != 'MX') {
            array_push($zoneRecords, $record);
        };
    }
    $result = localAPI('dnsmanager' ,
        array(
            'dnsaction' => 'updateZone',
            'zone_id' => $zoneID,
            'records' => $zoneRecords,
        )
    );
    if($result['result'] != 'success') {
        return 'Error: cloud not update zone for ID ' . $zoneID;
    }
    return 'success';
}

