<?php

namespace Salesloo\Models;

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

use Salesloo\Abstracts\Database;

/**
 * Access Model
 */
class Access extends Database
{
    protected $table = 'salesloo_access';

    protected $columns = [
        'ID'       => 'integer',
        'order_id' => 'integer',
        'item_id'  => 'integer',
    ];

    protected $attributes = [];

    protected $meta = [];


    /**
     * get meta
     */
    public function meta($meta_key = false)
    {
        if (empty($this->meta) && false == $meta_key) {
            $get_all_meta = Access_Meta::query('WHERE access_id = %d', $this->ID)->paginate(1000)->get();
            $all_meta = [];

            if ($get_all_meta) {
                foreach ($get_all_meta as $key => $value) {
                    if (isset($all_meta[$value->meta_key])) {

                        if (is_array($all_meta[$value->meta_key])) {
                            $all_meta[$value->meta_key][] = \maybe_unserialize($value->meta_value);
                        } else {
                            $temp = array(
                                $all_meta[$value->meta_key],
                                \maybe_unserialize($value->meta_value)
                            );

                            unset($all_meta[$value->meta_key]);

                            $all_meta[$value->meta_key] = $temp;
                        }
                    } else {
                        $all_meta[$value->meta_key] = \maybe_unserialize($value->meta_value);
                    }
                }
            }

            $this->meta = $all_meta;
        }

        if ($meta_key) {
            $all_meta = Access_Meta::query('WHERE access_id = %d AND meta_key = %s', $this->ID, $meta_key)->paginate(1000)->get();

            $meta = [];
            if ($all_meta) {
                foreach ($all_meta as $key => $value) {
                    $meta[] = \maybe_unserialize($value->meta_value);
                }
            }
            return $meta;
        }

        return $this->meta;
    }
}
