<?php
ini_set('memory_limit', '512M'); // Increase memory limit
ini_set('max_execution_time', '600'); // Increase execution time

// Maximum number of files to process
$maxFilesToProcess = 20; // Set your desired limit here

// Path to store the current file number
$counterFile = __DIR__ . '/current_file_number.txt';

// Starting file number
$defaultFileNumber = 1;

// Read current file number
if (file_exists($counterFile)) {
    $currentFileNumber = (int) file_get_contents($counterFile);
} else {
    $currentFileNumber = $defaultFileNumber;
}

// Check if the current file number exceeds the maximum allowed limit
if ($currentFileNumber > $maxFilesToProcess) {
    die("Processing limit of $maxFilesToProcess files reached. Stopping script.");
}

// Construct the URL for the current file number
$xmlUrl = "https://jnpcostadelsol.com/crm/XML/divided_files/properties_part_" . $currentFileNumber . ".xml";

// Fetch the XML file contents from the URL
$fileContents = file_get_contents($xmlUrl);
if ($fileContents === false) {
    die("Error: Failed to fetch the XML file from the URL $xmlUrl.");
}

// Attempt to load the XML from the fetched contents
$xml = simplexml_load_string($fileContents);
if ($xml === false) {
    die("Error: Failed to load XML file. Please check the file format.");
}

// OpenAI API setup
$openaiApiKey = 'sk-proj-hCDWyE6TGKWFSsYxVHYlT3BlbkFJDJTn6mcddWxUEum4XMIg'; // Replace with your actual OpenAI API key

// Function to call OpenAI API using curl
function rewriteContent($content, $apiKey, $type, $language = 'en') {
    $apiUrl = 'https://api.openai.com/v1/chat/completions';
    $model = 'gpt-4o-mini';

    $data = [
        'model' => $model,
        'messages' => [
            [
                'role' => 'system',
                'content' => "You are a helpful assistant that translates and rewrites real estate property $type in $language."
            ],
            [
                'role' => 'user',
                'content' => "Completely rewrite the following real estate property description, ensuring a significant difference in sentence structure, vocabulary, and style $type:\n\n$content"
            ],
        ],
        'max_tokens' => 550,
        'temperature' => 0.85,
    ];

    $ch = curl_init($apiUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $apiKey,
    ]);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        echo "cURL error: " . curl_error($ch);
        return false;
    }
    curl_close($ch);

    $response = json_decode($result, true);
    return $response['choices'][0]['message']['content'] ?? $content;
}

// Function to translate content into Spanish using OpenAI API
function translateContent($content, $apiKey) {
    return rewriteContent($content, $apiKey, "description", "Spanish");
}

// Directory for saving output XML files
$outputDir = 'translated_xml';
if (!is_dir($outputDir)) {
    mkdir($outputDir, 0777, true);
}

// Set output file path based on current file number
$outputFilePath = $outputDir . "/properties_part_" . $currentFileNumber . ".xml";

// Iterate through each property in the XML file
foreach ($xml->property as $property) {
    // Process <ref> tag
    if (isset($property->ref)) {
        $originalRef = (string)$property->ref;
        if (preg_match('/JNP(\d+)/', $originalRef, $matches)) {
            $newRefValue = 'JNP' . ($matches[1] * 2);
            $property->ref = $newRefValue;
        }
    }

    // Swap image URLs
    if (isset($property->images->image[0]->url) && isset($property->images->image[1]->url) && isset($property->images->image[2]->url) && isset($property->images->image[3]->url)) {
        // Store original URLs in a temporary array
        $tempUrls = [
            (string)$property->images->image[0]->url,
            (string)$property->images->image[1]->url,
            (string)$property->images->image[2]->url,
            (string)$property->images->image[3]->url
        ];
        
        // Reassign URLs using the original values
        $property->images->image[0]->url = $tempUrls[2];
        $property->images->image[1]->url = $tempUrls[3];
        $property->images->image[2]->url = $tempUrls[0];
        $property->images->image[3]->url = $tempUrls[1];
    }

    // Rewrite <desc><en> using OpenAI API and then translate to Spanish
   if (isset($property->desc->en)) {
    $rewrittenDescriptionEn = rewriteContent((string)$property->desc->en, $openaiApiKey, "description", "English");

    if ($rewrittenDescriptionEn !== false) {
        $finalDescriptionEn = trim($rewrittenDescriptionEn) . " ";
        $property->desc->en = $finalDescriptionEn;

        $translatedDescriptionEs = translateContent($finalDescriptionEn, $openaiApiKey);
        if ($translatedDescriptionEs !== false) {
            $finalDescriptionEs = trim($translatedDescriptionEs);
            $property->desc->addChild('es', $finalDescriptionEs);
        }
    }
}

    // Rewrite <title><en> using OpenAI API
    if (isset($property->title->en)) {
        $rewrittenTitle = rewriteContent((string)$property->title->en, $openaiApiKey, "title", "English");
        if ($rewrittenTitle !== false) {
            $property->title->en = trim($rewrittenTitle);
        }
    }
}

// Save the modified XML back to a new file
if ($xml->asXML($outputFilePath) === false) {
    die("Error: Failed to save the XML file to $outputFilePath.");
}

echo "XML file has been successfully updated and saved as $outputFilePath.";

// Increment the file number for the next run
$currentFileNumber++;
file_put_contents($counterFile, $currentFileNumber);
?>
