<?php

namespace Salesloo\Models;

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

use Salesloo\Abstracts\Database;
use Salesloo\Models\Coupon_Code;

/**
 * Product Model
 */
class Coupon extends Database
{
    protected $table = 'salesloo_coupon';

    protected $columns = [
        'ID'           => 'integer',
        'title'        => 'string',
        'description'  => 'content',
        'rebate'       => 'string',
        'active_start' => 'string',
        'active_end'   => 'string',
        'is_private'   => 'integer',
        'max_usage'    => 'integer',
        'products'     => 'array',
        'users'        => 'array',
        'status'       => 'string',
        'created_at'   => 'string',
        'updated_at'   => 'string'
    ];

    protected $attributes = [];

    protected $codes;

    /**
     * get_raw_rebate
     *
     * @return array
     */
    public function get_raw_rebate()
    {
        $rebate_array = [];

        if (strpos($this->rebate, '%')) {
            $rebate = str_replace('%', '', $this->rebate);

            $rebate_array = [
                'type' => 'percen',
                'value' => intval($rebate)
            ];
        } else {
            $rebate_array = [
                'type' => 'fixed',
                'value' => intval($this->rebate)
            ];
        }

        return $rebate_array;
    }

    /**
     * codes
     *
     * @return mixed
     */
    public function codes()
    {
        if (empty($this->codes)) {
            $this->codes = Coupon_Code::query('WHERE coupon_id = %d', $this->ID)->get();
        }

        return $this->codes;
    }
}
