<?php

namespace Mnv\Models;

use Mnv\Core\Model;
use Mnv\Http\Request;

/**
 * Class OrderStatus
 * @package Mnv\Models
 */
class OrderStatus extends Model
{
    /** @var string */
    protected string $table = 'shop_order_status';

    /** @var string  */
    protected string $primaryKey = 'order_status_id';

    protected string $orderBy = 'order_status_id ASC';

    public $statuses;

    public function __construct(Request $request)
    {
        $this->statuses = $request->get('statuses');
    }


    public function prepare(): bool
    {
        $oldStatuses = connect($this->table)->indexKey('order_status_id')->getAllIndexes('array');
        foreach ($this->statuses as $status) {
            if (!empty($status['order_status_id']) && $oldStatuses[$status['order_status_id']]['order_status_id'] == $status['order_status_id']) {
                connect($this->table)->where($this->primaryKey, $status['order_status_id'])->update(['name' => $status['name']]);
                unset($oldStatuses[$status['order_status_id']]);
            } else {
                connect($this->table)->insert(['name' => $status['name']]);
            }
        }

        foreach ($oldStatuses as $oldStatus) {
            connect($this->table)->where($this->primaryKey, $oldStatus['order_status_id'])->delete();
        }

        return true;
    }


}