<?php
/**
 * Elementor Widget: GB Découvrez Grid
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

class Guide_Benin_Decouvrez_Grid_Widget extends \Elementor\Widget_Base {

    public function get_name() {
        return 'gb_decouvrez_grid';
    }

    public function get_title() {
        return __( 'GB Découvrez Grid', 'guide-benin' );
    }

    public function get_icon() {
        return 'eicon-inner-section';
    }

    public function get_categories() {
        return array( 'guide-benin' );
    }

    protected function register_controls() {
        $this->start_controls_section(
            'section_content',
            array(
                'label' => __( 'Filtres de Destinations', 'guide-benin' ),
            )
        );

        $this->add_control(
            'count_text',
            array(
                'label'   => __( 'Texte Nombre de Destinations', 'guide-benin' ),
                'type'    => \Elementor\Controls_Manager::TEXT,
                'default' => '12 destinations',
            )
        );

        $this->end_controls_section();

        $this->start_controls_section(
            'section_query',
            array(
                'label' => __( 'Options de Requête', 'guide-benin' ),
            )
        );

        $this->add_control(
            'posts_per_page',
            array(
                'label'   => __( 'Nombre d\'éléments', 'guide-benin' ),
                'type'    => \Elementor\Controls_Manager::NUMBER,
                'default' => 12,
                'min'     => -1,
                'max'     => 100,
            )
        );

        $this->add_control(
            'orderby',
            array(
                'label'   => __( 'Trier par', 'guide-benin' ),
                'type'    => \Elementor\Controls_Manager::SELECT,
                'default' => 'date',
                'options' => array(
                    'date'  => __( 'Date', 'guide-benin' ),
                    'title' => __( 'Titre', 'guide-benin' ),
                    'rand'  => __( 'Aléatoire', 'guide-benin' ),
                ),
            )
        );

        $this->add_control(
            'order',
            array(
                'label'   => __( 'Ordre', 'guide-benin' ),
                'type'    => \Elementor\Controls_Manager::SELECT,
                'default' => 'DESC',
                'options' => array(
                    'DESC' => __( 'Décroissant', 'guide-benin' ),
                    'ASC'  => __( 'Croissant', 'guide-benin' ),
                ),
            )
        );

        $this->end_controls_section();
    }

    protected function render() {
        $settings = $this->get_settings_for_display();

        $query_args = array(
            'post_type'      => 'destination',
            'posts_per_page' => intval($settings['posts_per_page']),
            'orderby'        => $settings['orderby'],
            'order'          => $settings['order'],
            'post_status'    => 'publish',
        );
        $dest_query = new \WP_Query( $query_args );
        $all_destinations = array();

        if ( $dest_query->have_posts() ) {
            while ( $dest_query->have_posts() ) {
                $dest_query->the_post();
                $post_id = get_the_ID();
                $region = get_post_meta( $post_id, 'region', true );
                $cat = get_post_meta( $post_id, 'cat', true );
                if ( empty( $cat ) ) {
                    $cats = get_the_category();
                    $cat = ! empty( $cats ) ? $cats[0]->name : 'Culture & patrimoine';
                }
                $all_destinations[] = array(
                    'name'   => get_the_title(),
                    'region' => $region ? $region : 'Sud · Atlantique',
                    'cat'    => $cat,
                    'blurb'  => get_the_excerpt() ? get_the_excerpt() : wp_trim_words( get_the_content(), 15 ),
                    'href'   => get_permalink(),
                    'slotId' => '',
                    'thumbnail' => get_the_post_thumbnail_url( $post_id, 'medium_large' ) ? get_the_post_thumbnail_url( $post_id, 'medium_large' ) : 'https://dahomeydiscovery.com/wp-content/uploads/2026/05/Attractions-banner.jpg',
                );

            }
            wp_reset_postdata();
        }

        if ( empty( $all_destinations ) ) {
            $all_destinations = array(
                array('name' => 'Ganvié', 'region' => 'Sud · Lac Nokoué', 'cat' => 'Nature & faune', 'blurb' => 'La plus grande cité lacustre d’Afrique, surnommée la « Venise de l’Afrique ».', 'href' => home_url('/destination/ganvie/'), 'slotId' => 'dc-ganvie', 'thumbnail' => '' ),
                array('name' => 'Ouidah', 'region' => 'Sud · Atlantique', 'cat' => 'Culture & patrimoine', 'blurb' => 'Berceau du Vodun, la Route des esclaves et la Porte du Non-Retour.', 'href' => home_url('/destination/ouidah/'), 'slotId' => 'dc-ouidah', 'thumbnail' => '' ),
                array('name' => 'Palais royaux d’Abomey', 'region' => 'Centre · Zou', 'cat' => 'Culture & patrimoine', 'blurb' => 'Ensemble classé à l’UNESCO, cœur de l’ancien royaume du Dahomey.', 'href' => home_url('/destination/palais-royaux-dabomey/'), 'slotId' => 'dc-abomey', 'thumbnail' => '' ),
                array('name' => 'Parc de la Pendjari', 'region' => 'Nord · Atacora', 'cat' => 'Nature & faune', 'blurb' => 'Réserve de biosphère : éléphants, lions, hippopotames et savanes.', 'href' => home_url('/destination/parc-de-la-pendjari/'), 'slotId' => 'dc-pendjari', 'thumbnail' => '' ),
                array('name' => 'Grand-Popo', 'region' => 'Sud · Mono', 'cat' => 'Plages & lagunes', 'blurb' => 'Longues plages de sable, cocotiers et embouchure de la Bouche du Roy.', 'href' => home_url('/destination/grand-popo/'), 'slotId' => 'dc-grandpopo', 'thumbnail' => '' ),
                array('name' => 'Porto-Novo', 'region' => 'Sud · Ouémé', 'cat' => 'Villes', 'blurb' => 'La capitale, son architecture afro-brésilienne et ses musées.', 'href' => home_url('/destination/porto-novo/'), 'slotId' => 'dc-portonovo', 'thumbnail' => '' ),
                array('name' => 'Cotonou', 'region' => 'Sud · Littoral', 'cat' => 'Villes', 'blurb' => 'Le poumon économique : marché Dantokpa, plage de Fidjrossè et art contemporain.', 'href' => home_url('/destination/cotonou/'), 'slotId' => 'dc-cotonou', 'thumbnail' => '' ),
                array('name' => 'Tata Somba, Boukoumbé', 'region' => 'Nord · Atacora', 'cat' => 'Culture & patrimoine', 'blurb' => 'Les châteaux de terre du pays Tammari, habitat traditionnel fortifié.', 'href' => home_url('/destination/tata-somba-boukoumbe/'), 'slotId' => 'dc-tatasomba', 'thumbnail' => '' ),
                array('name' => 'Dassa-Zoumè', 'region' => 'Centre · Collines', 'cat' => 'Culture & patrimoine', 'blurb' => 'Les collines sacrées et le grand pèlerinage marial d’Arigbo.', 'href' => home_url('/destination/dassa-zoume/'), 'slotId' => 'dc-dassa', 'thumbnail' => '' ),
                array('name' => 'Lac Ahémé & Possotomè', 'region' => 'Sud · Mono', 'cat' => 'Plages & lagunes', 'blurb' => 'Lagune paisible, sources thermales et villages de pêcheurs.', 'href' => home_url('/destination/lac-aheme-possotome/'), 'slotId' => 'dc-aheme', 'thumbnail' => '' ),
                array('name' => 'Parc national du W', 'region' => 'Nord · Alibori', 'cat' => 'Nature & faune', 'blurb' => 'Réserve transfrontalière classée UNESCO, sanctuaire de la grande faune.', 'href' => home_url('/destination/parc-national-du-w/'), 'slotId' => 'dc-parcw', 'thumbnail' => '' ),
                array('name' => 'Chutes de Tanougou', 'region' => 'Nord · Atacora', 'cat' => 'Nature & faune', 'blurb' => 'Cascade spectaculaire nichée dans les reliefs de l’Atacora.', 'href' => home_url('/destination/chutes-de-tanougou/'), 'slotId' => 'dc-tanougou', 'thumbnail' => '' ),
            );
        }
        ?>

        <style>
            .decouvrez-section-<?php echo esc_attr( $this->get_id() ); ?> #destinations-list-grid {
                display: grid;
                grid-template-columns: repeat(3, 1fr);
                gap: 28px;
            }
            @media (max-width: 991px) {
                .decouvrez-section-<?php echo esc_attr( $this->get_id() ); ?> {
                    padding: 48px 24px 60px !important;
                }
                .decouvrez-section-<?php echo esc_attr( $this->get_id() ); ?> #destinations-list-grid {
                    grid-template-columns: repeat(2, 1fr) !important;
                    gap: 20px !important;
                }
            }
            @media (max-width: 767px) {
                .decouvrez-section-<?php echo esc_attr( $this->get_id() ); ?> #destinations-list-grid {
                    grid-template-columns: 1fr !important;
                }
            }
        </style>

        <section class="decouvrez-section-<?php echo esc_attr( $this->get_id() ); ?>" style="max-width:1180px; margin:0 auto; padding:54px 56px 96px; font-family:'Sora',sans-serif; text-align: left;">
          <div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:38px; flex-wrap:wrap; gap:20px;">
            <div style="display:flex; gap:12px; flex-wrap:wrap;">
              <?php
              $cats = array('Tout', 'Nature & faune', 'Culture & patrimoine', 'Plages & lagunes', 'Villes');
              foreach ($cats as $index => $label) {
                  $active_style = $label === 'Tout'
                      ? 'background:linear-gradient(95deg,#FB9A02,#E8431E); color:#fff; box-shadow:0 8px 20px rgba(232,67,30,0.26);'
                      : 'background:#fff; color:#5D351C; border:1px solid #EFE2CE;';
                  echo sprintf(
                      '<div class="gb-chip filter-btn" data-filter="%s" style="font-weight:600; font-size:14px; padding:11px 20px; border-radius:30px; transition:all .22s; cursor:pointer; %s">%s</div>',
                      esc_attr($label),
                      $active_style,
                      esc_html($label)
                  );
              }
              ?>
            </div>
            <div id="dest-count-label" style="font-weight:500; font-size:14px; color:#9A8270;"><?php echo !empty($settings['count_text']) ? str_replace('[count]', count($all_destinations), esc_html( $settings['count_text'] )) : count($all_destinations) . ' destinations'; ?></div>

          </div>

          <div id="destinations-list-grid">
            <?php
            foreach ($all_destinations as $d) {
                $slot_img = !empty($d['thumbnail']) ? $d['thumbnail'] : ( ( !empty($d['slotId']) && function_exists('guide_benin_get_slot_image_src') ) ? guide_benin_get_slot_image_src($d['slotId']) : '' );
                $bg_style = !empty($slot_img) ? "background-image:url('{$slot_img}');" : "background-color:#3A2415;";

                ?>
                <a href="<?php echo esc_url($d['href']); ?>" class="destination-item gb-card" data-cat="<?php echo esc_attr($d['cat']); ?>" style="background:#fff; border-radius:20px; overflow:hidden; border:1px solid #EFE2CE; display:block;">
                  <div style="position:relative; height:240px; overflow:hidden; <?php echo $bg_style; ?> background-size:cover; background-position:center;">
                    <div style="position:absolute; top:16px; left:16px; display:inline-flex; align-items:center; gap:7px; background:rgba(26,11,5,0.78); backdrop-filter:blur(4px); color:#FBF7EF; font-weight:600; font-size:11px; letter-spacing:0.05em; text-transform:uppercase; padding:7px 13px; border-radius:20px;"><?php echo esc_html($d['cat']); ?></div>
                  </div>
                  <div style="padding:26px;">
                    <div style="display:flex; align-items:center; gap:7px; margin-bottom:9px;">
                      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#E8431E" stroke-width="2.2"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"></path><circle cx="12" cy="10" r="3"></circle></svg>
                      <span style="font-weight:600; font-size:12px; letter-spacing:0.06em; color:#E8431E; text-transform:uppercase;"><?php echo esc_html($d['region']); ?></span>
                    </div>
                    <div style="font-family:'Baloo 2',sans-serif; font-weight:700; font-size:24px; color:#241009; line-height:1.1; margin-bottom:10px;"><?php echo esc_html($d['name']); ?></div>
                    <div style="font-weight:400; font-size:14.5px; color:#6A4A38; line-height:1.6; margin-bottom:20px;"><?php echo esc_html($d['blurb']); ?></div>
                    <div class="gb-navlink" style="display:inline-flex; align-items:center; gap:8px; font-weight:600; font-size:14px; color:#5D351C;">Découvrir
                      <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#5D351C" stroke-width="2.2"><line x1="5" y1="12" x2="19" y2="12"></line><polyline points="12 5 19 12 12 19"></polyline></svg>
                    </div>
                  </div>
                </a>
                <?php
            }
            ?>
          </div>
        </section>
        <script>
        (function() {
            function initDecouvrezGrid() {
                const filterButtons = document.querySelectorAll('.filter-btn');
                const items = document.querySelectorAll('.destination-item');
                const countLabel = document.getElementById('dest-count-label');

                filterButtons.forEach(btn => {
                    btn.addEventListener('click', function() {
                        const filterValue = this.getAttribute('data-filter');

                        filterButtons.forEach(b => {
                            b.style.background = '#fff';
                            b.style.color = '#5D351C';
                            b.style.border = '1px solid #EFE2CE';
                            b.style.boxShadow = 'none';
                        });

                        this.style.background = 'linear-gradient(95deg,#FB9A02,#E8431E)';
                        this.style.color = '#fff';
                        this.style.border = 'none';
                        this.style.boxShadow = '0 8px 20px rgba(232,67,30,0.26)';

                        let visibleCount = 0;
                        items.forEach(item => {
                            const cat = item.getAttribute('data-cat');
                            if (filterValue === 'Tout' || cat === filterValue) {
                                item.style.display = 'block';
                                visibleCount++;
                            } else {
                                item.style.display = 'none';
                            }
                        });

                        if (countLabel) {
                            countLabel.textContent = visibleCount + (visibleCount > 1 ? ' destinations' : ' destination');
                        }
                    });
                });
            }
            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', initDecouvrezGrid);
            } else {
                initDecouvrezGrid();
            }
        })();
        </script>
        <?php
    }
}
