<?php
if (!defined('ABSPATH')) exit;

class VS_Stores {

    public static function init() {
        add_shortcode('vs_stores', [__CLASS__, 'render_stores_page']);
    }

    public static function render_stores_page() {
        $selected_store_id = absint($_GET['store_id'] ?? 0);
        if ($selected_store_id > 0) {
            $store = self::get_store_data($selected_store_id);
            if ($store) {
                return self::render_store_details_page($store);
            }
        }

        $stores_page = max(1, absint($_GET['stores_page'] ?? 1));
        $stores_per_page = 9;
        $stores_data = self::get_stores_data($stores_page, $stores_per_page);
        $directory_url = self::get_stores_directory_url();
        $stores_view = $stores_data['stores'] ?? [];
        $stores_total = isset($stores_data['total']) ? (int) $stores_data['total'] : count($stores_view);
        $stores_max_pages = max(1, (int) ceil($stores_total / $stores_per_page));
        if ($stores_page > $stores_max_pages) {
            $stores_page = $stores_max_pages;
            $stores_data = self::get_stores_data($stores_page, $stores_per_page);
            $stores_view = $stores_data['stores'] ?? [];
        }

        ob_start();
        ?>
      <div class="vs-stores-page">
<style>
/* ═══════════════════════════════════════════════
   VS STORES PAGE — Professional Styling
   ═══════════════════════════════════════════════ */

@import url('https://fonts.googleapis.com/css2?family=Sora:wght@400;500;600;700&family=DM+Sans:wght@400;500&display=swap');

.vs-stores-page {
    font-family: 'DM Sans', sans-serif;
    padding: 40px 24px 64px;
    background: #f0f4ff;
    min-height: 100vh;
}

/* ── Hero ── */
.vs-stores-hero {
    text-align: center;
    margin-bottom: 48px;
}

.vs-stores-hero h2 {
    font-family: 'Sora', sans-serif;
    font-size: clamp(2rem, 5vw, 3rem);
    font-weight: 700;
    color: #0f172a;
    margin: 0 0 10px;
    letter-spacing: -0.03em;
}

.vs-stores-hero p {
    color: #64748b;
    font-size: 1.05rem;
    margin: 0;
}

/* ── Empty State ── */
.vs-stores-empty {
    text-align: center;
    color: #94a3b8;
    font-size: 1rem;
    padding: 60px 0;
}

/* ── Grid ── */
.vs-stores-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 28px;
    max-width: 1280px;
    margin: 0 auto;
}

/* ── Card Reveal Animation ── */
.vs-store-card-directory {
    opacity: 0;
    transform: translateY(22px);
    animation: vsStoreReveal .55s cubic-bezier(.22,.68,0,1.2) forwards;
    animation-delay: var(--vs-delay, 0ms);
}

@keyframes vsStoreReveal {
    from { opacity: 0; transform: translateY(22px); }
    to   { opacity: 1; transform: translateY(0); }
}

/* ── Card ── */
.vs-store-card-directory article,
article.vs-store-card-directory {
    background: #ffffff;
    border-radius: 20px;
    overflow: hidden;
    position: relative;
    box-shadow:
        0 1px 2px rgba(0,0,0,.04),
        0 4px 16px rgba(15,23,42,.07);
    transition:
        transform .32s cubic-bezier(.22,.68,0,1.2),
        box-shadow .32s ease;
    cursor: default;
}

article.vs-store-card-directory:hover {
    transform: translateY(-6px) scale(1.012);
    box-shadow:
        0 2px 4px rgba(0,0,0,.04),
        0 12px 40px rgba(37,99,235,.14),
        0 0 0 1.5px rgba(37,99,235,.12);
}

/* ── Banner ── */
.vs-store-card-banner {
    height: 110px;
    background-size: cover;
    background-position: center;
    position: relative;
    transition: filter .32s ease;
}

article.vs-store-card-directory:hover .vs-store-card-banner {
    filter: brightness(1.05) saturate(1.1);
}

.vs-store-card-banner.is-empty {
    background: linear-gradient(135deg, #dbeafe 0%, #ede9fe 50%, #fce7f3 100%);
}

/* ── Body ── */
.vs-store-card-body {
    padding: 20px 22px 22px;
    position: relative;
}

/* ══════════════════════════════════════════════
   FOLLOWING WATERMARK  — the special effect
   ══════════════════════════════════════════════ */

/* Ribbon watermark in top-right corner of the card */
.vs-following-watermark {
    position: absolute;
    top: 0;
    right: 0;
    width: 90px;
    height: 90px;
    overflow: hidden;
    pointer-events: none;
    z-index: 10;
}

.vs-following-watermark::before {
    content: '✓ Following';
    position: absolute;
    top: 20px;
    right: -22px;
    width: 110px;
    text-align: center;
    background: linear-gradient(90deg, #059669, #10b981);
    color: #fff;
    font-family: 'Sora', sans-serif;
    font-size: 10.5px;
    font-weight: 700;
    letter-spacing: .04em;
    padding: 5px 0;
    transform: rotate(45deg);
    box-shadow: 0 2px 8px rgba(16,185,129,.4);
}

/* Subtle glow ring on the banner when following */
article.vs-store-card-directory.is-following .vs-store-card-banner {
    box-shadow: inset 0 0 0 3px rgba(16,185,129,.45);
}

/* Soft tint on card bottom-right when following */
article.vs-store-card-directory.is-following::after {
    content: '';
    position: absolute;
    bottom: 0;
    right: 0;
    width: 120px;
    height: 120px;
    background: radial-gradient(circle at bottom right, rgba(16,185,129,.09) 0%, transparent 70%);
    pointer-events: none;
    border-radius: 0 0 20px 0;
}

/* ── Card Head (logo + name) ── */
.vs-store-card-head {
    display: flex;
    align-items: center;
    gap: 14px;
    margin-bottom: 18px;
}

.vs-store-card-head h3 {
    font-family: 'Sora', sans-serif;
    font-size: 1rem;
    font-weight: 700;
    color: #0f172a;
    margin: 0 0 3px;
    letter-spacing: -.01em;
    line-height: 1.3;
}

.vs-store-card-subtitle {
    font-size: .83rem;
    color: #94a3b8;
    margin: 0;
}

/* ── Logo ── */
.vs-store-card-logo {
    width: 52px;
    height: 52px;
    border-radius: 14px;
    object-fit: cover;
    flex-shrink: 0;
    box-shadow: 0 2px 8px rgba(0,0,0,.1);
    border: 2px solid #fff;
    transition: transform .28s ease;
}

article.vs-store-card-directory:hover .vs-store-card-logo {
    transform: scale(1.06) rotate(-2deg);
}

.vs-store-card-logo.is-placeholder {
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #2563eb, #7c3aed);
    color: #fff;
    font-family: 'Sora', sans-serif;
    font-size: 1.3rem;
    font-weight: 700;
}

/* ── Divider ── */
.vs-card-divider {
    height: 1px;
    background: #f1f5f9;
    margin: 0 0 16px;
}

/* ── Action Buttons Row ── */
.vs-store-card-actions {
    display: flex;
    align-items: center;
    gap: 10px;
    flex-wrap: wrap;
}

/* Visit Store Button */
.vs-btn-visit {
    display: inline-flex;
    align-items: center;
    gap: 7px;
    padding: 9px 16px;
    background: #2563eb;
    color: #fff !important;
    border-radius: 10px;
    text-decoration: none !important;
    font-family: 'Sora', sans-serif;
    font-size: .82rem;
    font-weight: 600;
    letter-spacing: .01em;
    box-shadow: 0 2px 8px rgba(37,99,235,.25);
    transition:
        background .22s ease,
        box-shadow .22s ease,
        transform .18s ease;
}

.vs-btn-visit:hover {
    background: #1d4ed8;
    box-shadow: 0 4px 14px rgba(37,99,235,.4);
    transform: translateY(-1px);
    color: #fff !important;
}

.vs-btn-visit:active {
    transform: translateY(0);
}

/* Share Button */
.vs-share-store-btn {
    display: inline-flex;
    align-items: center;
    gap: 7px;
    padding: 9px 14px;
    background: #fff;
    color: #16a34a;
    border: 1.5px solid #bbf7d0;
    border-radius: 10px;
    cursor: pointer;
    font-family: 'Sora', sans-serif;
    font-size: .82rem;
    font-weight: 600;
    box-shadow: 0 1px 4px rgba(22,163,74,.08);
    transition:
        background .22s ease,
        border-color .22s ease,
        box-shadow .22s ease,
        transform .18s ease;
}

.vs-share-store-btn:hover {
    background: #f0fdf4;
    border-color: #16a34a;
    box-shadow: 0 4px 12px rgba(22,163,74,.2);
    transform: translateY(-1px);
}

.vs-share-store-btn:active {
    transform: translateY(0);
}

/* Copied! message */
.vs-share-msg {
    font-size: .78rem;
    font-weight: 600;
    color: #10b981;
    display: none;
    animation: vsFadeIn .25s ease;
}

@keyframes vsFadeIn {
    from { opacity: 0; transform: translateX(-4px); }
    to   { opacity: 1; transform: translateX(0); }
}

/* ── Responsive ── */
@media (max-width: 480px) {
    .vs-stores-grid { grid-template-columns: 1fr; gap: 18px; }
    .vs-stores-page { padding: 24px 14px 48px; }
}
</style>

<!-- ── Hero ── -->
<div class="vs-stores-hero">
    <h2><?php echo esc_html__('Stores', 'vendor-space'); ?></h2>
    <p style="color:white;"><?php echo esc_html__('Browse all vendor stores and their public information.', 'vendor-space'); ?></p>
</div>

<?php if (empty($stores_view)): ?>
    <div class="vs-stores-empty">
        <?php echo esc_html__('No stores are available yet.', 'vendor-space'); ?>
    </div>
<?php else: ?>

    <div class="vs-stores-grid">
        <?php foreach ($stores_view as $index => $store):

            $is_following = is_user_logged_in() && function_exists('lux_is_vendor_followed')
                ? lux_is_vendor_followed($store['vendor_id'])
                : false;

            $store_url = get_author_posts_url((int) $store['vendor_id']);
        ?>
            <article
                class="vs-store-card-directory<?php echo $is_following ? ' is-following' : ''; ?>"
                style="--vs-delay: <?php echo esc_attr((string) ($index * 70)); ?>ms;"
            >

                <!-- ── Following Watermark (ribbon) ── -->
                <?php if ($is_following): ?>
                    <div class="vs-following-watermark" aria-label="<?php esc_attr_e('You are following this store', 'vendor-space'); ?>"></div>
                <?php endif; ?>

                <!-- ── Banner ── -->
                <?php if ($store['banner_url'] !== ''): ?>
                    <div class="vs-store-card-banner" style="background-image:url('<?php echo esc_url($store['banner_url']); ?>');"></div>
                <?php else: ?>
                    <div class="vs-store-card-banner is-empty"></div>
                <?php endif; ?>

                <!-- ── Body ── -->
                <div class="vs-store-card-body">

                    <!-- Logo + Name -->
                    <div class="vs-store-card-head">
                        <?php if ($store['logo_url'] !== ''): ?>
                            <img
                                class="vs-store-card-logo"
                                src="<?php echo esc_url($store['logo_url']); ?>"
                                alt="<?php echo esc_attr($store['store_name']); ?>"
                            >
                        <?php else: ?>
                            <div class="vs-store-card-logo is-placeholder">
                                <?php echo esc_html($store['initial']); ?>
                            </div>
                        <?php endif; ?>

                        <div>
                            <h3><?php echo esc_html($store['store_name']); ?></h3>
                            <p class="vs-store-card-subtitle"><?php echo esc_html($store['owner_name']); ?></p>
                            <div><strong><?php echo esc_html__('Products:', 'vendor-space'); ?></strong> <?php echo esc_html((string) (int) $store['products_count']); ?></div>

                        </div>
                    </div>

                    <div class="vs-card-divider"></div>

                    <!-- Action Buttons -->
                    <div class="vs-store-card-actions">

                        <a href="<?php echo esc_url($store_url); ?>" class="vs-btn-visit">
                            <i class="fas fa-store"></i>
                            <span><?php echo esc_html__('Visit Store', 'vendor-space'); ?></span>
                        </a>

                        <button
                            class="vs-share-store-btn"
                            data-url="<?php echo esc_url($store_url); ?>"
                            type="button"
                        >
                            <i class="fas fa-share-alt"></i>
                            <span><?php echo esc_html__('Share', 'vendor-space'); ?></span>
                        </button>

                        <span class="vs-share-msg">
                            <?php echo esc_html__('Copied!', 'vendor-space'); ?>
                        </span>

                    </div><!-- /.vs-store-card-actions -->

                </div><!-- /.vs-store-card-body -->

            </article>
        <?php endforeach; ?>
    </div><!-- /.vs-stores-grid -->

<?php endif; ?>

<!-- Share button JS (unchanged logic, cleaner scope) -->
<script>
(function () {
    document.querySelectorAll('.vs-share-store-btn').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var url = btn.dataset.url;
            var msg = btn.parentElement.querySelector('.vs-share-msg');
            if (!url) return;

            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(url).then(showMsg);
            } else {
                var ta = document.createElement('textarea');
                ta.value = url;
                ta.style.cssText = 'position:fixed;top:-9999px;left:-9999px;opacity:0';
                document.body.appendChild(ta);
                ta.select();
                document.execCommand('copy');
                document.body.removeChild(ta);
                showMsg();
            }

            function showMsg() {
                if (!msg) return;
                msg.style.display = 'inline';
                setTimeout(function () { msg.style.display = 'none'; }, 2000);
            }
        });
    });
})();
</script>

</div><!-- /.vs-stores-page -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.vs-share-store-btn').forEach(btn => {
        const msg = btn.nextElementSibling;
        btn.addEventListener('click', function() {
            const url = this.dataset.url;

            if(navigator.share){
                navigator.share({
                    title: document.title,
                    url: url
                }).then(()=> console.log('<?php echo esc_js(__('Shared successfully', 'vendor-space')); ?>'))
                .catch(err=> console.log('<?php echo esc_js(__('Share failed', 'vendor-space')); ?>', err));
            } 
        });
    });
});
</script>

                <?php if ($stores_max_pages > 1): ?>
                    <div style="margin-top:16px;display:flex;gap:8px;flex-wrap:wrap;align-items:center;">
                        <?php if ($stores_page > 1): ?>
                            <?php
                            $prev_stores_url = add_query_arg(
                                ['stores_page' => $stores_page - 1],
                                remove_query_arg(['store_id', 'vs_page', 'stores_page'], $directory_url)
                            );
                            ?>
                            <a href="<?php echo esc_url($prev_stores_url); ?>"
                               style="padding:7px 10px;border-radius:8px;text-decoration:none;border:1px solid #dbeafe;background:#eff6ff;color:#1d4ed8;">
                                <?php echo esc_html__('Previous', 'vendor-space'); ?>
                            </a>
                        <?php endif; ?>

                        <?php for ($i = 1; $i <= $stores_max_pages; $i++): ?>
                            <?php
                            $stores_page_url = add_query_arg(
                                ['stores_page' => $i],
                                remove_query_arg(['store_id', 'vs_page', 'stores_page'], $directory_url)
                            );
                            ?>
                            <a href="<?php echo esc_url($stores_page_url); ?>"
                               style="padding:7px 10px;border-radius:8px;text-decoration:none;border:1px solid <?php echo $i === $stores_page ? '#2563eb' : '#e5e7eb'; ?>;background:<?php echo $i === $stores_page ? '#2563eb' : '#fff'; ?>;color:<?php echo $i === $stores_page ? '#fff' : '#0f172a'; ?>;">
                                <?php echo esc_html((string) $i); ?>
                            </a>
                        <?php endfor; ?>

                        <?php if ($stores_page < $stores_max_pages): ?>
                            <?php
                            $next_stores_url = add_query_arg(
                                ['stores_page' => $stores_page + 1],
                                remove_query_arg(['store_id', 'vs_page', 'stores_page'], $directory_url)
                            );
                            ?>
                            <a href="<?php echo esc_url($next_stores_url); ?>"
                               style="padding:7px 10px;border-radius:8px;text-decoration:none;border:1px solid #dbeafe;background:#eff6ff;color:#1d4ed8;">
                                <?php echo esc_html__('Next', 'vendor-space'); ?>
                            </a>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
        </div>
        <?php
        return ob_get_clean();
    }

    

    private static function get_stores_data($paged = 1, $per_page = 12) {
        $paged = max(1, (int) $paged);
        $per_page = max(1, (int) $per_page);
        $cache_key = sprintf('vs_stores_%d_%d', $paged, $per_page);

        $cached = get_transient($cache_key);
        if ($cached !== false && is_array($cached)) {
            return $cached;
        }

        $stores = [];
        $vendor_ids = self::get_vendor_ids();

       foreach ($vendor_ids as $vendor_id) {

    $is_active = get_user_meta($vendor_id, 'vs_vendor_status', true);

    if ($is_active !== 'active') {
        continue;
    }

    $store = self::get_store_data((int) $vendor_id);

    if ($store) {
        $stores[] = $store;
    }
}
        usort($stores, fn($a, $b) =>
            strcasecmp($a['store_name'] ?? '', $b['store_name'] ?? '')
        );

        $total_stores = count($stores);
        $offset = ($paged - 1) * $per_page;
        $stores_view = array_slice($stores, $offset, $per_page);

        $result = [
            'stores' => $stores_view,
            'total' => $total_stores,
        ];

        set_transient($cache_key, $result, HOUR_IN_SECONDS);

        return $result;
    }

    private static function get_store_data($vendor_id) {
        $vendor_id = (int) $vendor_id;
        if ($vendor_id <= 0) {
            return null;
        }

        $vendor_user = get_userdata($vendor_id);
        if (!$vendor_user) {
            return null;
        }

        $visibility = get_user_meta($vendor_id, 'vs_store_visibility', true);
        if (!is_array($visibility)) {
            $visibility = [];
        }
        $visibility = wp_parse_args($visibility, [
            'contact_info' => true,
            'social_links' => true,
            'store_description' => true,
            'operating_hours' => true,
        ]);

        $products_count = (int) count_user_posts($vendor_id, 'product', false);
        if (!self::has_store_metadata($vendor_id) && $products_count <= 0) {
            return null;
        }

        $store_name = trim((string) get_user_meta($vendor_id, 'vs_store_name', true));
        if ($store_name === '') {
            $store_name = $vendor_user->display_name;
        }

        $social = get_user_meta($vendor_id, 'vs_store_social_links', true);
        if (!is_array($social)) {
            $social = [];
        }
        $social = array_filter([
            'facebook' => esc_url_raw($social['facebook'] ?? ''),
            'instagram' => esc_url_raw($social['instagram'] ?? ''),
            'x' => esc_url_raw($social['x'] ?? ''),
            'linkedin' => esc_url_raw($social['linkedin'] ?? ''),
            'youtube' => esc_url_raw($social['youtube'] ?? ''),
        ]);

        $contact_email = (string) get_user_meta($vendor_id, 'vs_store_contact_email', true);
        if ($contact_email === '') {
            $contact_email = $vendor_user->user_email;
        }

        $description_raw = wp_strip_all_tags((string) get_user_meta($vendor_id, 'vs_store_desc', true));
        $description_short = $description_raw;
        if ($description_short !== '') {
            $description_short = wp_trim_words($description_short, 28, '...');
        }

        $initial = strtoupper(substr($store_name, 0, 1));
        if ($initial === '') {
            $initial = 'S';
        }

        return [
            'vendor_id' => $vendor_id,
            'store_name' => $store_name,
            'owner_name' => $vendor_user->display_name,
            'description' => $visibility['store_description'] ? $description_short : '',
            'description_full' => $visibility['store_description'] ? $description_raw : '',
            'location' => (string) get_user_meta($vendor_id, 'vs_store_location', true),
            'address' => (string) get_user_meta($vendor_id, 'vs_store_address', true),
            'contact_email' => $visibility['contact_info'] ? $contact_email : '',
            'contact_phone' => $visibility['contact_info'] ? (string) get_user_meta($vendor_id, 'vs_store_contact_phone', true) : '',
            'operating_hours' => $visibility['operating_hours'] ? (string) get_user_meta($vendor_id, 'vs_store_operating_hours', true) : '',
            'social' => $visibility['social_links'] ? $social : [],
            'products_count' => $products_count,
            'logo_url' => wp_get_attachment_image_url((int) get_user_meta($vendor_id, 'vs_store_logo_id', true), 'thumbnail') ?: '',
            'banner_url' => wp_get_attachment_image_url((int) get_user_meta($vendor_id, 'vs_store_banner_id', true), 'large') ?: '',
            'initial' => $initial,
        ];
    }

    public static function get_stores_directory_url() {
        $queried_id = (int) get_queried_object_id();
        if ($queried_id > 0) {
            $url = get_permalink($queried_id);
            if ($url) {
                return $url;
            }
        }
        return home_url('/stores/');
    }

    private static function get_vendor_ids() {
        $ids = [];

        $query_sets = [
            get_users([
               'role__in' => ['vendor', 'administrator'],
                'fields' => 'ID',
                'number' => -1,
            ]),
            get_users([
                'meta_key' => 'vs_store_name',
                'meta_compare' => 'EXISTS',
                'fields' => 'ID',
                'number' => -1,
            ]),
            get_users([
                'capability' => 'edit_products',
                'fields' => 'ID',
                'number' => -1,
            ]),
        ];

        foreach ($query_sets as $query_ids) {
            foreach ((array) $query_ids as $user_id) {
                $ids[(int) $user_id] = (int) $user_id;
            }
        }

        $ids = array_values($ids);
        $filtered = [];
        foreach ($ids as $user_id) {
            if (user_can($user_id, 'manage_options')) {
                continue;
            }
            $filtered[] = $user_id;
        }

        return $filtered;
    }

    private static function has_store_metadata($user_id) {
        $keys = [
            'vs_store_name',
            'vs_store_desc',
            'vs_store_location',
            'vs_store_contact_email',
            'vs_store_contact_phone',
            'vs_store_address',
            'vs_store_operating_hours',
            'vs_store_logo_id',
            'vs_store_banner_id',
        ];

        foreach ($keys as $meta_key) {
            $value = get_user_meta($user_id, $meta_key, true);
            if (is_string($value) && trim($value) !== '') {
                return true;
            }
            if (is_numeric($value) && (int) $value > 0) {
                return true;
            }
        }

        return false;
    }
}