<?php

if (!defined('ABSPATH')) { exit; }

global $wpdb;
$images_table   = $wpdb->prefix . 'yatoon_service_images';
$services_table = $wpdb->prefix . 'yatoon_services';

$service_id    = intval($atts['service_id'] ?? 0);
$category      = sanitize_text_field($atts['category'] ?? '');
$limit         = max(1, min(200, intval($atts['limit'] ?? 50)));
$mode          = in_array($atts['mode'] ?? 'grid', array('grid','slider'), true) ? ( $atts['mode'] ?? 'grid' ) : 'grid';
$cols          = max(2, min(8, intval($atts['cols'] ?? 5)));
$gap           = max(2, min(24, intval($atts['gap'] ?? 6)));
$ratio         = sanitize_text_field($atts['ratio'] ?? '1/1'); // aspect ratio e.g. 1/1, 4/3, 3/4
$mobile_height = sanitize_text_field($atts['mobile_height'] ?? ''); // e.g. 480px, overrides ratio on mobile
$autoplay      = ( $atts['autoplay'] ?? '1' ) === '1';
$interval      = max(2000, intval($atts['interval'] ?? 3500));
$show_captions = ( $atts['captions'] ?? '0' ) === '1';
$show_dots     = ( $atts['dots'] ?? '1' ) === '1';
$show_arrows   = ( $atts['arrows'] ?? '1' ) === '1';
$height        = sanitize_text_field($atts['height'] ?? '460px');
$lightbox      = ( $atts['lightbox'] ?? '1' ) === '1'; // grid: click to enlarge
$book_label    = sanitize_text_field($atts['book_label'] ?? get_option('yatoon_catalog_book_label', 'Book Now'));
$booking_page  = get_option('yatoon_booking_page_url', '');
$primary_color = get_option('yatoon_primary_color', '#C2185B');

// Build query
if ($service_id) {
    $images = $wpdb->get_results($wpdb->prepare(
        "SELECT i.*, s.name AS service_name, s.id AS service_id_val, s.category
         FROM $images_table i
         JOIN $services_table s ON s.id = i.service_id
         WHERE i.service_id = %d AND s.is_active = 1
         ORDER BY i.sort_order ASC LIMIT %d",
        $service_id, $limit
    ));
} elseif ($category) {
    $images = $wpdb->get_results($wpdb->prepare(
        "SELECT i.*, s.name AS service_name, s.id AS service_id_val, s.category
         FROM $images_table i
         JOIN $services_table s ON s.id = i.service_id
         WHERE s.category = %s AND s.is_active = 1
         ORDER BY s.sort_order ASC, i.sort_order ASC LIMIT %d",
        $category, $limit
    ));
} else {
    $images = $wpdb->get_results($wpdb->prepare(
        "SELECT i.*, s.name AS service_name, s.id AS service_id_val, s.category
         FROM $images_table i
         JOIN $services_table s ON s.id = i.service_id
         WHERE s.is_active = 1
         ORDER BY s.is_featured DESC, s.sort_order ASC, i.sort_order ASC LIMIT %d",
        $limit
    ));
}

// Fallback: service cover images if no gallery images uploaded
if (empty($images)) {
    $where_extra = '';
    if ($service_id) {  $where_extra = $wpdb->prepare(' AND id = %d', $service_id);
    } elseif ($category) { $where_extra = $wpdb->prepare(' AND category = %s', $category);
    }
    $rows = $wpdb->get_results("SELECT id AS service_id_val, name AS service_name, category, image_url FROM $services_table WHERE is_active = 1 AND image_url != '' $where_extra ORDER BY is_featured DESC, sort_order ASC LIMIT $limit");
    $images = array_map(function ( $s ) {
        return (object) array('image_url'=>$s->image_url,'service_name'=>$s->service_name,'category'=>$s->category,'caption'=>'','service_id_val'=>$s->service_id_val);
    }, (array) $rows);
}

if (empty($images)) { return '';
}

$uid = 'yg' . uniqid();
?>

<?php if ($mode === 'grid'): ?>
<!-- -- GRID MODE ------------------------------------------------------- -->
<div class="yatoon-gallery-grid" id="<?php echo esc_attr($uid); ?>" style="--primary:<?php echo esc_attr($primary_color); ?>;--cols:<?php echo esc_attr($cols); ?>;--gap:<?php echo esc_attr($gap); ?>px;--ratio:<?php echo esc_attr($ratio); ?>">
    <div class="ygg-grid">
        <?php foreach ($images as $i => $img): ?>
        <div class="ygg-item" data-index="<?php echo esc_attr($i); ?>" data-src="<?php echo esc_url($img->image_url); ?>" data-caption="<?php echo esc_attr($img->service_name ?? ''); ?>">
            <img src="<?php echo esc_url($img->image_url); ?>" alt="<?php echo esc_attr($img->service_name ?? ''); ?>" width="600" height="600" decoding="async" loading="lazy">
            <div class="ygg-overlay">
                <?php if ($img->service_name): ?>
                <span class="ygg-service"><?php echo esc_html($img->service_name); ?></span>
                <?php endif; ?>
                <?php if ($booking_page): ?>
                <a href="<?php echo esc_url(add_query_arg('service_id', intval($img->service_id_val ?? 0), $booking_page)); ?>" class="ygg-book"><?php echo esc_html($book_label); ?></a>
                <?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

    <!-- Dots navigation -->
    <div class="ygg-dots-nav" id="<?php echo esc_attr($uid); ?>-dots">
        <?php foreach ($images as $di => $dimg): ?>
        <button type="button" class="ygg-dot-nav<?php echo $di === 0 ? ' active' : ''; ?>" data-dot="<?php echo esc_attr($di); ?>" aria-label="<?php /* translators: %d: Image position in the gallery. */ echo esc_attr( sprintf( __( 'Show image %d', 'yatoon-booking-system' ), $di + 1 ) ); ?>"></button>
        <?php endforeach; ?>
    </div>

    <?php if ($lightbox): ?>
    <!-- Lightbox -->
    <div class="ygg-lightbox" id="<?php echo esc_attr($uid); ?>-lb" style="display:none;">
        <div class="ygg-lb-backdrop"></div>
        <div class="ygg-lb-content">
            <button type="button" class="ygg-lb-close" aria-label="<?php esc_attr_e( 'Close gallery', 'yatoon-booking-system' ); ?>"><?php esc_html_e( '&times;', 'yatoon-booking-system' ); ?></button>
            <button type="button" class="ygg-lb-prev" aria-label="<?php esc_attr_e( 'Previous image', 'yatoon-booking-system' ); ?>">&#8249;</button>
            <button type="button" class="ygg-lb-next" aria-label="<?php esc_attr_e( 'Next image', 'yatoon-booking-system' ); ?>">&#8250;</button>
            <img class="ygg-lb-img" src="" alt="">
            <div class="ygg-lb-caption"></div>
        </div>
    </div>
    <?php endif; ?>
</div>

<style>
.yatoon-gallery-grid{--primary:<?php echo esc_attr($primary_color); ?>;}

/* -- Carousel: horizontal scroll, shows --cols items at a time -- */
.ygg-grid{
    display:flex;flex-direction:row;flex-wrap:nowrap;
    overflow-x:auto;-webkit-overflow-scrolling:touch;
    scroll-snap-type:x mandatory;
    gap:var(--gap,6px);padding:4px 0 12px;
    scrollbar-width:none;cursor:grab;
    scroll-behavior:smooth;
}
.ygg-grid::-webkit-scrollbar{display:none;}
.ygg-grid:active{cursor:grabbing;}
.ygg-item{
    flex:0 0 calc((100% - var(--gap,6px) * (var(--cols,5) - 1)) / var(--cols,5));
    min-width:calc((100% - var(--gap,6px) * (var(--cols,5) - 1)) / var(--cols,5));
    position:relative;overflow:hidden;border-radius:8px;cursor:pointer;background:#f3f4f6;
    scroll-snap-align:start;
}
.ygg-item::before{content:'';display:block;padding-top:calc(100% / (<?php echo esc_html( str_replace('/', ' / ', preg_replace('/[^0-9\/.]/', '', (string) $ratio) ) ); ?> ));}
.ygg-item img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover;transition:transform .4s ease;}
.ygg-item:hover img{transform:scale(1.04);}
.ygg-overlay{position:absolute;inset:0;background:linear-gradient(transparent 40%,rgba(0,0,0,.65));opacity:0;transition:opacity .25s;display:flex;flex-direction:column;align-items:flex-start;justify-content:flex-end;padding:10px 12px;gap:6px;}
.ygg-item:hover .ygg-overlay{opacity:1;}
.ygg-service{font-size:12px;font-weight:700;color:#fff;text-shadow:0 1px 3px rgba(0,0,0,.5);line-height:1.3;}
.ygg-book{font-size:11px;font-weight:700;padding:4px 12px;background:var(--primary);color:#fff;border-radius:6px;text-decoration:none;transition:opacity .15s;}
.ygg-book:hover{opacity:.88;color:#fff;}

/* Lightbox */
.ygg-lightbox{position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;}
.ygg-lb-backdrop{position:absolute;inset:0;background:rgba(0,0,0,.88);backdrop-filter:blur(6px);}
.ygg-lb-content{position:relative;z-index:1;max-width:92vw;max-height:90vh;display:flex;flex-direction:column;align-items:center;}
.ygg-lb-img{max-width:100%;max-height:80vh;border-radius:10px;object-fit:contain;}
.ygg-lb-caption{margin-top:10px;font-size:14px;font-weight:600;color:#fff;text-align:center;}
.ygg-lb-close{position:fixed;top:16px;right:16px;width:40px;height:40px;border-radius:50%;background:rgba(255,255,255,.15);border:none;color:#fff;font-size:22px;cursor:pointer;display:flex;align-items:center;justify-content:center;backdrop-filter:blur(4px);}
.ygg-lb-prev,.ygg-lb-next{position:fixed;top:50%;transform:translateY(-50%);width:48px;height:48px;border-radius:50%;background:rgba(255,255,255,.15);border:none;color:#fff;font-size:28px;cursor:pointer;display:flex;align-items:center;justify-content:center;backdrop-filter:blur(4px);}
.ygg-lb-prev{left:12px;} .ygg-lb-next{right:12px;}
.ygg-lb-prev:hover,.ygg-lb-next:hover,.ygg-lb-close:hover{background:rgba(255,255,255,.3);}

/* Tablet: show 3 items */
@media(max-width:900px){
    .ygg-item{
        flex:0 0 calc((100% - var(--gap,6px) * 2) / 3);
        min-width:calc((100% - var(--gap,6px) * 2) / 3);
    }
}
/* Dots nav */
.ygg-dots-nav{
    display:flex;justify-content:center;gap:6px;
    margin-top:10px;flex-wrap:wrap;padding:0 8px;
}
.ygg-dot-nav{
    width:8px;height:8px;border-radius:50%;
    background:#d1d5db;border:none;cursor:pointer;padding:0;
    transition:background .2s,transform .2s,width .2s;
    flex-shrink:0;
}
.ygg-dot-nav.active{
    background:var(--primary);
    transform:scale(1.25);
    width:20px;border-radius:4px;
}
.ygg-dot-nav:hover{background:#9ca3af;}

/* Mobile: exactly 1 item full width */
@media(max-width:640px){
    .ygg-item{flex:0 0 100%;min-width:100%;}
    .ygg-item::before{padding-top:<?php echo $mobile_height ? '0' : '100%'; ?>;}
    <?php if ($mobile_height): ?>.ygg-item{height:<?php echo esc_attr($mobile_height); ?>;}.ygg-item img{position:absolute;}<?php endif; ?>
    .ygg-overlay{opacity:1;background:linear-gradient(transparent 55%,rgba(0,0,0,.55));}
    .ygg-book{display:none;}
    .ygg-dots-nav{margin-top:8px;}
    .ygg-dot-nav{width:6px;height:6px;}
    .ygg-dot-nav.active{width:16px;}
}
</style>

<script>
(function(){
document.addEventListener('DOMContentLoaded',function(){
    const wrap=document.getElementById('<?php echo esc_js($uid); ?>');
    if(!wrap)return;
    const grid=wrap.querySelector('.ygg-grid');
    const origItems=Array.from(wrap.querySelectorAll('.ygg-item[data-index]'));
    if(!grid||origItems.length<2)return;

    // -- Clone for infinite loop ----------------------------------------------
    const origCount=origItems.length;
    origItems.forEach(function(el){
        const clone=el.cloneNode(true);
        clone.removeAttribute('data-index');
        grid.appendChild(clone);
    });

    let autoTimer=null, curIdx=0, userInteracting=false;

    function getItemW(){
        const el=grid.querySelector('.ygg-item');
        if(!el)return 0;
        const gap=parseFloat(getComputedStyle(grid).columnGap)||parseFloat(getComputedStyle(grid).gap)||6;
        return el.offsetWidth+gap;
    }

    const dotsWrap=document.getElementById('<?php echo esc_js($uid); ?>-dots');
    const dotBtns=dotsWrap?Array.from(dotsWrap.querySelectorAll('.ygg-dot-nav')):[];

    function updateDots(idx){
        const active=((idx%origCount)+origCount)%origCount;
        dotBtns.forEach(function(d,i){d.classList.toggle('active',i===active);});
    }

    // Dot click
    dotBtns.forEach(function(d,i){
        d.addEventListener('click',function(){
            userInteracting=false;
            stopAuto();
            curIdx=i;
            const w=getItemW();
            if(w) grid.scrollTo({left:curIdx*w,behavior:'smooth'});
            updateDots(curIdx);
            startAuto();
        });
    });

    function advance(){
        curIdx++;
        const w=getItemW();
        if(!w)return;
        grid.scrollTo({left:curIdx*w,behavior:'smooth'});
        updateDots(curIdx);
        setTimeout(function(){
            if(curIdx>=origCount){
                curIdx=0;
                grid.scrollTo({left:0,behavior:'instant'});
                updateDots(0);
            }
        },600);
    }

    function startAuto(){
        clearInterval(autoTimer);
        autoTimer=setInterval(function(){if(!userInteracting)advance();},<?php echo intval($interval); ?>);
    }
    function stopAuto(){clearInterval(autoTimer);}

    // Touch
    grid.addEventListener('touchstart',function(){userInteracting=true;stopAuto();},{passive:true});
    grid.addEventListener('touchend',function(){
        userInteracting=false;
        setTimeout(function(){
            const w=getItemW();
            if(w){curIdx=Math.round(grid.scrollLeft/w)%origCount;}
            updateDots(curIdx);
            startAuto();
        },500);
    },{passive:true});

    // Mouse drag
    let isDown=false,startX=0,startScroll=0;
    grid.addEventListener('mousedown',function(e){isDown=true;userInteracting=true;stopAuto();startX=e.pageX;startScroll=grid.scrollLeft;grid.style.cursor='grabbing';});
    grid.addEventListener('mousemove',function(e){if(!isDown)return;grid.scrollLeft=startScroll-(e.pageX-startX);});
    ['mouseup','mouseleave'].forEach(function(ev){
        grid.addEventListener(ev,function(){
            if(!isDown)return;
            isDown=false;grid.style.cursor='';
            setTimeout(function(){userInteracting=false;const w=getItemW();if(w)curIdx=Math.round(grid.scrollLeft/w);startAuto();},300);
        });
    });

    window.addEventListener('resize',function(){stopAuto();setTimeout(startAuto,200);});
    startAuto();

    // -- Lightbox -------------------------------------------------------------
    <?php if ($lightbox): ?>
    const lb=document.getElementById('<?php echo esc_js($uid); ?>-lb');
    if(lb){
        const lbImg=lb.querySelector('.ygg-lb-img');
        const lbCap=lb.querySelector('.ygg-lb-caption');
        let cur=0;
        function openLb(i){
            cur=((i%origCount)+origCount)%origCount;
            lbImg.src=origItems[cur].dataset.src;
            lbCap.textContent=origItems[cur].dataset.caption||'';
            lb.style.display='flex';
            document.body.style.overflow='hidden';
        }
        function closeLb(){lb.style.display='none';document.body.style.overflow='';}
        wrap.querySelectorAll('.ygg-item[data-index]').forEach(function(el,i){
            el.addEventListener('click',function(){openLb(i);});
        });
        lb.querySelector('.ygg-lb-close').addEventListener('click',closeLb);
        lb.querySelector('.ygg-lb-backdrop').addEventListener('click',closeLb);
        lb.querySelector('.ygg-lb-prev').addEventListener('click',function(){openLb(cur-1);});
        lb.querySelector('.ygg-lb-next').addEventListener('click',function(){openLb(cur+1);});
        document.addEventListener('keydown',function(e){
            if(lb.style.display==='none')return;
            if(e.key==='Escape')closeLb();
            if(e.key==='ArrowLeft')openLb(cur-1);
            if(e.key==='ArrowRight')openLb(cur+1);
        });
        let tx=0;
        lb.addEventListener('touchstart',function(e){tx=e.touches[0].clientX;},{passive:true});
        lb.addEventListener('touchend',function(e){const d=e.changedTouches[0].clientX-tx;if(Math.abs(d)>40)d<0?openLb(cur+1):openLb(cur-1);},{passive:true});
    }
    <?php endif; ?>
});
})();
</script>

<?php else: ?>
<!-- -- SLIDER MODE ----------------------------------------------------- -->
<div class="yatoon-gallery" id="<?php echo esc_attr($uid); ?>" style="--primary:<?php echo esc_attr($primary_color); ?>">
    <div class="yg-track-wrap" style="height:<?php echo esc_attr($height); ?>">
        <div class="yg-track">
            <?php foreach ($images as $img): ?>
            <div class="yg-slide">
                <img src="<?php echo esc_url($img->image_url); ?>" alt="<?php echo esc_attr($img->service_name ?? ''); ?>" width="600" height="600" decoding="async" loading="lazy">
                <?php if ($show_captions || !empty($img->service_name)): ?>
                <div class="yg-caption">
                    <?php if (!empty($img->service_name)): ?>
                    <span class="yg-caption-service"><?php echo esc_html($img->service_name); ?></span>
                    <?php endif; ?>
                    <?php if ($show_captions && !empty($img->caption)): ?>
                    <span class="yg-caption-text"><?php echo esc_html($img->caption); ?></span>
                    <?php endif; ?>
                    <?php if ($booking_page): ?>
                    <a href="<?php echo esc_url(add_query_arg('service_id', intval($img->service_id_val ?? 0), $booking_page)); ?>" class="yg-book-btn"><?php echo esc_html($book_label); ?></a>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>
        <?php if ($show_arrows && count($images) > 1): ?>
        <button type="button" class="yg-arrow yg-prev" aria-label="<?php esc_attr_e( 'Previous image', 'yatoon-booking-system' ); ?>">&#8249;</button>
        <button type="button" class="yg-arrow yg-next" aria-label="<?php esc_attr_e( 'Next image', 'yatoon-booking-system' ); ?>">&#8250;</button>
        <?php endif; ?>
    </div>
    <?php if ($show_dots && count($images) > 1): ?>
    <div class="yg-dots">
        <?php foreach ($images as $i => $img): ?>
        <button type="button" class="yg-dot<?php echo $i === 0 ? ' active' : ''; ?>" data-index="<?php echo esc_attr($i); ?>" aria-label="<?php /* translators: %d: Image position in the gallery. */ echo esc_attr( sprintf( __( 'Show image %d', 'yatoon-booking-system' ), $i + 1 ) ); ?>"></button>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>
</div>
<style>
.yatoon-gallery{--primary:<?php echo esc_attr($primary_color); ?>;}
.yg-track-wrap{position:relative;overflow:hidden;border-radius:14px;background:#111;}
.yg-track{display:flex;transition:transform .5s cubic-bezier(.4,0,.2,1);height:100%;will-change:transform;}
.yg-slide{min-width:100%;position:relative;overflow:hidden;flex-shrink:0;}
.yg-slide img{width:100%;height:100%;object-fit:cover;display:block;transition:transform .6s ease;}
.yg-slide:hover img{transform:scale(1.03);}
.yg-caption{position:absolute;bottom:0;left:0;right:0;background:linear-gradient(transparent,rgba(0,0,0,.75));padding:40px 24px 20px;display:flex;align-items:flex-end;gap:12px;flex-wrap:wrap;}
.yg-caption-service{font-size:16px;font-weight:700;color:#fff;flex:1;text-shadow:0 1px 3px rgba(0,0,0,.5);}
.yg-caption-text{font-size:13px;color:rgba(255,255,255,.8);flex-basis:100%;margin-top:2px;}
.yg-book-btn{padding:8px 20px;background:var(--primary);color:#fff;border-radius:8px;text-decoration:none;font-size:14px;font-weight:700;white-space:nowrap;flex-shrink:0;}
.yg-arrow{position:absolute;top:50%;transform:translateY(-50%);width:44px;height:44px;border-radius:50%;background:rgba(255,255,255,.9);border:none;cursor:pointer;font-size:24px;color:#111;display:flex;align-items:center;justify-content:center;opacity:0;transition:opacity .15s;z-index:5;}
.yg-track-wrap:hover .yg-arrow{opacity:1;}
.yg-prev{left:12px;}.yg-next{right:12px;}
.yg-dots{display:flex;justify-content:center;gap:6px;margin-top:12px;}
.yg-dot{width:8px;height:8px;border-radius:50%;background:#d1d5db;border:none;cursor:pointer;padding:0;transition:background .2s,transform .2s;}
.yg-dot.active{background:var(--primary);transform:scale(1.3);}
</style>
<script>
(function(){
document.addEventListener('DOMContentLoaded',function(){
    const wrap=document.getElementById('<?php echo esc_js($uid); ?>');
    if(!wrap)return;
    const track=wrap.querySelector('.yg-track');
    const slides=wrap.querySelectorAll('.yg-slide');
    const dots=wrap.querySelectorAll('.yg-dot');
    let cur=0,timer=null;
    const total=slides.length;
    if(total<=1)return;
    function goTo(n){cur=(n+total)%total;track.style.transform='translateX(-'+(cur*100)+'%)';dots.forEach(function(d,i){d.classList.toggle('active',i===cur);});}
    function next(){goTo(cur+1);}
    const btnNext=wrap.querySelector('.yg-next');
    const btnPrev=wrap.querySelector('.yg-prev');
    if(btnNext)btnNext.addEventListener('click',function(){clearInterval(timer);next();startAuto();});
    if(btnPrev)btnPrev.addEventListener('click',function(){clearInterval(timer);goTo(cur-1);startAuto();});
    dots.forEach(function(d,i){d.addEventListener('click',function(){clearInterval(timer);goTo(i);startAuto();});});
    let tx=0;
    wrap.addEventListener('touchstart',function(e){tx=e.touches[0].clientX;},{passive:true});
    wrap.addEventListener('touchend',function(e){const d=e.changedTouches[0].clientX-tx;if(Math.abs(d)>40){clearInterval(timer);d<0?next():goTo(cur-1);startAuto();}},{passive:true});
    function startAuto(){<?php if($autoplay): ?>timer=setInterval(next,<?php echo intval($interval); ?>);<?php endif; ?>}
    wrap.addEventListener('mouseenter',function(){clearInterval(timer);});
    wrap.addEventListener('mouseleave',startAuto);
    startAuto();
});
})();
</script>
<?php endif; ?>
