<?php

namespace Salesloo\Models;

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

use Salesloo\Abstracts\Database;

/**
 * Checkout Model
 */
class Checkout extends Database
{
    protected $table = 'salesloo_checkout';

    protected $columns = [
        'ID'         => 'integer',
        'user'       => 'string',
        'created_at' => 'string',
        'updated_at' => 'string'
    ];

    protected $attributes = [];

    protected $meta = [];

    /**
     * get meta
     */
    public function meta($meta_key = false)
    {
        if (empty($this->meta)) {
            $get_all_meta = Checkout_Meta::query('WHERE checkout_id = %d', $this->ID)->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) {
            return isset($this->meta[$meta_key]) ? $this->meta[$meta_key] : false;
        }

        return $this->meta;
    }
}
