<?php
/**
 * Themesdealer Functions and definitions
 * প্রথম সমাচার - সবসময় দৃশ্যমান পোল, ডুপ্লিকেট চেকিং এবং হোমপেজ ও নিউজ শেয়ার ফিক্স
 * ২০২৬-০২-২৬ তারিখে চূড়ান্তভাবে ডাবল চেক করা হয়েছে। 
 */

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

/* [১] বাংলা সংখ্যা ও তারিখ সুরক্ষা */
if ( ! function_exists( 'bn_number' ) ) {
    function bn_number($str) {
        $en = array(1,2,3,4,5,6,7,8,9,0); $bn = array('১','২','৩','৪','৫','৬','৭','৮','৯','০');
        return str_replace($en, $bn, $str);
    }
}
if ( ! function_exists( 'bangla_date' ) ) {
    function bangla_date($str) {
        $en = array(1,2,3,4,5,6,7,8,9,0,'January','February','March','April','May','June','July','August','September','October','November','December','am','pm','Saturday','Sunday','Monday','Tuesday','Wednesday','Thursday','Friday');
        $bn = array('১','২','৩','৪','৫','৬','৭','৮','৯','০','জানুয়ারি','ফেব্রুয়ারি','মার্চ','এপ্রিল','মে','জুন','জুলাই','অগাস্ট','সেপ্টেম্বর','অক্টোবর','নভেম্বর','ডিসেম্বর','পূর্বাহ্ন','অপরাহ্ন','শনিবার','রোববার','সোমবার','মঙ্গলবার','বুধবার','বৃহস্পতিবার','শুক্রবার');
        return str_replace($en, $bn, $str);
    }
}

/* [২] থিম সাপোর্ট ও স্ক্রিপ্ট লোড */
function ps_theme_setup_master() {
    add_theme_support( 'title-tag' ); 
    add_theme_support( 'post-thumbnails' );
    add_theme_support( 'custom-logo' ); 
}
add_action( 'after_setup_theme', 'ps_theme_setup_master' );

function ps_enqueue_master_scripts() {
    wp_enqueue_style( 'bootstrap', get_template_directory_uri() . '/assets/css/bootstrap.min.css' );
    wp_enqueue_style( 'font-awesome', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css' );
    wp_enqueue_style( 'theme-style', get_stylesheet_uri() );
    wp_enqueue_script( 'jquery' );
    wp_enqueue_script( 'bootstrap-js', get_template_directory_uri() . '/assets/js/bootstrap.min.js', array('jquery'), '', true );
}
add_action( 'wp_enqueue_scripts', 'ps_enqueue_master_scripts' );

/* [৩] মাস্টার সিএসএস - হোভার প্যানেল, মেনু লেআউট ও পোল ডিজাইন */
function ps_inject_solid_master_styles() {
    echo "
    <style>
        @import url('https://fonts.cdnfonts.com/css/solaimanlipi');
        body, html, h1, h2, h3, h4, h5, h6, p, a, span, li, div, input, button { font-family: 'SolaimanLipi', sans-serif !important; }

        /* পেজ ব্রেকিং ফিক্স */
        .ps-sticky-bar { background: #fff; border-bottom: 3px solid #010B1D; }
        .ps-sticky-bar .container { display: flex !important; align-items: center !important; justify-content: space-between !important; max-width: 100% !important; padding: 0 15px !important; }
        .navbar-nav { display: flex !important; flex-direction: row !important; flex-wrap: nowrap !important; align-items: center !important; width: 100%; margin: 0 !important; }

        /* মেনু ফন্ট ও হোম বাটন */
        .navbar-nav li a { color: #010B1D !important; font-weight: 900 !important; font-size: 22px !important; padding: 12px 14px !important; text-decoration: none !important; transition: 0.3s; }
        .navbar-nav li a:hover { color: #D80000 !important; }

        .navbar-nav > li:first-child > a::before {
            content: '\\f015'; font-family: FontAwesome; font-size: 22px !important; color: #fff; background: #6c757d; 
            width: 40px !important; height: 40px !important; display: inline-flex; align-items: center; justify-content: center; 
            border-radius: 4px; transition: 0.3s;
        }

        /* থ্রি-লাইন আইকন */
        .trigger-area { margin-left: auto !important; }
        .trigger-area a { background: #f1f1f1 !important; border: 1px solid #ddd !important; border-radius: 4px; width: 42px !important; height: 42px !important; display: flex !important; align-items: center; justify-content: center; padding: 0 !important; cursor: pointer; }
        .trigger-area a:hover { background: #D80000 !important; border-color: #D80000 !important; }
        .trigger-area a i { font-size: 20px !important; color: #010B1D; transition: 0.3s; }
        .trigger-area a:hover i { color: #fff !important; }

        /* হোভার প্যানেল */
        .ps-all-cats-panel { position: fixed; top: 0; right: -350px; width: 320px; height: 100vh; background: #fff; z-index: 9999999; box-shadow: -5px 0 15px rgba(0,0,0,0.1); transition: right 0.3s ease-in-out; overflow-y: auto; padding: 25px; }
        .ps-all-cats-panel.active { right: 0; }
        .ps-panel-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100vh; background: rgba(0,0,0,0.5); z-index: 9999998; display: none; }

        /* অনলাইন জরিপ উন্নত ডিজাইন */
        .ps-poll-msg { color: #fff; background: #D80000; padding: 8px; border-radius: 4px; text-align: center; font-weight: bold; font-size: 15px; margin-bottom: 15px; display: none; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
        .poll-res-bar { background: #eee; height: 10px; border-radius: 10px; margin: 5px 0 10px; overflow: hidden; }

        @media (min-width: 992px) {
            .navbar-header, .navbar-toggle, .mobile-menu-wrapper, .ps-mobile-only, .ps-m-drawer, .drawer-overlay { display: none !important; }
            .ps-sticky-bar { position: sticky !important; top: 0; z-index: 99999; }
        }
    </style>
    ";
}
add_action('wp_head', 'ps_inject_solid_master_styles', 1000);

/* [৪] হোভার প্যানেল ও মাস্টার সার্চ জাভাস্ক্রিপ্ট */
function ps_all_categories_panel_html() {
    echo '<div class="ps-panel-overlay"></div><div class="ps-all-cats-panel" id="hover-panel">';
    echo '<div class="ps-panel-logo-box" style="text-align:center; margin-bottom:20px; border-bottom:2px solid #eee; padding-bottom:15px;">';
    $custom_logo_id = get_theme_mod( 'custom_logo' );
    if ( $custom_logo_id ) {
        echo '<a href="'.esc_url(home_url('/')).'"><img src="'.esc_url(wp_get_attachment_image_url($custom_logo_id, 'full')).'" style="max-width:220px; height:auto;"></a>';
    } else {
        echo '<a href="'.esc_url(home_url('/')).'" style="font-size:24px; font-weight:900; color:#010B1D; text-decoration:none;">'.get_bloginfo('name').'</a>';
    }
    echo '</div><ul>';
    
    $menu_cats = array();
    $menus = wp_get_nav_menus();
    if(!empty($menus)) {
        $menu_items = wp_get_nav_menu_items($menus[0]->term_id); 
        if($menu_items) {
            foreach($menu_items as $item) {
                if($item->object == 'category') {
                    echo '<li><a href="'.esc_url($item->url).'" style="display:block; padding:10px 0; color:#010B1D; font-size:18px; font-weight:bold; border-bottom:1px dashed #eee; text-decoration:none;">'.$item->title.'</a></li>';
                    $menu_cats[] = $item->object_id;
                }
            }
        }
    }
    $categories = get_categories(array('orderby' => 'name', 'order' => 'DESC', 'exclude' => $menu_cats, 'hide_empty' => 0));
    foreach($categories as $category) {
        echo '<li><a href="' . get_category_link($category->term_id) . '" style="display:block; padding:10px 0; color:#010B1D; font-size:18px; font-weight:bold; border-bottom:1px dashed #eee; text-decoration:none;">' . $category->name . '</a></li>';
    }
    echo '</ul></div>';
}
add_action('wp_footer', 'ps_all_categories_panel_html');

function ps_inject_master_js() {
    echo "
    <script>
    jQuery(document).ready(function($) {
        if ($('.navbar-nav').length && $('.trigger-area').length === 0) {
            $('.navbar-nav').append('<li class=\"trigger-area\"><a href=\"javascript:void(0);\"><i class=\"fa fa-bars\"></i></a></li>');
        }

        if($('#ps-master-search').length === 0){
            $('body').append('<div id=\"ps-master-search\" style=\"display:none; position:fixed; top:0; left:0; width:100%; height:100vh; background:rgba(1,11,29,0.96); z-index:99999999; justify-content:center; align-items:center;\"><span id=\"ps-close-search\" style=\"position:absolute; top:30px; right:40px; font-size:50px; color:#D80000; cursor:pointer; font-weight:bold;\">&times;</span><form action=\"" . esc_url(home_url('/')) . "\" method=\"get\" style=\"width:90%; max-width:750px; position:relative;\"><input type=\"text\" name=\"s\" placeholder=\"কী খুঁজতে চান?...\" autocomplete=\"off\" style=\"width:100%; padding:20px 30px; font-size:26px; border:none; border-radius:50px; outline:none; font-family:\'SolaimanLipi\', sans-serif; box-shadow:0 10px 40px rgba(0,0,0,0.6);\"><button type=\"submit\" style=\"position:absolute; right:8px; top:8px; bottom:8px; background:#D80000; color:#fff; border:none; border-radius:50px; padding:0 35px; font-size:22px; font-weight:bold; cursor:pointer; font-family:\'SolaimanLipi\', sans-serif;\"><i class=\"fa fa-search\"></i> খুঁজুন</button></form></div>');
        }

        $(document).on('click', '.fa-search, [class*=\"search-icon\"], [class*=\"search-toggle\"], .header-search a, .search-btn', function(e) {
            if (!$(this).closest('#ps-master-search').length) {
                e.preventDefault(); e.stopPropagation(); 
                $('#ps-master-search').css('display', 'flex').hide().fadeIn(250);
                setTimeout(function(){ $('#ps-master-search input[name=\"s\"]').focus(); }, 300);
            }
        });

        $(document).on('submit', 'form', function(e) {
            var isSearchForm = $(this).find('input[name=\"s\"]').length > 0;
            var isOurSearch = $(this).closest('#ps-master-search').length > 0;
            if (isSearchForm && !isOurSearch) {
                e.preventDefault();
                $('#ps-master-search').css('display', 'flex').hide().fadeIn(250);
                setTimeout(function(){ $('#ps-master-search input[name=\"s\"]').focus(); }, 300);
            }
        });

        $(document).on('click', '#ps-close-search', function() { $('#ps-master-search').fadeOut(250); });

        var timer;
        $('.trigger-area, #hover-panel').on('mouseenter', function() {
            clearTimeout(timer); $('#hover-panel').addClass('active'); $('.ps-panel-overlay').stop(true, true).fadeIn(200);
        }).on('mouseleave', function() {
            timer = setTimeout(function() { $('#hover-panel').removeClass('active'); $('.ps-panel-overlay').stop(true, true).fadeOut(200); }, 300); 
        });
    });
    </script>
    ";
}
add_action('wp_footer', 'ps_inject_master_js', 100);

/* [৫] অনলাইন জরিপ ড্যাশবোর্ড মেনু */
function ps_register_online_poll_cpt() {
    register_post_type('online_poll', array(
        'labels' => array('name' => 'অনলাইন জরিপ', 'menu_name' => 'অনলাইন জরিপ', 'add_new' => 'নতুন জরিপ'),
        'public' => true, 'show_ui' => true, 'menu_icon' => 'dashicons-chart-pie', 'supports' => array('title')
    ));
}
add_action('init', 'ps_register_online_poll_cpt');

/* [৬] উন্নত পোল লজিক (AJAX হ্যান্ডলার ও JSON) */
function ps_get_poll_results_html($pid) {
    $yes = (int)get_post_meta($pid, 'poll_yes', true); $no = (int)get_post_meta($pid, 'poll_no', true);
    $total = ($yes + $no) ?: 1;
    $y_p = round(($yes / $total) * 100); $n_p = round(($no / $total) * 100);
    ob_start(); ?>
    <div class="ps-poll-option-result">
        <div style="display:flex; justify-content:space-between; margin-bottom:5px;">
            <span style="font-weight:bold; font-size:17px; color:#010B1D;"><i class="fa fa-check-circle" style="color:green; margin-right:5px;"></i> হ্যাঁ</span>
            <span style="font-weight:bold; font-size:17px; color:#010B1D;"><?php echo bn_number($y_p); ?>%</span>
        </div>
        <div class="poll-res-bar"><div style="width:<?php echo $y_p; ?>%; background:green; height:100%; border-radius:10px;"></div></div>
    </div>
    <div class="ps-poll-option-result" style="margin-top:15px;">
        <div style="display:flex; justify-content:space-between; margin-bottom:5px;">
            <span style="font-weight:bold; font-size:17px; color:#010B1D;"><i class="fa fa-times-circle" style="color:red; margin-right:5px;"></i> না</span>
            <span style="font-weight:bold; font-size:17px; color:#010B1D;"><?php echo bn_number($n_p); ?>%</span>
        </div>
        <div class="poll-res-bar"><div style="width:<?php echo $n_p; ?>%; background:red; height:100%; border-radius:10px;"></div></div>
    </div>
    <p style="text-align:center; font-weight:bold; font-size:15px; margin-top:20px; color:#666; border-top:1px dashed #eee; padding-top:10px;">মোট ভোট: <?php echo bn_number($total); ?> জন</p>
    <?php return ob_get_clean();
}

add_action('wp_ajax_ps_v_act', 'ps_v_h'); add_action('wp_ajax_nopriv_ps_v_act', 'ps_v_h');
function ps_v_h() {
    $pid = intval($_POST['pid']); $pv = sanitize_text_field($_POST['pv']);
    
    if(isset($_COOKIE['ps_v_d_'.$pid])){
        wp_send_json(array('status' => 'already_voted', 'html' => ps_get_poll_results_html($pid)));
        die();
    }
    
    if($pv=='yes'||$pv=='no'){
        update_post_meta($pid, 'poll_'.$pv, (int)get_post_meta($pid, 'poll_'.$pv, true)+1);
        setcookie('ps_v_d_'.$pid, '1', time()+(86400 * 30), "/");
        wp_send_json(array('status' => 'success', 'html' => ps_get_poll_results_html($pid)));
    }
    die();
}

/* [৭] পোল শর্টকোড */
add_shortcode('ps_online_poll', 'ps_p_master');
function ps_p_master() {
    $pq = new WP_Query(array('post_type'=>'online_poll', 'posts_per_page'=>1));
    if ($pq->have_posts()) : while ($pq->have_posts()) : $pq->the_post(); 
        $pid = get_the_ID(); ob_start(); ?>
        <div style="background:#fff; border:1px solid #ddd; padding:20px; border-radius:8px; margin-top:20px;">
            <div style="border-bottom:2px solid #010B1D; margin-bottom:15px; padding-bottom:5px;">
                <a href="<?php echo esc_url(home_url('/?post_type=online_poll')); ?>" style="color:#010B1D; font-weight:900; font-size:18px; text-decoration:none; display:flex; justify-content:space-between; align-items:center;">
                    <span>অনলাইন জরিপ</span> <i class="fa fa-angle-double-right"></i>
                </a>
            </div>
            
            <div id="p-area-<?php echo $pid; ?>">
                <div class="ps-poll-msg" id="poll-msg-<?php echo $pid; ?>">আপনি ইতিমধ্যে আপনার মতামত প্রদান করেছেন।</div>
                
                <p style="font-weight:bold; margin-bottom:15px; font-size:17px; line-height:1.4; color:#010B1D;"><?php the_title(); ?></p>
                
                <form class="ps-poll-form" id="form-<?php echo $pid; ?>">
                    <input type="hidden" name="pid" value="<?php echo $pid; ?>">
                    <label style="display:block; cursor:pointer; margin-bottom:12px; font-size:17px; font-weight:bold; color:#333; border:1px solid #eee; padding:8px 12px; border-radius:4px; transition:0.3s;" onmouseover="this.style.background='#f9f9f9'" onmouseout="this.style.background='transparent'"><input type="radio" name="pv" value="yes" style="margin-right:8px;"> হ্যাঁ</label>
                    <label style="display:block; cursor:pointer; font-size:17px; font-weight:bold; color:#333; border:1px solid #eee; padding:8px 12px; border-radius:4px; transition:0.3s;" onmouseover="this.style.background='#f9f9f9'" onmouseout="this.style.background='transparent'"><input type="radio" name="pv" value="no" style="margin-right:8px;"> না</label>
                </form>

                <div id="poll-res-<?php echo $pid; ?>" style="display:none; margin-top:10px;"></div>
            </div>
        </div>
        <script>
        jQuery(document).ready(function($) {
            $(document).on('change', '#form-<?php echo $pid; ?> input[name="pv"]', function() {
                var pid = '<?php echo $pid; ?>';
                var val = $(this).val();
                var msgArea = $('#poll-msg-' + pid);
                var resArea = $('#poll-res-' + pid);
                var formArea = $('#form-' + pid);
                
                $.ajax({
                    url: "<?php echo admin_url('admin-ajax.php'); ?>",
                    type: 'POST',
                    dataType: 'json',
                    data: { action: 'ps_v_act', pid: pid, pv: val },
                    success: function(res) {
                        if(res.status === "already_voted"){
                            msgArea.slideDown(200).delay(3500).slideUp(200);
                            formArea.hide(); 
                            resArea.html(res.html).fadeIn(300); 
                        } else if(res.status === "success") {
                            formArea.hide(); 
                            resArea.html(res.html).fadeIn(300);
                        }
                    }
                });
            });
        });
        </script>
    <?php endwhile; wp_reset_postdata(); endif; return ob_get_clean();
}

/* [৮] ফেসবুক ও সোশ্যাল মিডিয়া শেয়ারিং ফিক্স (নিউজ ও হোমপেজ) */
function ps_add_open_graph_tags() {
    if (is_single()) {
        global $post;
        if (has_post_thumbnail($post->ID)) {
            $img_src = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'full');
            if ($img_src) {
                echo '<meta property="og:image" content="' . esc_attr($img_src[0]) . '"/>' . "\n";
                echo '<meta property="og:type" content="article"/>' . "\n";
                echo '<meta property="og:url" content="' . get_permalink() . '"/>' . "\n";
                echo '<meta property="og:title" content="' . esc_attr(get_the_title()) . '"/>' . "\n";
                echo '<meta property="og:description" content="' . esc_attr(wp_trim_words(get_the_excerpt(), 30)) . '"/>' . "\n";
            }
        }
    } elseif (is_front_page() || is_home()) {
        // হোমপেজের জন্য লজিক
        $custom_logo_id = get_theme_mod('custom_logo');
        $logo_url = $custom_logo_id ? wp_get_attachment_image_url($custom_logo_id, 'full') : '';
        echo '<meta property="og:type" content="website"/>' . "\n";
        echo '<meta property="og:url" content="' . esc_url(home_url('/')) . '"/>' . "\n";
        echo '<meta property="og:title" content="' . esc_attr(get_bloginfo('name')) . '"/>' . "\n";
        echo '<meta property="og:description" content="' . esc_attr(get_bloginfo('description')) . '"/>' . "\n";
        if ($logo_url) {
            echo '<meta property="og:image" content="' . esc_attr($logo_url) . '"/>' . "\n";
        }
    }
    echo '<meta property="og:site_name" content="' . get_bloginfo('name') . '"/>' . "\n";
    echo '<meta name="twitter:card" content="summary_large_image"/>' . "\n";
}
add_action('wp_head', 'ps_add_open_graph_tags', 5);

/* [৯] ফ্রেমওয়ার্ক ইনক্লুড */
$ps_base = get_template_directory();
$includes = array('/framework/ReduxCore/framework.php', '/framework/sample/config.php', '/include/menu.php', '/include/wp-bootstrap-navwalker.php', '/include/widget.php', '/include/customs_post.php', '/assets/file/metabox/init.php', '/assets/file/metabox/functions.php');
foreach ($includes as $file) { if (file_exists($ps_base . $file)) { require_once($ps_base . $file); } }