<?php

/**
 *  Main conferencia class to handle all functions for conferencias 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 Conferencia{
    
    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_list( $year, $month, $last_update, $text, $locale, $termid="ultimas" ){ //Default last updated
        //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,";
        if($text){
            $sql .= "P.post_content as content,";
        }
        $sql .= "LENGTH(P.post_content) as bodylength,
                O.option_value AS translationmeta
                FROM ".$prefix."posts P
                LEFT JOIN ".$prefix."options O ON O.option_name = CONCAT('msls_',P.ID)";
        if($year == '' && $month == ''){
        $sql .= "
                INNER JOIN ".$prefix."term_relationships AS tr ON (P.ID = tr.object_id)
                INNER JOIN ".$prefix."terms AS t ON (t.term_id = tr.term_taxonomy_id)";
        }
        $sql .= "
                WHERE P.post_type = 'conferencias'
                AND P.post_status = 'publish'";
                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 .= " AND t.slug = '$termid'";
                    $sql .= " ORDER BY P.post_modified DESC";
                    $sql .= " LIMIT 16";
                }
        return $this->execute_sql( $sql );
    }

    function conference_meta($id){
        $sql = "SELECT 
                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
                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 = 'conferencias'
                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 list( $year, $month, $last_update, $text, $locale ){
        $sql = "SELECT  
                P.ID,   
                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 = 'conferencias'
                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 );
    }

    /**
     *  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){
        //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_content AS content,
                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.ID = '$id'";
        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,
                P.post_title AS title,
                P.post_content AS content,
                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_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_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_post_files($id,$locale){
        //Check locale and change accordingly to the right DB prefix for that locale
        $prefix = $this->get_blog_by_locale( $locale );
        
        $sql = "SELECT
                MF.youtube,
                MF.video,
                MF.audio,
                MF.pdf,
                MF.pdf_simple,
                MF.videofile,
                MF.audiofile,
                MF.pdffile,
                MF.pdfsimplefile
                FROM ".$prefix."messagefiles as MF
                WHERE MF.post_id = '$id'";
        return $this->execute_sql( $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 = 'conferencias'
                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 = 'conferencias'
                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` = 'conferencias'
        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 = 'conferencias'
                AND P.post_status = 'publish'
                AND MD.country = '$c'
                ORDER BY MD.date DESC";
        return $this->execute_sql($sql);
    }

    function year_list(){
        $sql = "SELECT
                count(ID) as total,
                YEAR(post_date) as year,
                MONTH(post_date) as month
                FROM wp_posts
                WHERE `post_status` = 'publish'
                AND `post_type` = 'conferencias'
                GROUP BY YEAR(post_date), MONTH(post_date)
                ORDER BY YEAR(post_date) DESC, MONTH(post_date) DESC;";
        return $this->execute_sql($sql);
    }
}