<?php
function push_center_config(){
    $file = __DIR__ . '/../config/push_center.php';
    $cfg = is_file($file) ? include $file : array();
    if(!is_array($cfg)) $cfg = array();
    $cfg['realtime_enabled'] = !empty($cfg['realtime_enabled']);
    $cfg['baidu'] = array_merge(array('enabled'=>false, 'domains'=>array()), is_array($cfg['baidu'] ?? null) ? $cfg['baidu'] : array());
    $cfg['bing'] = array_merge(array('enabled'=>false, 'api_key'=>''), is_array($cfg['bing'] ?? null) ? $cfg['bing'] : array());
    return $cfg;
}

function push_center_log($engine, $domain, $url, $result){
    $dir = __DIR__ . '/../cache/push';
    if(!is_dir($dir)) @mkdir($dir, 0777, true);
    $line = date('Y-m-d H:i:s') . "\t" . $engine . "\t" . $domain . "\t" . $url . "\t" . str_replace(array("\r","\n","\t"), ' ', $result) . "\n";
    return @file_put_contents($dir . '/push_center.log', $line, FILE_APPEND | LOCK_EX) !== false;
}

function push_center_dedupe_key($engine, $domain, $url){
    return md5($engine . '|' . $domain . '|' . $url);
}

function push_center_was_pushed($engine, $domain, $url){
    $file = __DIR__ . '/../cache/push/pushed_urls.php';
    $data = is_file($file) ? include $file : array();
    if(!is_array($data)) $data = array();
    return isset($data[push_center_dedupe_key($engine, $domain, $url)]);
}

function push_center_mark_pushed($engine, $domain, $url){
    $file = __DIR__ . '/../cache/push/pushed_urls.php';
    $dir = dirname($file);
    if(!is_dir($dir)) @mkdir($dir, 0777, true);
    $data = is_file($file) ? include $file : array();
    if(!is_array($data)) $data = array();
    $data[push_center_dedupe_key($engine, $domain, $url)] = time();
    $content = "<?php\nreturn " . var_export($data, true) . ";\n";
    file_put_contents($file, $content, LOCK_EX);
}

function push_center_domain_protocol($domain){
    $cfg = push_center_config();
    if(!empty($cfg['baidu']['domains'][$domain]['protocol'])){
        return $cfg['baidu']['domains'][$domain]['protocol'];
    }
    return 'https';
}

function push_center_make_url($domain, $path){
    if(preg_match('#^https?://#i', $path)) return $path;
    return push_center_domain_protocol($domain) . '://' . $domain . '/' . ltrim($path, '/');
}

function push_baidu_url($domain, $url, $cfg){
    if(empty($cfg['baidu']['enabled'])) {
        return array(false, 'Baidu push is disabled');
    }

    $domains = $cfg['baidu']['domains'] ?? array();
    if(empty($domains[$domain]['token'])) {
        return array(false, 'Baidu token is not configured for current domain');
    }

    $site = $domains[$domain]['site'] ?: $domain;
    $token = $domains[$domain]['token'];
    $api = 'http://data.zz.baidu.com/urls?site=' . urlencode($site) . '&token=' . urlencode($token);

    if(!function_exists('curl_init')) {
        return array(false, 'curl extension is not enabled');
    }

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $api);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $res = curl_exec($ch);
    $err = curl_error($ch);
    $http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if($res !== false && $res !== '') {
        $ok = $http >= 200 && $http < 300;
        $data = json_decode($res, true);
        if(is_array($data)){
            if(isset($data['error']) || intval($data['success'] ?? 0) <= 0){
                $ok = false;
            }
        }
        return array($ok, 'HTTP ' . $http . ': ' . $res);
    }
    return array(false, 'HTTP ' . $http . ': ' . $err);
}

function push_bing_url($domain, $url, $cfg){
    if(empty($cfg['bing']['enabled'])) {
        return array(false, 'Bing push is disabled');
    }

    $key = $cfg['bing']['api_key'] ?? '';
    if(!$key) {
        return array(false, 'Bing API Key is not configured');
    }

    if(!function_exists('curl_init')) {
        return array(false, 'curl extension is not enabled');
    }

    $api = 'https://ssl.bing.com/webmaster/api.svc/json/SubmitUrl?apikey=' . urlencode($key);
    $siteUrl = preg_replace('#/+$#', '', push_center_domain_protocol($domain) . '://' . $domain);
    $payload = json_encode(array(
        'siteUrl' => $siteUrl,
        'url' => $url,
    ), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $api);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8'));
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $res = curl_exec($ch);
    $err = curl_error($ch);
    $http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if($res !== false) {
        $message = $res !== '' ? $res : 'OK';
        return array($http >= 200 && $http < 300, 'HTTP ' . $http . ': ' . $message);
    }
    return array(false, 'HTTP ' . $http . ': ' . $err);
}

function push_center_submit($domain, $url, $engines=array('baidu','bing'), $force=false){
    $cfg = push_center_config();
    $results = array();
    $url = push_center_make_url($domain, $url);

    foreach($engines as $engine){
        if(!in_array($engine, array('baidu','bing'), true)) {
            continue;
        }

        if(!$force && push_center_was_pushed($engine, $domain, $url)){
            $results[$engine] = array(false, 'Already pushed, skipped');
            continue;
        }

        if($engine === 'baidu'){
            $res = push_baidu_url($domain, $url, $cfg);
        } else {
            $res = push_bing_url($domain, $url, $cfg);
        }

        $results[$engine] = $res;
        push_center_log($engine, $domain, $url, $res[1]);

        if($res[0]) {
            push_center_mark_pushed($engine, $domain, $url);
        }
    }

    return $results;
}

function push_center_realtime($domain, $url){
    $cfg = push_center_config();

    if(empty($cfg['realtime_enabled'])) {
        return array();
    }

    $engines = array();
    if(!empty($cfg['baidu']['enabled'])) $engines[] = 'baidu';
    if(!empty($cfg['bing']['enabled'])) $engines[] = 'bing';

    if(!$engines) return array();

    return push_center_submit($domain, $url, $engines, false);
}
