<?php
namespace App\Models;

use CodeIgniter\Model;

class BlogDataModel extends Model
{
    protected $db;
    public $con_name = 'wrench_dockerblog';

    public function blogData($recLimit) {
        $this->db = \Config\Database::connect($this->con_name);
        $data = array();

        try {
            $mysql = "SELECT  id, post_title, post_content,post_date,comment_count FROM wp_posts WHERE post_type='post' AND post_status = 'publish' ORDER BY post_date DESC LIMIT 9";
            $mysql = "SELECT p1.id AS id,  p1.*, wm2.meta_value FROM  wp_posts p1 LEFT JOIN   wp_postmeta wm1
            ON (wm1.post_id = p1.id AND wm1.meta_value IS NOT NULL AND wm1.meta_key = '_thumbnail_id' )    
            LEFT JOIN 
            wp_postmeta wm2
            ON (wm1.meta_value = wm2.post_id AND wm2.meta_key = '_wp_attached_file' AND wm2.meta_value IS NOT NULL   )
            WHERE
            p1.post_status='publish'
            AND p1.post_type='post'
            ORDER BY p1.post_date DESC LIMIT $recLimit";

            $query = $this->db->query($mysql);

            $data['payload']['blogdata'] = $query->getResult('array');
            $totalCount = count( $data['payload']['blogdata'] );

            $randomIndex =  rand(1, $totalCount);

            $data['payload']['featured']  =  $data['payload']['blogdata'][$randomIndex];
            $data['payload']['image_url'] = 'https://blog.wrenchboard.com/wp-content/uploads/';
            $data['payload']['blog_url']  = 'https://blog.wrenchboard.com/';
            $data['payload']['total'] = $totalCount;
        } catch (Exception $ex) {

        }

        return $data;
    }

}

