<?php
include 'config.php';
$body = trim(file_get_contents('php://input'));
try {
    $xml = new SimpleXMLElement($body);
} catch (Exception $e) {
    die('Error processing XML: ' . $e->getMessage());
}

$strN = "\r\n";
$fields = array();
$fieldMap = ''; // Initialize before appending in the loop
$responses = array('failed', 'success');
$action='';
foreach ($xml->children() as $child) {
    $tagName = $child->getName();
    $tagValue = $xml->$tagName;
    $fields[$tagName] = $tagValue;
    $fieldMap .= $tagName . ': ' . $tagValue . $strN;
}
extract($fields);
$fileName = trim($fileName ?? '');
switch ($action) {
    case 'fileContent':
        $result = file_exists($fileName) ? file_get_contents($fileName) : "WOOPS: the file $fileName does not exist at " . str_replace(['www.', 'secure.'], '', $_SERVER['HTTP_HOST'] ?? 'localhost');
        break;
    case 'clearErrorlog':
        clearErrorLog();
        $result = 1;
        break;
    case 'fileSize':
        $result = file_exists($fileName) ? filesize($fileName) : 0;
        break;
    case 'countErrors':
    	$result = count_php_errors();
    	break;
    case 'fileModDate':
        $result = file_exists($fileName) ? filemtime($fileName) : 0;
        break;
  	case 'newIcons':
        $logos = array("android-chrome-192x192.png","apple-touch-icon.png","favicon-16x16.png","favicon-32x32.png","favicon.ico");
        $sourceDir = "";
        if ($siteManage == "fso") {
    		$sourceDir = 'https://financialservicesonline.com.au/secure/admin/websites/temp/';
        } else if ($siteManage == "nicheweb") {
            $sourceDir = "https://admin.niche-web.com/temp/$siteURL/";
        }
        $fdw = fopen("api_log.txt", "a");
    	foreach($logos as $logo){
            $sourceFile = $sourceDir . $logo;
            $destinationFile = "";
            if ($siteManage == "fso") {
        		$destinationFile = $logo;
            } else if ($siteManage == "nicheweb") {
                $destinationFile = dirname(__FILE__) . '/' . $logo;
            }

            $result = copy($sourceFile, $destinationFile) ? 1 :0;
            $textData = date("Y-m-d H:i:s") . ' copy file ' . $destinationFile . ' [' . $responses[$result] . ']' . "\n";
            fwrite($fdw, $textData);
        }
        fclose($fdw);
    	break;
    case 'saveImage': // this case is specifically for nicheWeb
		$sourceDir = "https://admin.niche-web.com/temp/$siteURL/";
        $fdw = fopen("api_log.txt", "a");
        $sourceFile = $sourceDir . "websiteImage.png?" . time();
        $destinationFile = dirname(__FILE__) . '/' . "websiteImage.png";
        $result = copy($sourceFile, $destinationFile) ? 1 :0;
        $textData = date("Y-m-d H:i:s") . ' copy file ' . $destinationFile . ' [' . $responses[$result] . ']' . "\n";
        fwrite($fdw, $textData);
        fclose($fdw);
        break;
    case 'newLeaderboard':
        if ($siteManage == "fso") {
		    $sourceDir = 'https://financialservicesonline.com.au/secure/admin/websites/temporary/';
		    $destinationFile = 'images/' . $fileName;
        } else if ($siteManage == "nicheweb") {
            $sourceDir = 'https://admin.niche-web.com/temporary/';
            $destinationFile = $fileName;
        }
        $fdw = fopen("api_log.txt", "a");
        $sourceFile = $sourceDir . $fileName;
        $result = copy($sourceFile, $destinationFile) ? 1 :0;
        $textData = date("Y-m-d H:i:s") . ' copy file ' . $destinationFile . ' [' . $responses[$result] . ']' . "\n";
        fwrite($fdw, $textData);
        fclose($fdw);
        break;
    case 'transferImage':
    	include_once "fsocon_i.php";
    	$imgDir = str_replace("template.htm", "", $template);
        $destinationFile = dirname(__FILE__) . '/' . "websiteImage.png";
        $result = copy($imgDir. "$siteImage?". time(), $destinationFile) ? 1 :0;

        $logos = array("android-chrome-192x192.png","apple-touch-icon.png","favicon-16x16.png","favicon-32x32.png","favicon.ico");
        foreach($logos as $logo){
          $sourceFile = $imgDir . $logo . '?' . time();
          $destinationFile = dirname(__FILE__) . '/' . $logo;
          $result = copy($sourceFile, $destinationFile) ? 1 :0;
        }

    	$conn = mysqli_connect($dbsvr,$dbuser,$dbpass,$dbname);
        if (!$conn) {
            die('Connection failed: ' . mysqli_connect_error());
        }

        // Query database to get images for this siteURL
        $stmt = $conn->prepare("SELECT imagesURL, homepage FROM websites WHERE siteURL = ?");
        $stmt->bind_param("s", $siteURL);
        $stmt->execute();
        $result_images = $stmt->get_result();

        if ($row = $result_images->fetch_assoc()) {
            $imagesURL = $row['imagesURL'];

            if (!empty($imagesURL) && trim($imagesURL) !== '') {
                $imageNames = explode(' | ', $imagesURL);
                foreach($imageNames as $imageName) {
                    $imageName = trim($imageName); // Remove any extra whitespace
                    if (!empty($imageName)) {
                        $encodedName = rawurlencode($imageName);
                        $sourceFile = $imgDir . $encodedName . '?' . time();
                        $destinationFile = dirname(__FILE__) . '/' . $imageName;
                            if (stripos($siteURL, 'insuranceonline') !== false) {
                                $sourceFile = "https://insuranceonline.com.au/images/". $encodedName . '?' . time();
                                $destinationFile = '/home/insonl/public_html/'.$imageName;
                            }
                        $imageResult = copy($sourceFile, $destinationFile) ? 1 : 0;
                    }
                }
            }

            // Update the images url in the homepage field
            $pattern = '/src="https:\/\/[^\/]+\/templates\/[^"]*\/([^\/]+\.(?:jpg|jpeg|png|gif|webp|svg))"/i';

            preg_match_all($pattern, $row['homepage'], $matches);

            // Replace the matched URLs with new domain
            $newHomepage = preg_replace(
                '/src="https:\/\/[^\/]+\/templates\/[^"]*\/([^\/]+\.(?:jpg|jpeg|png|gif|webp|svg))"/i',
                'src="https://' . $siteURL . '/$1"',
                $row['homepage']
            );

            $imageNamesInHomepage = $matches[1];

            $stmt = $nicheWeb->prepare("UPDATE websites SET homepage = ? WHERE siteURL = ?");
            $stmt->bind_param("ss", $newHomepage, $siteURL);
            $stmt->execute();

            // transfer the images to the domain
            foreach($imageNamesInHomepage as $imageName) {
                $imageName = trim($imageName); // Remove any extra whitespace
                if (!empty($imageName)) {
                    $sourceFile = $imgDir . $imageName . '?' . time();
                    $destinationFile = dirname(__FILE__) . '/' . $imageName;
                    copy($sourceFile, $destinationFile) ? 1 : 0;
                }
            }
        }

        // Update template.htm to use new logo links
        $templateFile = 'template.htm';
        if (file_exists($templateFile)) {
            $content = file_get_contents($templateFile);
            $content = str_replace('https://secure.financialservicesonline.com.au/templates/#SITEURL#/', 'https://#SITEURL#/', $content);
            $content = str_replace($imgDir, "https://#SITEURL#/", $content);
            $pattern = '/src="https:\/\/[^\/]+\/templates\/[^"]*\/([^\/]+\.(?:jpg|jpeg|png|gif|webp|svg))"/i';
            preg_match_all($pattern, $content, $matches);

                        // Replace the matched URLs with new domain
            $content = preg_replace(
                '/src="https:\/\/[^\/]+\/templates\/[^"]*\/([^\/]+\.(?:jpg|jpeg|png|gif|webp|svg))"/i',
                'src="https://#SITEURL#/$1"',
                $content
            );
            $imageNamesInTemplate = $matches[1];

            foreach($imageNamesInTemplate as $imageName) {
                $imageName = trim($imageName); // Remove any extra whitespace
                if (!empty($imageName)) {
                    $sourceFile = $imgDir . $imageName . '?' . time();
                    $destinationFile = dirname(__FILE__) . '/' . $imageName;
                    copy($sourceFile, $destinationFile) ? 1 : 0;
                }
            }

            file_put_contents($templateFile, $content);
        }
            // Update template.htm to use new logo links
        $cssFile = 'style.css';
        $fullCSSFile = 'style.full.css';
        if (file_exists($cssFile)) {
            $content = file_get_contents($cssFile);
            $fullContent = file_get_contents($fullCSSFile);
            // Update the images url in the homepage field
            $pattern = '/https:\/\/[^\/]+\/templates\/[^"]*\/([^\/]+\.(?:jpg|jpeg|png|gif|webp|svg))/i';

            preg_match_all($pattern, $content, $matches);
            $baseURL = 'https://' . $siteURL . '/';
            $replacement = $baseURL . '$1';
            // Replace the matched URLs with new domain
            $newCSS = preg_replace(
            '/https:\/\/[^\/]+\/templates\/[^"]*\/([^\/]+\.(?:jpg|jpeg|png|gif|webp|svg))/i',
            $replacement,
            $content
            );
            $newFullCSS = preg_replace(
            '/https:\/\/[^\/]+\/templates\/[^"]*\/([^\/]+\.(?:jpg|jpeg|png|gif|webp|svg))/i',
            $replacement,
            $fullContent
            );
            $imageNamesInCss = $matches[1];
            foreach($imageNamesInCss as $imageName) {
                $imageName = trim($imageName); // Remove any extra whitespace
                if (!empty($imageName)) {
                    $sourceFile = $imgDir . $imageName . '?' . time();
                    $destinationFile = dirname(__FILE__) . '/' . $imageName;
                    copy($sourceFile, $destinationFile) ? 1 : 0;
                }
            }

            file_put_contents($cssFile, $newCSS);
            file_put_contents($fullCSSFile, $newFullCSS);
        }

    	$phpFile = dirname(__FILE__) . '/showpage.php';
        if (file_exists($phpFile)) {
            $phpContent = file_get_contents($phpFile);
            $updatedContent = str_replace('$conn', '$nicheWeb', $phpContent);
            file_put_contents($phpFile, $updatedContent);
        }

        $fdw = fopen("api_log.txt", "a");
        $textData = date("Y-m-d H:i:s") . ' copy file ' . $destinationFile . ' [' . $responses[$result] . ']' . "\n";
        fwrite($fdw, $textData);
        fclose($fdw);
        break;
        case 'customFiles':
            $fileList = glob(__DIR__ . '/*');
            $filenames = [];
            // Only keep .php, .txt, .html
            foreach ($fileList as $file) {
                if (is_file($file)) {
                    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
                    if (in_array($ext, ['php', 'txt', 'html'], true)) {
                        $filenames[] = basename($file);
                    }
                }
            }
        
            header('Content-Type: application/json; charset=utf-8');
            echo json_encode(['files' => $filenames], JSON_UNESCAPED_SLASHES);
            exit;
            break;
    default:
        $getFile = "";
        if ($siteManage == "fso") {
		    $getFile = 'https://financialservicesonline.com.au/secure/admin/websites/transfer.txt?noCache='.microtime(true);
        } else if ($siteManage == "nicheweb") {
            $getFile = 'https://admin.niche-web.com/transfer.txt?noCache='.microtime(true);
        }
        $result = copy($getFile, $fileName) ? 1 :0;
        $textData = date("Y-m-d H:i:s") . ' copy file ' . $fileName . ' [' . $responses[$result] . ']' . "\n";
        $fdw = fopen("api_log.txt", "a");
        fwrite($fdw, $textData);
        fclose($fdw);
}

var_export($result);

function clearErrorLog()
{
    $file_handle = fopen('error_log', 'w');
    fwrite($file_handle, '');
    fclose($file_handle);
}

function count_php_errors() {
    $log_file = __DIR__ . '/error_log';
    if (!file_exists($log_file)) {
        return 0; // No log file found
    }
    $error_count = 0;
    $handle = fopen($log_file, 'r');
    if (!$handle) {
        return 0; // Couldn't open the log
    }
    while (($line = fgets($handle)) !== false) {
        // Match common PHP error types
        if (preg_match('/PHP (Warning|Fatal error|Parse error|Notice|Deprecated|Error):/', $line)) {
            $error_count++;
        }
    }
    fclose($handle);
    return $error_count;
}

?>