<?php 
    $path="../../"; 
    include("../../map.php");
    
    // PHP Helper Fonksiyonları
    function get_cdn_content($url, $context) {
        $content = @file_get_contents($url, false, stream_context_create($context));
        return $content ? json_decode($content, true) : [];
    }

    // Dosya silme işlemi (Güvenlik eklendi)
    if(isset($_GET["file"]) && $_GET["file"] != ""){
        $fileToDelete = basename($_GET["file"]); // Sadece dosya adını al, ../ engelle
        $targetPath = "../../../deppo/image/" . $fileToDelete;
        if(file_exists($targetPath)){
            unlink($targetPath);
        }
    }
?>
<style>
    /* Genel Kart Stilleri */
    .theme-item {
        position: relative;
        padding: 5px;
        display: block;
        transition: all 0.3s ease;
        text-decoration: none !important;
    }
    .theme-preview {
        width: 100%;
        height: 80px;
        float: left;
        margin-left: 5px;
        margin-bottom: 5px;
        border-radius: 4px;
        object-fit: cover;
        box-shadow: 0 1px 3px rgba(0,0,0,0.2);
        transition: transform 0.2s;
        border: 4px solid #ddd; /* Varsayılan border */
    }
    .theme-item:hover .theme-preview {
        transform: scale(1.02);
        box-shadow: 0 4px 8px rgba(0,0,0,0.3);
    }
    .theme-active {
        border-color: orange !important;
    }
    .theme-label {
        position: absolute;
        bottom: 5px;
        left: 20px;
        width: calc(100% - 25px);
        background: rgba(255, 255, 255, 0.85);
        padding: 2px 5px;
        font-size: 11px;
        color: #333;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        border-radius: 0 0 4px 4px;
        pointer-events: none;
    }
    
    /* Video Play İkonu */
    .item-video:before {
        content: '';
        width: 30px;
        height: 30px;
        position: absolute;
        top: 50%;
        left: 50%;
        z-index: 2;
        background: rgba(0,0,0,0.5) url("data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%20357%20357%22%3E%3Cpolygon%20points%3D%2238.25%2C0%2038.25%2C357%20318.75%2C178.5%20%20%20%22%20fill%3D%22%23FFF%22/%3E%3C/svg%3E") 10px 8px no-repeat;
        background-size: 14px 14px;
        border-radius: 50%;
        transform: translate(-50%,-50%);
        pointer-events: none;
    }

    /* Silme Butonu */
    .delete-theme-btn {
        position: absolute;
        right: 8px;
        top: 8px;
        background: rgba(255,0,0,0.7);
        color: white;
        border-radius: 50%;
        width: 20px;
        height: 20px;
        text-align: center;
        line-height: 20px;
        font-size: 12px;
        cursor: pointer;
        z-index: 10;
    }
    .delete-theme-btn:hover {
        background: red;
    }

    /* Alt Butonlar */
    .control-btn {
        display: block;
        padding: 10px;
        background: #f5f5f5;
        border: 1px solid #ddd;
        text-align: center;
        border-radius: 4px;
        color: #333;
        font-weight: bold;
        text-decoration: none !important;
        transition: background 0.2s;
    }
    .control-btn:hover {
        background: #e9e9e9;
        color: #000;
    }
</style>

<div class="v3-panel-group" id="myGroup" role="tablist" aria-multiselectable="true">
    
    <div class="v3-panel v3-panel-default">
        <div class="v3-panel-heading" role="tab" id="heading-t1">
            <h4 class="v3-panel-title">
                <a role="button" data-toggle="collapse" data-parent="#myGroup" href="#collapse-t1" aria-expanded="true" aria-controls="collapse-t1">
                    Resimler
                </a>
            </h4>
        </div>
        <div id="collapse-t1" class="v3-panel-collapse collapse in show" role="tabpanel" aria-labelledby="heading-t1">
            <div class="v3-panel-body">
                <?php
                    $images = get_cdn_content('https://cdn.'.$cdnurl.'/themes/?folder=images/thumbs', $arrContextOptions);
                    if($images): foreach($images as $image){
                        $isActive = ($module["crm_background"] == $image) ? 'theme-active' : '';
                        $cleanName = str_replace([".jpg", "themes/images/thumbs/"], "", $image);
                ?>
                <a class="v3-col-md-4 v3-col-xs-6 theme-item item-image" href="fonksiyon.php?durum=ujson&crm_background=<?php echo str_replace("thumbs/","",$image)?>" target="logfrm">
                    <img src="https://cdn.crmplus.com.tr/<?php echo $image?>" 
                         data-sourge="https://cdn.<?php echo $cdnurl?>/<?php echo str_replace("thumbs/","",$image)?>" 
                         class="themes theme_images theme-preview <?php echo $isActive; ?>" 
                         loading="lazy">
                    <span class="theme-label"><?php echo $cleanName; ?></span>
                </a>
                <?php } endif; ?>
            </div>
        </div>
    </div>

    <div class="v3-panel v3-panel-default">
        <div class="v3-panel-heading" role="tab" id="heading-t2">
            <h4 class="v3-panel-title">
                <a role="button" data-toggle="collapse" data-parent="#myGroup" href="#collapse-t2" aria-expanded="false" aria-controls="collapse-t2">
                    Svg Arkaplanlar
                </a>
            </h4>
        </div>
        <div id="collapse-t2" class="v3-panel-collapse collapse" role="tabpanel" aria-labelledby="heading-t2">
            <div class="v3-panel-body">
                <?php
                    $svgs = get_cdn_content('https://cdn.'.$cdnurl.'/themes/?folder=svg', $arrContextOptions);
                    $colors = array("CornflowerBlue","CadetBlue","Grey"); 
                    $i = -1;
                    if($svgs): foreach($svgs as $svg){ $i++;
                        $color = isset($colors[$i]) ? $colors[$i] : "Grey";
                        $isActive = ($module["crm_background"] == $svg) ? 'theme-active' : '';
                        $cleanName = str_replace([".svg", "themes/svg/"], "", $svg);
                ?>
                <a class="v3-col-md-4 v3-col-xs-6 theme-item item-svg" href="fonksiyon.php?durum=ujson&crm_background=<?php echo $color?>,<?php echo $svg?>" target="logfrm">
                    <div class="themes theme_svgs theme-preview <?php echo $isActive; ?>" 
                         data-sourge="https://cdn.<?php echo $cdnurl?>/<?php echo $svg?>" 
                         data-color="<?php echo $color?>" 
                         style="background-image:url(https://cdn.<?php echo $cdnurl?>/<?php echo $svg?>); background-size: cover; background-color: <?php echo $color?>;">
                    </div>
                    <span class="theme-label"><?php echo $cleanName; ?></span>
                </a>
                <?php } endif; ?>
            </div>
        </div>
    </div>

    <div class="v3-panel v3-panel-default">
        <div class="v3-panel-heading" role="tab" id="heading-t3">
            <h4 class="v3-panel-title">
                <a role="button" data-toggle="collapse" data-parent="#myGroup" href="#collapse-t3" aria-expanded="false" aria-controls="collapse-t3">
                    Videolar
                </a>
            </h4>
        </div>
        <div id="collapse-t3" class="v3-panel-collapse collapse" role="tabpanel" aria-labelledby="heading-t3">
            <div class="v3-panel-body">
                <?php
                    $videos = get_cdn_content('https://cdn.'.$cdnurl.'/themes/?folder=videos/thumbs', $arrContextOptions);
                    if($videos): foreach($videos as $video){
                        $isActive = ($module["crm_background"] == $video) ? 'theme-active' : '';
                        $videoSrc = str_replace([".jpg", "thumbs/"], [".mp4", ""], $video);
                        $cleanName = str_replace([".jpg", "themes/videos/thumbs/"], "", $video);
                ?>
                <a class="v3-col-md-4 v3-col-xs-6 theme-item item-video" href="fonksiyon.php?durum=ujson&crm_background=<?php echo $videoSrc; ?>" target="logfrm">
                    <img src="https://cdn.crmplus.com.tr/<?php echo $video?>" 
                         data-sourge="https://cdn.<?php echo $cdnurl?>/<?php echo $videoSrc; ?>" 
                         class="themes theme_videos theme-preview <?php echo $isActive; ?>" 
                         loading="lazy">
                    <span class="theme-label"><?php echo $cleanName; ?></span>
                </a>
                <?php } endif; ?>
            </div>
        </div>
    </div>

    <div class="v3-panel v3-panel-default">
        <div class="v3-panel-heading" role="tab" id="heading-t4">
            <h4 class="v3-panel-title">
                <a role="button" data-toggle="collapse" data-parent="#myGroup" href="#collapse-t4" aria-expanded="false" aria-controls="collapse-t4">
                    Renkler
                </a>
            </h4>
        </div>
        <div id="collapse-t4" class="v3-panel-collapse collapse" role="tabpanel" aria-labelledby="heading-t4">
            <div class="v3-panel-body">
                <?php
                    $bg_colors = array("Tomato","Black","CadetBlue","Chocolate","Crimson","DarkCyan","DarkKhaki","DarkOliveGreen","DimGray","FireBrick","GoldenRod","SlateGrey");
                    foreach($bg_colors as $color){
                        $isActive = ($module["crm_background"] == $color) ? 'theme-active' : '';
                ?>
                <a class="v3-col-md-4 v3-col-xs-6 theme-item item-color" href="fonksiyon.php?durum=ujson&crm_background=<?php echo $color?>" target="logfrm">
                    <div class="themes theme_colors theme-preview <?php echo $isActive; ?>" 
                         data-sourge="<?php echo $color?>" 
                         style="background:<?php echo $color?>;">
                    </div>
                    <span class="theme-label"><?php echo $color?></span>
                </a>
                <?php } ?>
            </div>
        </div>
    </div>
</div>

<div class="custom-themes-container">
    <?php
        $mydir = '../../../deppo/image';
        if(is_dir($mydir)){
            $myfiles = array_diff(scandir($mydir), array('.', '..'));
            $custom_i = 0;
            foreach($myfiles as $theme){
                if(substr($theme, 0, 5) == "theme"){
                    $custom_i++;
                    $isActive = ($module["crm_background"] == "deppo/image/".$theme) ? 'theme-active' : '';
                    $cleanName = str_replace([".jpg", "deppo/images/"], "", $theme);
    ?>
    <a class="v3-col-md-4 v3-col-xs-6 theme-item item-image custom-theme-<?php echo $custom_i?>" href="fonksiyon.php?durum=ujson&crm_background=deppo/image/<?php echo $theme?>" target="logfrm">
        <i class="fas fa-times delete-theme-btn" data-id="custom-theme-<?php echo $custom_i?>" data-sourge="<?php echo $theme?>" title="Sil"></i>
        <img src="../../../deppo/image/<?php echo $theme?>" 
             data-sourge="../../../deppo/image/<?php echo $theme?>" 
             class="themes theme_images theme-preview <?php echo $isActive; ?>" 
             loading="lazy">
        <span class="theme-label"><?php echo $cleanName; ?></span>
    </a>
    <?php 
                }
            }
        }
    ?>
</div>

<div style="clear:both; display:block; margin-bottom: 20px;"></div>

<div class="v3-row" style="margin: 0;">
    <div class="v3-col-md-6 v3-col-xs-6" style="padding-right: 5px;">
        <a class="theme_reset control-btn" href="fonksiyon.php?durum=ujson&crm_background=" target="logfrm">
            <i class="fas fa-broom"></i> Reset
        </a>
    </div>
    <div class="v3-col-md-6 v3-col-xs-6" style="padding-left: 5px;" id="dark_mode">
        </div>
</div>

<script>
    // Ortak fonksiyon: Theme Active Class Değiştirme
    function setActiveTheme(element) {
        jQuery('.themes').removeClass('theme-active').css('border-color', 'grey'); // Reset all
        jQuery(element).addClass('theme-active').css('border-color', 'orange');
    }

    // Resim Tıklama
    jQuery('.theme_images').click(function(e){
        setActiveTheme(this);
        var src = jQuery(this).attr("data-sourge");
        jQuery('#background-video').html('');
        jQuery('#jswpanel').css('background', 'url('+src+') center center / cover no-repeat fixed');
    });

    // Video Tıklama
    jQuery('.theme_videos').click(function(e){
        setActiveTheme(this);
        var src = jQuery(this).attr("data-sourge");
        jQuery('#jswpanel').css('background', 'url() center center / cover no-repeat fixed');
        
        // Videoyu yeniden oluşturmak yerine varsa kaynağı güncelle
        var videoHtml = '<video id="background-video" autoplay loop muted playsinline style="position: absolute; right: 0; bottom: 0; min-width: 100%; min-height: 100%;"><source src="'+src+'" type="video/mp4"></video>';
        
        if(jQuery('#background-video').length){
             jQuery('#background-video source').attr('src', src);
             jQuery('#background-video')[0].load();
        } else {
             jQuery('#jswpanel').append(videoHtml);
        }
    });

    // Renk Tıklama
    jQuery('.theme_colors').click(function(e){
        setActiveTheme(this);
        var src = jQuery(this).attr("data-sourge");
        jQuery('#background-video').html(''); // Videoyu temizle
        jQuery('#jswpanel').css('background', src);
    });

    // SVG Tıklama
    jQuery('.theme_svgs').click(function(e){
        setActiveTheme(this);
        var src = jQuery(this).attr("data-sourge");
        var color = jQuery(this).attr("data-color");
        jQuery('#background-video').html('');
        jQuery('#jswpanel').css('background', color);
        jQuery('#jswpanel').css('background-image', 'url('+src+')');
        jQuery('#jswpanel').css('background-size', 'cover');
    });

    // Reset
    jQuery('.theme_reset').click(function(e){
        jQuery('.themes').removeClass('theme-active').css('border-color', 'grey');
        jQuery('#background-video').html('');
        jQuery('#jswpanel').css('background', 'url(https://cdn.<?php echo $cdnurl?>/themes/svg/pattern.svg)');
        jQuery('#jswpanel').css('background-repeat', 'repeat');
        jQuery('#jswpanel').css('background-size', 'auto');
        jQuery('#jswpanel').css('background-color', 'rgb(84, 93, 107)');
    });

    // Silme Butonu
    jQuery('.delete-theme-btn').click(function(e){
        e.preventDefault(); // Linke gitmeyi engelle
        e.stopPropagation(); // Parent click eventini engelle
        if(!confirm('Bu temayı silmek istediğinize emin misiniz?')) return;

        var data_sourge = jQuery(this).attr('data-sourge');
        var data_id = jQuery(this).attr('data-id');
        
        jQuery('.'+data_id).fadeOut(300, function(){ $(this).remove(); });
        // Mevcut sayfaya silme parametresi ile yönlendir (PHP tarafında silinecek)
        // Güvenlik: logfrm değil, bu sayfanın kendisini yeniliyoruz ki silinsin
        window.location.href = '?file='+data_sourge; 
    });

    // Dark Mode Mantığı
    function updateDarkModeBtn() {
        var isDark = jQuery('body').hasClass("dark-mode");
        var html = '';
        if(isDark){
            html = '<a class="control-btn" onclick="darkmode()" href="fonksiyon.php?durum=ujson&dark-mode=" target="logfrm"><i class="fas fa-sun"></i> Light Mode</a>';
        } else {
            html = '<a class="control-btn" onclick="darkmode()" href="fonksiyon.php?durum=ujson&dark-mode=1" target="logfrm"><i class="fas fa-moon"></i> Dark Mode</a>';
        }
        jQuery('#dark_mode').html(html);
    }

    jQuery(document).ready(function(){
        updateDarkModeBtn();
        // Butona tıklandığında butonun hemen değişmesi için bir listener ekliyoruz 
        // (darkmode fonksiyonunun body class'ını değiştirdiğini varsayıyoruz)
        jQuery('#dark_mode').click(function(){
            setTimeout(updateDarkModeBtn, 200); // UI update gecikmesi için ufak timeout
        });
    });
</script>