<?php
class Simplexml {
    private $data = [];

    public static function parse($source){
        $xmlString = false;
        $context = stream_context_create(['http'=>['timeout'=>10]]);
        if(filter_var($source, FILTER_VALIDATE_URL)){
            $xmlString = @file_get_contents($source, false, $context);
        } elseif(file_exists($source)){
            if(filesize($source) > 5*1024*1024) return [["XML çok büyük (5MB sınırı)"]];
            $xmlString = @file_get_contents($source);
        }

        if(!$xmlString || empty($xmlString)) return false;

        libxml_use_internal_errors(true);
        $xml = @simplexml_load_string($xmlString, "SimpleXMLElement", LIBXML_NOCDATA);
        if(!$xml) return false;

        $rows = [];
        $first = $xml->children()[0] ?? null;
        if(!$first) return false;

        $headers = [];
        foreach($first->children() as $key => $val) $headers[] = $key;
        $rows[] = $headers;

        foreach($xml->children() as $child){
            $cols = [];
            foreach($headers as $key){
                if(in_array($key, ['images','resimler'])){
                    $imgs = [];
                    if(isset($child->$key->img_item)){
                        foreach($child->$key->img_item as $img){
                            $url = trim((string)$img);
                            $url = str_replace(['"', "'"], '', $url); // tırnak temizle
                            $imgs[] = $url;
                            if(count($imgs) >= 50) break;
                        }
                    }
                    $cols[] = implode(',', $imgs);
                } else {
                    $val = trim((string)$child->$key);

                    // CDATA, HTML, yorum ve özel karakter temizliği
                    $val = preg_replace('/<!\[CDATA\[|\]\]>/', '', $val); // CDATA
                    $val = preg_replace('/<!--.*?-->/', '', $val);        // yorumlar
                    $val = html_entity_decode($val, ENT_QUOTES | ENT_HTML5, 'UTF-8'); // HTML entity
                    $val = preg_replace('/\s+/', ' ', $val);              // fazla boşluklar
                    $val = trim($val);

                    $cols[] = $val;
                }
            }
            $rows[] = $cols;
        }

        $obj = new self();
        $obj->data = $rows;
        return $obj;
    }

    public function rows(){ return $this->data; }
    public static function parseError(){ return [["XML okunamadı veya veri bulunamadı"]]; }
}

function savePostToJson($postData, $xmlUrl) {
    // XML URL'den domain adını al
    $parsedUrl = parse_url($xmlUrl);
    if (!isset($parsedUrl['host'])) return false;

    $host = $parsedUrl['host'];
    // www ve uzantıyı kaldır, sadece ana domain
    $parts = explode('.', $host);
    $domain = $parts[0]; 
    if(strtolower($domain) === 'www' && isset($parts[1])) $domain = $parts[1];

    $dir = __DIR__ . '/../../../deppo/excel/';
    if (!is_dir($dir)) mkdir($dir, 0755, true);

    $filepath = $dir . $domain . '.json';

    // Mevcut JSON verisini oku
    $existingData = [];
    if (file_exists($filepath)) {
        $json = file_get_contents($filepath);
        $existingData = json_decode($json, true) ?? [];
    }

    // Aynı xml URL varsa güncelle, yoksa ekle
    $found = false;
    foreach ($existingData as $k => $v) {
        if (isset($v['xml']) && $v['xml'] === $postData['xml']) {
            $existingData[$k] = $postData; // eskiyi tamamen güncelle
            $found = true;
            break;
        }
    }
    if (!$found) $existingData[] = $postData;

    $jsonData = json_encode($existingData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    if (file_put_contents($filepath, $jsonData)) return $filepath;

    return false;
}

function getJsonFromPostUrl($postFileUrl) {
    if (empty($postFileUrl)) return false;

    $host = parse_url($postFileUrl, PHP_URL_HOST);
    if (!$host) return false;

    $parts = explode('.', $host);
    $domain = $parts[0]; 
    if (strtolower($domain) === 'www' && isset($parts[1])) $domain = $parts[1];

    $dir = __DIR__ . '/../../../deppo/excel/';
    $filepath = $dir . $domain . '.json';

    if (!file_exists($filepath)) return false;

    return json_decode(file_get_contents($filepath), true) ?? [];
}
?>