<?php

/**
 *  Main actividad class to handle all functions for actividades interaction for the API.
 * 
 *  This class uses the db.php files connection in PDO style and only returns SQL statements.
 * 
 *  @author XFATBoY (xfatboy@carpa.com)
 *  @since v1
 */
class Actividad{
    
    private $conn;
    private $table_name = "wp_posts";
 
    public $id;
    public $name;
    public $description;
    public $price;
    public $category_id;
    public $category_name;
    public $created;
 
    /**
     *  Main constructor
     *  
     *  Initializes with the db
     */
    public function __construct($db){
        $this->conn = $db;
    }

    /**
     *  Helper function to get all blogs and their languages
     */
    function get_blog_by_locale($locale){
        $r = '';
        switch($locale){
            case "fr_FR":
            case "fr":
                $r = "wp_4_";
                break;
            case "en":
            case "en_US":
                $r = "wp_2_";
                break;
            case "pt":
            case "pt-br":
            case "pt_br":
            case "pt_BR":    
                $r = "wp_3_";
                break;
            case "es":
            case "es_ES":
            default:
                $r = "wp_";
                break;
        }
        return $r;
    }

    function translation_slug( $locale, $id ){
        $sql = "SELECT
                P.post_name as slug
                FROM wp_posts P
                WHERE P.ID = $id";
        return $this->execute_sql( $sql );     
    }

    
    function translation_list( $year, $month, $last_update, $text, $locale, $termid="ultimas", $all=false, $history=false, $limit=16, $from='' ){ //Default last updated
        //Check locale and change accordingly to the right DB prefix for that locale
        $sql = "SELECT
        P.ID,
        (SELECT
        tt2.description AS translationmeta
        FROM wp_posts P2
        LEFT JOIN wp_term_relationships tr ON tr.object_id = P2.ID
        LEFT JOIN wp_term_relationships tr2 ON tr2.object_id = P2.ID
        LEFT JOIN wp_term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id AND tt.taxonomy = 'language'
        INNER JOIN wp_term_taxonomy tt2 ON tr2.term_taxonomy_id = tt2.term_taxonomy_id AND tt2.taxonomy = 'post_translations'
        LEFT JOIN wp_terms t ON t.term_id = tr.term_taxonomy_id
        WHERE P2.ID=P.ID AND t.slug = '$locale') AS translationmeta,
        P.post_title AS title,
        P.post_date AS date,
        P.post_modified AS modified,
        P.post_name AS slug,
        WEEKDAY(P.post_date) AS dia,
        PMM.meta_value AS mensaje_id,
        PMA.meta_value AS mensaje_json
        FROM wp_posts P
        LEFT JOIN wp_postmeta PMA ON PMA.post_id = P.ID AND PMA.meta_key = 'mensaje_json'
        LEFT JOIN wp_postmeta PMM ON PMM.post_id = P.ID AND PMM.meta_key = 'mensaje'
        INNER JOIN wp_terms T ON T.slug = '$locale'
        INNER JOIN wp_term_relationships TR ON TR.object_id = P.ID AND TR.term_taxonomy_id = T.term_id
        WHERE P.post_status = 'publish'
        AND P.post_type = 'actividades'";
                if($history){
                    $sql .= "
                    AND PMM.meta_value IS NOT NULL
                    AND PMM.meta_value != ''
                    AND PMA.meta_value IS NOT NULL
                    AND PMA.meta_value != ''";
                }

                if($from != ''){
                    $sql .= " AND P.post_date >= '$from'";
                }

                if($year!=''){
                    $sql .= " AND YEAR(P.post_date) = '$year'";
                    if($month!=''){
                        $sql .= " AND MONTH(P.post_date) = '$month'";
                    }
                    if($last_update!=''){
                        $sql .= " AND UNIX_TIMESTAMP(P.post_modified) > ". $last_update;
                    }
                    $sql .= " ORDER BY P.post_date DESC";
                } else {
                    $sql .= " ORDER BY P.post_date DESC";
                    if(!$all){
                if(!$limit){
                                    $sql .= " LIMIT 16";
                } else {
                $sql .= " LIMIT " . $limit;
                }
                    }
                }
        return $this->execute_sql( $sql );
    }

    function activity_meta($id){
        $sql = "SELECT 
PML.meta_value AS lugar,
                PMC.meta_value AS city,
                PMS.meta_value AS state,
                PMCO.meta_value AS country,
                PMT2.meta_value AS thumbnail,
                PMN.meta_value AS numero_de_estudio_biblico,
                PMA.meta_value AS actividad,
                PMG.meta_value AS gallery,
                PMY.meta_value AS youtube,
                #PMU.meta_value AS url_del_mensaje,
                PMI.meta_value AS mensaje,
                PMJ.meta_value AS mensaje_json,
                PMR.meta_value AS 'related_content',
                PMRC.meta_value AS 'related_content_count',
                PMCK.meta_value AS 'revisado'
                FROM wp_posts P
LEFT JOIN wp_postmeta PML ON P.ID = PML.post_id AND PML.meta_key = 'lugar'
                LEFT JOIN wp_postmeta PMC ON P.ID = PMC.post_id AND PMC.meta_key = 'city'
                LEFT JOIN wp_postmeta PMS ON P.ID = PMS.post_id AND PMS.meta_key = 'state'
                LEFT JOIN wp_postmeta PMCO ON P.ID = PMCO.post_id AND PMCO.meta_key = 'country'
                LEFT JOIN wp_postmeta PMA ON P.ID = PMA.post_id AND PMA.meta_key = 'actividad'
                LEFT JOIN wp_postmeta PMN ON P.ID = PMN.post_id AND PMN.meta_key = 'numero_de_estudio_biblico'
                LEFT JOIN wp_postmeta PMG ON P.ID = PMG.post_id AND PMG.meta_key = 'gallery'
                LEFT JOIN wp_postmeta PMY ON P.ID = PMY.post_id AND PMY.meta_key = 'youtube'
                #LEFT JOIN wp_postmeta PMU ON P.ID = PMU.post_id AND PMU.meta_key = 'url_del_mensaje'
                LEFT JOIN wp_postmeta PMI ON P.ID = PMI.post_id AND PMI.meta_key = 'mensaje'
                LEFT JOIN wp_postmeta PMJ ON P.ID = PMJ.post_id AND PMJ.meta_key = 'mensaje_json'
                LEFT JOIN wp_postmeta PMT ON P.ID = PMT.post_id AND PMT.meta_key = '_thumbnail_id'
                LEFT JOIN wp_postmeta PMT2 ON PMT.meta_value = PMT2.post_id AND PMT2.meta_key = '_wp_attached_file'
                LEFT JOIN wp_postmeta PMR ON P.ID = PMR.post_id AND PMR.meta_key = 'usar_contenido_relacionado'
                LEFT JOIN wp_postmeta PMRC ON P.ID = PMRC.post_id AND PMRC.meta_key = 'contenido_relacionado'
                LEFT JOIN wp_postmeta PMCK ON P.ID = PMCK.post_id AND PMCK.meta_key = 'revisado'
                WHERE P.post_type = 'actividades'
                AND P.post_status = 'publish'
                AND P.ID = ".$id;
        $data = $this->execute_sql( $sql );
        $response = $data->fetch(PDO::FETCH_ASSOC);
        return $response;
    }

    /**
     *  List function
     * 
     *  Displays the list of messages with it's pertinent variables
     * 
     */
    function activities_list( $year, $month, $last_update, $text, $locale ){
        $sql = "SELECT  
                P.ID,
                (SELECT
					 tt2.description AS translationmeta
					 FROM wp_posts P2
					 LEFT JOIN wp_term_relationships tr ON tr.object_id = P2.ID
                LEFT JOIN wp_term_relationships tr2 ON tr2.object_id = P2.ID
                LEFT JOIN wp_term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id AND tt.taxonomy = 'language'
                INNER JOIN wp_term_taxonomy tt2 ON tr2.term_taxonomy_id = tt2.term_taxonomy_id AND tt2.taxonomy = 'post_translations'
                LEFT JOIN wp_terms t ON t.term_id = tr.term_taxonomy_id
					 WHERE P2.ID='$id' AND t.slug = '$locale') AS translationmeta,   
                P.post_title AS title,
                P.post_date AS creation_date, 
                P.post_modified as last_updated,";
        if($text){
            $sql .= "P.post_content as content,";
        }
        $sql .= "LENGTH(P.post_content) as bodylength,
                IFNULL(NULLIF(TIME_TO_SEC(MD.duration), '' ), 0) AS duration,
                MD.date,
                MD.activity AS no_activity,
                MD.city,
                MD.country, 
                MD.state, 
                PMA.meta_value AS thumbnail,
                PMAS.meta_value AS meta,
                #O.option_value AS translationmeta,
                P.post_name as slug
                FROM wp_posts P
                LEFT JOIN wp_messagedata MD ON P.id = MD.post_id
                LEFT JOIN wp_postmeta PM ON PM.post_id =  P.ID AND PM.meta_key = '_thumbnail_id'
                LEFT JOIN wp_postmeta PMA ON PM.meta_value = PMA.post_id AND PMA.meta_key = '_wp_attached_file'
                LEFT JOIN wp_postmeta PMAS ON PM.meta_value = PMAS.post_id AND PMAS.meta_key = '_wp_attachment_metadata'
                #LEFT JOIN wp_options O ON O.option_name = CONCAT('msls_',P.ID)
                WHERE P.post_type = 'actividades'
                AND P.post_status = 'publish'";
                if($year!=''){
                    $sql .= " AND YEAR(MD.date) = '$year'";
                }
                if($month!=''){
                    $sql .= " AND MONTH(MD.date) = '$month'";
                }
                if($last_update!=''){
                    $sql .= " AND UNIX_TIMESTAMP(P.post_modified) > ". $last_update;
                }
                $sql .= " ORDER BY P.post_date DESC";
        return $this->execute_sql( $sql );
    }

     /**
     *  Summary function
     */
    function activity_summary($id,$locale){
        
        $sql = "SELECT
        P.ID,
        P.post_title AS title,
        P.post_date AS creation_date,
        P.post_name AS slug,
        P.post_modified AS last_updated,
        PMA.meta_value AS activity,
        PML.meta_value AS lugar,
        PMC.meta_value AS city,
        PMS.meta_value AS state,
        PMCO.meta_value AS country,
        PMN.meta_value AS bible_study,
        CASE
            WHEN PMT.meta_value IS NOT NULL AND PMT.meta_value <> '' THEN 1 -- Or 'True'
            ELSE 0 -- Or 'False'
        END AS has_text
        FROM wp_posts P
        LEFT JOIN wp_postmeta PMA ON PMA.post_id = P.ID AND PMA.meta_key = 'actividad'
        LEFT JOIN wp_postmeta PML ON PML.post_id = P.ID AND PML.meta_key = 'lugar'
        LEFT JOIN wp_postmeta PMC ON PMC.post_id = P.ID AND PMC.meta_key = 'city'
        LEFT JOIN wp_postmeta PMS ON PMS.post_id = P.ID AND PMS.meta_key = 'state'
        LEFT JOIN wp_postmeta PMCO ON PMCO.post_id = P.ID AND PMCO.meta_key = 'country'
        LEFT JOIN wp_postmeta PMN ON PMN.post_id = P.ID AND PMN.meta_key = 'numero_de_estudio_biblico'
        LEFT JOIN wp_postmeta PMT ON PMT.post_id = P.ID AND PMT.meta_key = 'intervenciones_0_texto'
        WHERE P.ID = $id
        AND P.post_status = 'publish'
        AND P.post_type = 'actividades'";
        return $this->execute_sql( $sql );
    }


    /**
     *  Summary function
     */
    function summary($id,$locale){
        
        $sql = "SELECT
        P.ID,
        P.post_title AS title,
        P.post_date AS creation_date,
        P.post_name AS slug,
        P.post_modified AS last_updated,
        PMA.meta_value AS activity,
        PML.meta_value AS lugar,
        PMC.meta_value AS city,
        PMS.meta_value AS state,
        PMCO.meta_value AS country,
        PMN.meta_value AS bible_study
        FROM wp_posts P
        LEFT JOIN wp_postmeta PMA ON PMA.post_id = P.ID AND PMA.meta_key = 'actividad'
        LEFT JOIN wp_postmeta PML ON PML.post_id = P.ID AND PML.meta_key = 'lugar'
        LEFT JOIN wp_postmeta PMC ON PMC.post_id = P.ID AND PMC.meta_key = 'city'
        LEFT JOIN wp_postmeta PMS ON PMS.post_id = P.ID AND PMS.meta_key = 'state'
        LEFT JOIN wp_postmeta PMCO ON PMCO.post_id = P.ID AND PMCO.meta_key = 'country'
        LEFT JOIN wp_postmeta PMN ON PMN.post_id = P.ID AND PMN.meta_key = 'numero_de_estudio_biblico'
        LEFT JOIN wp_postmeta PMPID ON PMPID.meta_key = 'mensaje' AND PMPID.meta_value = $id 
        WHERE P.ID = PMPID.post_id
        AND P.post_status = 'publish'
        AND P.post_type = 'actividades'";
        return $this->execute_sql( $sql );
    }


    /**
     *  Detail function
     * 
     *  Given an ID returns the message with all details
     *  
     *  @param  id  Int id of the message whose details want to be found.
     */
    function detail($id,$locale){
        
        $sql = "SELECT
                P.ID,
                (SELECT
					 tt2.description AS translationmeta
					 FROM wp_posts P2
					 LEFT JOIN wp_term_relationships tr ON tr.object_id = P2.ID
                LEFT JOIN wp_term_relationships tr2 ON tr2.object_id = P2.ID
                LEFT JOIN wp_term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id AND tt.taxonomy = 'language'
                INNER JOIN wp_term_taxonomy tt2 ON tr2.term_taxonomy_id = tt2.term_taxonomy_id AND tt2.taxonomy = 'post_translations'
                LEFT JOIN wp_terms t ON t.term_id = tr.term_taxonomy_id
					 WHERE P2.ID='$id' AND t.slug = '$locale') AS translationmeta,
                P.post_title AS title,
                P.post_content AS content,
                P.post_date AS creation_date,
                PMA.meta_value AS mensaje,
                P.post_name AS slug,
                P.post_modified AS last_updated
                FROM wp_posts P
                LEFT JOIN wp_postmeta PMA ON PMA.post_id = P.ID AND PMA.meta_key = 'mensaje'
                WHERE P.ID = '$id' LIMIT 1";
        return $this->execute_sql( $sql );
    }

    /**
     *  Slug function
     * 
     *  Given a slug, returns the message with all details
     * 
     *  @param slug String  Slug of the message whose details want to be found
     */
    function detailBySlug($slug,$locale){
        //Check locale and change accordingly to the right DB prefix for that locale
        $prefix = $this->get_blog_by_locale( $locale );
        
        $sql = "SELECT
                P.ID,
                (SELECT
					 tt2.description AS translationmeta
					 FROM wp_posts P2
					 LEFT JOIN wp_term_relationships tr ON tr.object_id = P2.ID
                LEFT JOIN wp_term_relationships tr2 ON tr2.object_id = P2.ID
                LEFT JOIN wp_term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id AND tt.taxonomy = 'language'
                INNER JOIN wp_term_taxonomy tt2 ON tr2.term_taxonomy_id = tt2.term_taxonomy_id AND tt2.taxonomy = 'post_translations'
                LEFT JOIN wp_terms t ON t.term_id = tr.term_taxonomy_id
					 WHERE P2.post_name='$slug' AND t.slug = '$locale') AS translationmeta,
                P.post_title AS title,
                P.post_content AS content,
                P.post_date AS creation_date,
                P.post_name AS slug,
                PMA.meta_value AS mensaje,
                P.post_modified AS last_updated
                FROM wp_posts P
                LEFT JOIN wp_postmeta PMA ON PMA.post_id = P.ID AND PMA.meta_key = 'mensaje'
                WHERE P.post_name='$slug'";
        return $this->execute_sql( $sql );
    }
    
    /**
     *  Last update function
     * 
     *  Returns the last updated imtestamp for the message passed in via the @id
     * 
     *  @param  id  Int id for whom the last update should be found
     */
    function last_update($id){
        $sql = "SELECT
                P.post_modified AS last_updated
                FROM wp_posts P
                WHERE P.ID = '$id'";
        return $this->execute_sql( $sql );
    }

    /**
     *  Execute SQL function
     * 
     *  Executes a generic SQL statement and passes back the result.
     * 
     *  @param  string sql SQl statement to be executed
     *  @return 
     */
    function execute_sql( $sql ){
        $stmt = $this->conn->prepare($sql);
        $stmt->execute();
        return $stmt;
    }

    /**
     *  Relevant conferences function
     * 
     *  Get all relevant conferences and return
     */
    function relevant_conferences(){
        $sql = "SELECT
                option_value
                FROM wp_options
                where option_name = 'options_conference'";
        return $this->execute_sql( $sql );
    }

    function get_post_source($trid){
        $sql = "SELECT
            T.element_id AS post_id
            FROM wp_icl_translations AS T
            WHERE T.trid = '$trid'
            AND T.language_code = 'es'";
        return $this->execute_sql( $sql );
    }

    function get_post_interventions($id){
        $sql = "SELECT
        PM.meta_value
        FROM wp_postmeta AS PM
        WHERE PM.post_id = '$id'
        AND PM.meta_key = 'intervenciones'";
        return $this->execute_sql( $sql );
    }

    function get_interventions($id,$count){
        $interventions = [];

        for($i=0;$i<$count;$i++){
            $sql = "SELECT
            PMT.meta_value AS titulo,
            PMF.meta_value AS fecha,
            PML.meta_value AS lugar,
            PMA.meta_value AS autor,
            PMC.meta_value AS texto
            FROM wp_postmeta AS PMT
            LEFT JOIN wp_postmeta AS PMF ON PMF.post_id = '$id' AND PMF.meta_key = 'intervenciones_".$i."_fecha'
            LEFT JOIN wp_postmeta AS PML ON PML.post_id = '$id' AND PML.meta_key = 'intervenciones_".$i."_lugar'
            LEFT JOIN wp_postmeta AS PMA ON PMA.post_id = '$id' AND PMA.meta_key = 'intervenciones_".$i."_autor'
            LEFT JOIN wp_postmeta AS PMC ON PMC.post_id = '$id' AND PMC.meta_key = 'intervenciones_".$i."_texto'
            WHERE PMT.post_id = '$id'
            AND PMT.meta_key = 'intervenciones_".$i."_titulo' ";
            $data = $this->execute_sql( $sql );
            $response = $data->fetch(PDO::FETCH_ASSOC);
            //$interventions[$count] = $response;
            array_push($interventions,$response);
        }

        return $interventions;
    }

    function get_related_content($id,$count){
        $related = [];

        for($i=0;$i<$count;$i++){
            $sql = "SELECT
            PM.meta_value AS conference_url
            FROM wp_postmeta AS PM
            WHERE PM.post_id = '$id'
            AND PM.meta_key = 'contenido_relacionado_".$i."_conference_url'";
            $data = $this->execute_sql( $sql );
            $response = $data->fetch(PDO::FETCH_ASSOC);
            array_push($related,$response);
        }

        return $related;
    }
    
    function get_post_language($id){
        $sql = "SELECT
        T.language_code,
        T.trid
        FROM wp_icl_translations AS T
        WHERE T.element_id = '$id'
        AND T.element_type = 'post_message'";
        return $this->execute_sql( $sql );
    }
    
    function get_post_metadata($id){
        $sql = "SELECT
                IFNULL(NULLIF(TIME_TO_SEC(MD.duration), '' ), 0) AS duration,
                MD.country, 
                MD.state, 
                MD.city AS city,
                MD.activity AS no_activity
                FROM wp_messagedata AS MD
                WHERE post_id = '$id'";
        return $this->execute_sql( $sql );
    }
    
    function get_activity_files($id){
        $sql = "SELECT
                PMAR.meta_value AS use_files,
                PMNV.meta_value AS videos,
                PMNA.meta_value AS audios,
                PMNT.meta_value AS textos,
                PMNE.meta_value AS enlaces
                FROM wp_posts P
                LEFT JOIN wp_postmeta PMAR ON P.ID = PMAR.post_id AND PMAR.meta_key = 'usar_archivos'
                LEFT JOIN wp_postmeta PMNV ON P.ID = PMNV.post_id AND PMNV.meta_key = 'videos'
                LEFT JOIN wp_postmeta PMNA ON P.ID = PMNA.post_id AND PMNA.meta_key = 'audios'
                LEFT JOIN wp_postmeta PMNT ON P.ID = PMNT.post_id AND PMNT.meta_key = 'textos'
                LEFT JOIN wp_postmeta PMNE ON P.ID = PMNE.post_id AND PMNE.meta_key = 'enlaces'
                WHERE P.post_type = 'actividades'
                AND P.post_status = 'publish'
                AND P.ID = ".$id;
        return $this->execute_sql( $sql );
    }

    function get_files( $id, $type, $qty ){
        $t = [];
        for($x=0;$x<$qty;$x++){
            $fileSql = $this->get_file_sql($id, $type, $x);
            $data = $this->execute_sql( $fileSql );
            $response = $data->fetch(PDO::FETCH_ASSOC);
            array_push( $t, $response );
        }
        return $t;
    }

    function get_file_sql( $id, $type, $idx){
        if($type == 'enlaces'){
            $fname = 'enlace';
        } else {
            $fname = 'archivo';
        }
        $sql = "SELECT
        PMAT.meta_value as title,
        PMAD.meta_value as description,
        PMAF.meta_value as link,
        PF.guid AS file
        FROM wp_posts P
        LEFT JOIN wp_postmeta PMAT ON PMAT.post_id = P.ID AND PMAT.meta_key = '".$type."_".$idx."_titulo'
        LEFT JOIN wp_postmeta PMAD ON PMAD.post_id = P.ID AND PMAD.meta_key = '".$type."_".$idx."_descripcion'
        LEFT JOIN wp_postmeta PMAF ON PMAF.post_id = P.ID AND PMAF.meta_key	= '".$type."_".$idx."_".$fname."'
        LEFT JOIN wp_posts PF ON PF.ID = PMAF.meta_value
        WHERE P.ID = $id";
        return $sql;
    }

    function get_post_file($id,$locale){
        //Check locale and change accordingly to the right DB prefix for that locale
        $prefix = $this->get_blog_by_locale( $locale );
        
        $sql = "SELECT
                P.guid as url
                FROM ".$prefix."posts P
                WHERE P.ID = '$id'";
        return $this->execute_sql( $sql );
    }

    function title_search($q,$locale){
        //Check locale and change accordingly to the right DB prefix for that locale
        $prefix = $this->get_blog_by_locale( $locale );
        
        $sql = "SELECT  
                P.ID,   
                P.post_title AS title,
                P.post_date AS creation_date, 
                P.post_modified as last_updated,
                O.option_value AS translationmeta,
                P.post_name as slug
                FROM ".$prefix."posts AS P
                LEFT JOIN ".$prefix."options O ON O.option_name = CONCAT('msls_',P.ID)
                WHERE P.post_type = 'actividades'
                AND P.post_status = 'publish'
                AND P.post_title LIKE('%$q%')";
       return $this->execute_sql($sql);
            
    }

    function content_search($q){
        $sql = "SELECT  
                P.ID,   
                P.post_title AS title,
                P.post_date AS creation_date, 
                P.post_modified as last_updated,
                IFNULL(NULLIF(TIME_TO_SEC(MD.duration), '' ), 0) AS duration,
                MD.date,
                MD.activity AS no_activity,
                MD.city,
                MD.country, 
                MD.state, 
                PMA.meta_value AS thumbnail,
                P.post_name as slug,
                MATCH(P.post_content) AGAINST ('$q' IN NATURAL LANGUAGE MODE) as score,
                SUBSTRING(P.post_content, LOCATE('$q', P.post_content) - 20, 300 + LENGTH('$q') + 300) as excerpt
                FROM wp_posts P
                LEFT JOIN wp_messagedata MD ON P.id = MD.post_id
                LEFT JOIN wp_postmeta PM ON PM.post_id =  P.ID AND PM.meta_key = '_thumbnail_id'
                LEFT JOIN wp_postmeta PMA ON PM.meta_value = PMA.post_id AND PMA.meta_key = '_wp_attached_file'
                WHERE P.post_type = 'actividades'
                AND P.post_status = 'publish'
                AND MATCH(P.post_content) AGAINST ('$q' IN NATURAL LANGUAGE MODE)
                ORDER BY score DESC";
        return $this->execute_sql($sql);
    }

    function country_summary(){
        $sql = "SELECT
        count( P.ID ) as total,
        MC.country_name as country,
        MC.country_code as country_code
        FROM `wp_posts` P
        INNER JOIN wp_messagedata MD ON MD.post_id = P.ID
        INNER JOIN wp_messagecountries MC ON MC.country_code = MD.country
        WHERE `post_status` = 'publish'
        AND `post_type` = 'actividades'
        AND MC.language_code = 'es'
        GROUP BY country_code
        ORDER BY country;";
        return $this->execute_sql($sql);
    }

    function country_list($c){
        $sql = "SELECT  
                P.ID,   
                P.post_title AS title,
                P.post_date AS creation_date, 
                P.post_modified as last_updated,
                LENGTH(P.post_content) as bodylength,
                IFNULL(NULLIF(TIME_TO_SEC(MD.duration), '' ), 0) AS duration,
                MD.date,
                MD.activity AS no_activity,
                MD.city,
                MD.country, 
                MD.state, 
                PMA.meta_value AS thumbnail,
                P.post_name as slug
                FROM wp_posts P
                LEFT JOIN wp_messagedata MD ON P.id = MD.post_id
                LEFT JOIN wp_postmeta PM ON PM.post_id =  P.ID AND PM.meta_key = '_thumbnail_id'
                LEFT JOIN wp_postmeta PMA ON PM.meta_value = PMA.post_id AND PMA.meta_key = '_wp_attached_file'
                WHERE P.post_type = 'actividades'
                AND P.post_status = 'publish'
                AND MD.country = '$c'
                ORDER BY MD.date DESC";
        return $this->execute_sql($sql);
    }

    function year_list( $locale ){
        $sql = "SELECT
        COUNT(P.ID) as total,
        YEAR(P.post_date) as year,
        MONTH(P.post_date) as month
        FROM wp_posts P
        INNER JOIN wp_terms T ON T.slug = '$locale'
        INNER JOIN wp_term_relationships TR ON TR.object_id = P.ID AND TR.term_taxonomy_id = T.term_id
        WHERE P.post_type = 'actividades' AND P.post_status = 'publish'
        GROUP BY YEAR(P.post_date), MONTH(P.post_date)
        ORDER BY YEAR(P.post_date) DESC, MONTH(P.post_date) DESC;";
        return $this->execute_sql($sql);
    }

    function year_list_history( $locale ){
        $sql = "SELECT
        COUNT(P.ID) as total,
        YEAR(P.post_date) as year,
        MONTH(P.post_date) as month
        FROM wp_posts P
        LEFT JOIN wp_postmeta PM ON PM.post_id = P.ID AND PM.meta_key = 'mensaje_json'
        INNER JOIN wp_terms T ON T.slug = 'es'
        INNER JOIN wp_term_relationships TR ON TR.object_id = P.ID AND TR.term_taxonomy_id = T.term_id
        WHERE P.post_type = 'actividades'
		  AND P.post_status = 'publish'
        AND PM.meta_value IS NOT NULL
		  AND PM.meta_value != ''
        GROUP BY YEAR(P.post_date), MONTH(P.post_date)
        ORDER BY YEAR(P.post_date) DESC, MONTH(P.post_date) DESC;";
        return $this->execute_sql($sql);
    }

    function lgccctv_list( $locale ){
        //Check locale and change accordingly to the right DB prefix for that locale
        $prefix = $this->get_blog_by_locale( $locale );
        
        $sql = "SELECT  
                P.ID,   
                P.post_title AS title,
                P.post_date AS creation_date, 
                P.post_modified as last_updated,
                P.post_name as slug,
                O.option_value AS translationmeta
                FROM ".$prefix."posts P
                LEFT JOIN ".$prefix."options O ON O.option_name = CONCAT('msls_',P.ID)
                WHERE P.post_type = 'actividades'
                AND P.post_status = 'publish'";
                
        return $this->execute_sql( $sql );
    }
}