<?php if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}


class Page_model extends MY_Model
{

    public function __construct()
    {
        parent::__construct();
    }

    private static function init()
    {
        return get_instance()->db->from('cm_page_attributes')
            ->join('cm_page_content', 'cm_page_content.pageID = cm_page_attributes.pageID')
            ->join('cm_page_meta', 'cm_page_meta.pageID = cm_page_attributes.pageID')
            ->where("pagePublished", 1);
    }

    public function getOne($pageUrl)
    {
        $pageUrl = is_array($pageUrl) ? $pageUrl : [$pageUrl];
        return self::init()->where_in("cm_page_content.pageID", $pageUrl)->get()->row();
    }

    public function getPageDelivery($pageID)
    {
        $this->db->join('cm_page_attributes', 'cm_page_attributes.pageID=cm_delivery.pageID');
        return $this->db->where('cm_page_attributes.pageID', $pageID)->get('cm_delivery')->result();
    }

    public function getTablePageTitle(&$rows)
    {
        if (count($rows)) {
            $pages = get_instance()->db
                ->join('cm_post_page', 'cm_page_content.pageID=cm_post_page.pageID', 'left')
                ->where_in('cm_post_page.postID', array_column($rows, 'postID'))->get('cm_page_content')->result();
            foreach ($rows as $k => $row) {
                $rows[$k]['pages'] = [];
                foreach ($pages as $r) {
                    if ($row['postID'] == $r->postID) {
                        $rows[$k]['pages'][] = $r->pageID;
                        $rows[$k]['pageTitle'] = (empty($rows[$k]['pageTitle']) ? '' : $rows[$k]['pageTitle'] . ', ') . $r->pageTitle;
                    }
                }
            }
        }
    }
}
