<?php
/**
 * Single Portfolio Post Template - "HIERARCHY & TAXONOMY FINAL FIX"
 * 1. Taxonomy Fix: portfolio_cat ve portfolio-category ikisini de kontrol eder.
 * 2. Sıralama: ATTO panelindeki (Canvas > Paperworks > Pasteller...) sırayı KESİN takip eder.
 * 3. Mantık: Ebeveyn kategoriler (Paperworks gibi) altındakileri ezmez, sırasını bekler.
 */
get_header();

while (have_posts()) : the_post();

// --- 1. DOĞRU KATEGORİ SİSTEMİNİ BUL ---
$tax = 'portfolio_cat'; // Senin sistemin muhtemelen bu
if (!taxonomy_exists($tax)) {
    $tax = 'portfolio-category'; // Değilse bu
}
if (!taxonomy_exists($tax)) {
    $tax = 'category'; // O da değilse standart budur
}

// --- 2. PANEL SIRALAMASINI ÇEK (ATTO) ---
// hide_empty => false yaptık ki hiçbir kategori kaybolmasın
$terms = get_terms(array(
    'taxonomy'   => $tax,
    'orderby'    => 'term_order',
    'order'      => 'ASC',
    'hide_empty' => false 
));

$virtual_chain = array();
$seen_ids = array();

// --- 3. ZİNCİRİ İNŞA ET (SIRA SIRA GEZ) ---
if (!empty($terms) && !is_wp_error($terms)) {
    foreach ($terms as $term) {
        // Bu kategoriye ait resimleri çek
        $cat_posts = get_posts(array(
            'post_type'      => 'portfolio',
            'posts_per_page' => -1,
            'post_status'    => 'publish',
            'tax_query'      => array(
                array(
                    'taxonomy' => $tax,
                    'field'    => 'term_id',
                    'terms'    => $term->term_id,
                    'include_children' => false // ÖNEMLİ: Paperworks, Pasteller'in resimlerini çalmasın!
                ),
            ),
            'orderby'        => 'date',
            'order'          => 'DESC'
        ));

        foreach ($cat_posts as $post_obj) {
            // Eğer resim daha önce eklenmediyse ekle (Mükerrer kaydı önler)
            if (!in_array($post_obj->ID, $seen_ids)) {
                $virtual_chain[] = $post_obj;
                $seen_ids[] = $post_obj->ID;
            }
        }
    }
}

// --- 4. NAVİGASYON HESAPLA ---
$curr_id = get_the_ID();
$curr_idx = -1;
foreach($virtual_chain as $idx => $p) {
    if ($p->ID == $curr_id) { $curr_idx = $idx; break; }
}

// Komşu resimleri bul
$prev_item = (isset($virtual_chain[$curr_idx - 1])) ? $virtual_chain[$curr_idx - 1] : null;
$next_item = (isset($virtual_chain[$curr_idx + 1])) ? $virtual_chain[$curr_idx + 1] : null;

$l_url = $prev_item ? esc_url(add_query_arg('dir', 'prev', get_permalink($prev_item->ID))) : '';
$r_url = $next_item ? esc_url(add_query_arg('dir', 'next', get_permalink($next_item->ID))) : '';

// Animasyon yönü
$entrance = 'fade-up-init';
if (isset($_GET['dir'])) {
    if ($_GET['dir'] === 'next') $entrance = 'enter-right';
    if ($_GET['dir'] === 'prev') $entrance = 'enter-left';
}

$full_image_url = esc_url(wp_get_attachment_image_src(get_post_thumbnail_id(), 'full')[0]);
?>

<section id="p-view" class="portfolio-section <?php echo esc_attr($entrance); ?>">
    
    <?php if ($l_url) : ?>
        <a href="<?php echo $l_url; ?>" class="nav-arrow l-nav"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="15 18 9 12 15 6"></polyline></svg></a>
    <?php endif; ?>
    <?php if ($r_url) : ?>
        <a href="<?php echo $r_url; ?>" class="nav-arrow r-nav"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="9 18 15 12 9 6"></polyline></svg></a>
    <?php endif; ?>

    <div class="container main-cont">
        <div class="art-frame" id="main-frame" onclick="openZoom()">
            <div class="art-zoom-icon">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line><line x1="11" y1="8" x2="11" y2="14"></line><line x1="8" y1="11" x2="14" y2="11"></line></svg>
            </div>
            <div class="art-inner">
                <?php the_post_thumbnail('full', array('class' => 'art-img')); ?>
            </div>
        </div>
        <div class="desc-wrap">
            <div class="clean-box">
                <h3 class="title"><?php esc_html_e('About This Work', 'artist-theme'); ?></h3>
                <div class="text"><?php the_content(); ?></div>
            </div>
        </div>
    </div>
</section>

<div id="art-lb" class="art-lb">
    <span class="lb-close" onclick="closeZoomManual()">&times;</span>
    <div id="lb-viewport" class="lb-viewport">
        <img id="lb-main-img" src="<?php echo $full_image_url; ?>" draggable="false">
    </div>
    <div id="mini-map" class="mini-map">
        <img src="<?php echo $full_image_url; ?>" class="mm-img">
        <div id="mm-rect" class="mm-rect"></div>
    </div>
</div>

<style>
    /* CSS AYARLARI */
    body { background-color: #050505; overflow-x: hidden; touch-action: pan-y; }
    .portfolio-section { padding: 130px 0 80px; min-height: 100vh; display: flex; flex-direction: column; justify-content: flex-start; overflow: hidden; }
    .main-cont { display: flex; flex-direction: column; align-items: center; width: 100%; }
    
    .fade-up-init { animation: fUp 0.8s ease-out forwards; }
    .enter-right { animation: sInR 0.5s cubic-bezier(0.2, 0.8, 0.2, 1) forwards; }
    .enter-left { animation: sInL 0.5s cubic-bezier(0.2, 0.8, 0.2, 1) forwards; }
    .exit-left { animation: sOutL 0.4s ease-in forwards !important; }
    .exit-right { animation: sOutR 0.4s ease-in forwards !important; }
    @keyframes fUp { from { opacity: 0; transform: translateY(30px); } to { opacity: 1; transform: translateY(0); } }
    @keyframes sInR { from { opacity: 0; transform: translateX(100%); } to { opacity: 1; transform: translateX(0); } }
    @keyframes sInL { from { opacity: 0; transform: translateX(-100%); } to { opacity: 1; transform: translateX(0); } }
    @keyframes sOutL { to { opacity: 0; transform: translateX(-100%); } }
    @keyframes sOutR { to { opacity: 0; transform: translateX(100%); } }

    .nav-arrow { position: fixed; top: 50%; transform: translateY(-50%); width: 60px; height: 60px; background: rgba(128, 0, 32, 0.75); color: #fff; display: flex; align-items: center; justify-content: center; border-radius: 50%; z-index: 999; border: 1px solid rgba(255,255,255,0.3); transition: 0.3s; box-shadow: 0 5px 20px rgba(0,0,0,0.6); }
    .l-nav { left: 20px; } .r-nav { right: 20px; }
    .nav-arrow:hover { background: #a30029; transform: translateY(-50%) scale(1.15); box-shadow: 0 0 25px rgba(255, 0, 50, 0.6); }

    .art-frame { position: relative; width: 100%; max-width: 900px; height: 600px; background: #0a0a0a; margin: 0 auto 40px; display: flex; align-items: center; justify-content: center; border: 1px solid rgba(255,255,255,0.08); border-radius: 4px; box-shadow: 0 20px 60px rgba(0,0,0,0.9), 0 0 50px rgba(255, 255, 255, 0.08); cursor: zoom-in; overflow: hidden; }
    .art-img { width: 100%; height: 100%; object-fit: contain; display: block; }
    .art-zoom-icon { position: absolute; top: 20px; right: 20px; width: 44px; height: 44px; background: rgba(0,0,0,0.6); border: 1px solid rgba(255,255,255,0.2); border-radius: 50%; display: flex; align-items: center; justify-content: center; opacity: 1; z-index: 999; }
    
    .title { color: #c5a47e; font-size: 14px; letter-spacing: 2px; text-transform: uppercase; margin: 20px 0; }
    .text p { color: #bbb; font-size: 16px; line-height: 1.6; }

    .art-lb { display: none; position: fixed; z-index: 100000; left: 0; top: 0; width: 100%; height: 100%; background: #000; touch-action: none; }
    .lb-viewport { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; overflow: hidden; }
    #lb-main-img { max-width: 100%; max-height: 100%; object-fit: contain; transform-origin: center center; will-change: transform; }
    .lb-close { position: absolute; top: 20px; right: 30px; color: #fff; font-size: 50px; cursor: pointer; z-index: 100001; }
    .mini-map { position: absolute; bottom: 20px; left: 20px; width: 120px; background: rgba(0,0,0,0.8); border: 1px solid rgba(255,255,255,0.3); z-index: 100002; display: none; pointer-events: none; padding: 2px; }
    .mm-img { width: 100%; display: block; opacity: 0.5; }
    .mm-rect { position: absolute; border: 1px solid #ff0000; background: rgba(255, 0, 0, 0.2); top: 0; left: 0; }

    @media (max-width: 768px) {
        .portfolio-section { padding-top: 130px !important; padding-bottom: 80px; justify-content: flex-start !important; display: block; }
        .nav-arrow { width: 50px; height: 50px; background: rgba(128, 0, 32, 0.9); }
        .l-nav { left: 10px; } .r-nav { right: 10px; }
        .art-frame { height: auto; aspect-ratio: 4/5; max-height: 60vh; width: 95%; margin-top: 10px; }
        .mini-map { width: 100px; bottom: 10px; left: 10px; }
    }
</style>

<script>
    // --- JAVASCRIPT AYARLARI (POINTER EVENTS İLE KUSURSUZ HAREKET) ---
    const lbBox = document.getElementById("art-lb"), zImg = document.getElementById("lb-main-img"), vPort = document.getElementById("lb-viewport");
    const minimap = document.getElementById("mini-map"), mmRect = document.getElementById("mm-rect");
    const view = document.getElementById("p-view");
    const pUrl = "<?php echo $l_url; ?>", nUrl = "<?php echo $r_url; ?>";
    
    let sc = 1, px = 0, py = 0, sx = 0, sy = 0, isDragging = false, tStartX = 0, initialDist = 0, initialScale = 1, isPinching = false;

    function openZoom() { lbBox.style.display = "flex"; sc = 1; px = 0; py = 0; updateTransform(); document.body.style.overflow = "hidden"; history.pushState({zoom: true}, "", "#zoom"); }
    function closeZoomManual() { if(history.state && history.state.zoom) { history.back(); } else { forceCloseZoom(); } }
    function forceCloseZoom() { lbBox.style.display = "none"; document.body.style.overflow = "auto"; sc = 1; px = 0; py = 0; }
    window.addEventListener('popstate', (e) => { if (lbBox.style.display === "flex") { forceCloseZoom(); } });

    function updateTransform() {
        const limitX = Math.max(0, (zImg.offsetWidth * sc - window.innerWidth) / 2), limitY = Math.max(0, (zImg.offsetHeight * sc - window.innerHeight) / 2);
        px = Math.max(-limitX, Math.min(limitX, px)); py = Math.max(-limitY, Math.min(limitY, py));
        zImg.style.transform = `translate3d(${px}px, ${py}px, 0) scale(${sc})`;
        if (sc > 1) {
            minimap.style.display = "block";
            const mapW = minimap.clientWidth, mapH = minimap.clientHeight, imgW = zImg.offsetWidth * sc, imgH = zImg.offsetHeight * sc, viewW = window.innerWidth, viewH = window.innerHeight;
            const rectW = (viewW / imgW) * mapW, rectH = (viewH / imgH) * mapH;
            const posXRatio = (-px + (imgW - viewW) / 2) / (imgW - viewW), posYRatio = (-py + (imgH - viewH) / 2) / (imgH - viewH);
            let rL = posXRatio * (mapW - rectW), rT = posYRatio * (mapH - rectH);
            if (!isFinite(rL)) rL = 0; if (!isFinite(rT)) rT = 0;
            mmRect.style.width = `${rectW}px`; mmRect.style.height = `${rectH}px`; mmRect.style.left = `${rL}px`; mmRect.style.top = `${rT}px`;
        } else { minimap.style.display = "none"; }
    }

    const onStart = (e) => {
        const cx = e.pageX || (e.touches ? e.touches[0].pageX : 0), cy = e.pageY || (e.touches ? e.touches[0].pageY : 0);
        if (e.touches && e.touches.length === 2) { isPinching = true; initialDist = Math.hypot(e.touches[0].pageX - e.touches[1].pageX, e.touches[0].pageY - e.touches[1].pageY); initialScale = sc; zImg.style.transition = "none"; }
        else { tStartX = cx; if(sc > 1) { isDragging = true; sx = cx - px; sy = cy - py; zImg.style.transition = "none"; } }
    };
    const onMove = (e) => {
        if (isPinching && e.touches && e.touches.length === 2) { e.preventDefault(); const dist = Math.hypot(e.touches[0].pageX - e.touches[1].pageX, e.touches[0].pageY - e.touches[1].pageY); sc = Math.min(Math.max(1, initialScale * (dist / initialDist)), 50); updateTransform(); }
        else if (isDragging && sc > 1) { e.preventDefault(); const cx = e.pageX || e.touches[0].pageX, cy = e.pageY || e.touches[0].pageY; px = cx - sx; py = cy - sy; updateTransform(); }
    };
    const onEnd = (e) => {
        if (isPinching) { isPinching = false; } else if (isDragging) { isDragging = false; }
        zImg.style.transition = "transform 0.2s ease-out";
        if (sc === 1 && lbBox.style.display !== "flex") {
            const cx = e.changedTouches ? e.changedTouches[0].pageX : e.pageX;
            const diff = tStartX - cx;
            if (Math.abs(diff) > 80) { if (diff > 0 && nUrl) { view.classList.add('exit-left'); setTimeout(() => { window.location.href = nUrl; }, 300); } else if (diff < 0 && pUrl) { view.classList.add('exit-right'); setTimeout(() => { window.location.href = pUrl; }, 300); } }
        }
    };

    vPort.addEventListener('mousedown', onStart); window.addEventListener('mousemove', onMove); window.addEventListener('mouseup', onEnd);
    vPort.addEventListener('touchstart', onStart, {passive: false}); vPort.addEventListener('touchmove', onMove, {passive: false}); vPort.addEventListener('touchend', onEnd);
    vPort.addEventListener('click', () => { if(!isDragging && !isPinching) { sc = sc === 1 ? 2.5 : 1; updateTransform(); } });
    lbBox.addEventListener('wheel', (e) => { e.preventDefault(); sc = Math.min(Math.max(1, sc + (e.deltaY * -0.0015)), 50); updateTransform(); }, {passive: false});
    const mainF = document.getElementById("main-frame");
    if(mainF) { mainF.addEventListener('touchstart', (e)=>{ tStartX = e.touches[0].pageX; }, {passive: true}); mainF.addEventListener('touchend', onEnd); }
</script>

<?php endwhile; get_footer(); ?>
/* --- Portfolyo Görseli Kırpma Ayarı Başlangıcı --- */

/* Not: Bu kodlar genel WordPress yapılarına göre yazılmıştır.
   Eğer temanızda çalışmazsa, doğru sınıf (class) adlarını bulmamız gerekebilir. */

/* 1. Resmin içinde bulunduğu "çerçeve" kutusunu ayarlıyoruz */
.single-portfolio .post-thumbnail, 
.project-media-wrapper,
.portfolio-single-image { 
    /* Çerçevenin yüksekliğini sabitleyin.
       Bu değeri 400px, 600px gibi istediğiniz görünümü elde edene kadar değiştirebilirsiniz. */
    height: 550px; 

    width: 100%;
    overflow: hidden; /* Kutudan taşan kısımları gizle */
    position: relative;
    display: block;
    
    /* Eğer görselin etrafında koyu çerçeve yoksa ve eklemek isterseniz aşağıdaki satırı aktif edin: */
    /* border: 10px solid #1a1a1a; */
    /* box-shadow: 0 0 20px rgba(0,0,0,0.5); */ /* Hafif gölge efekti için */
}

/* 2. Kutunun içindeki resmin nasıl davranacağını ayarlıyoruz */
.single-portfolio .post-thumbnail img,
.project-media-wrapper img,
.portfolio-single-image img {
    width: 100%;
    height: 100% !important; /* Resmi kutunun yüksekliğine uymaya zorla */
    
    /* KİLİT NOKTA BURASI: 'cover' değeri, resmin en boy oranını bozmadan
       kutuyu tamamen doldurmasını sağlar. Taşan kısımlar kırpılır. */
    object-fit: cover; 
    
    /* Resmin hangi kısmının odaklanacağını belirler. Genelde 'center center' iyidir.
       Eğer resimlerin üst kısmı görünsün isterseniz 'top center' yapabilirsiniz. */
    object-position: center center; 
    
    margin: 0;
    padding: 0;
}

/* --- Portfolyo Görseli Kırpma Ayarı Sonu --- */