<?php
declare(strict_types=1);

namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\Validation\Validator;

class ProductsTable extends Table
{
    public function initialize(array $config): void
    {
        parent::initialize($config);

        // table + PK
        $this->setTable('products');
        $this->setDisplayField('name');
        $this->setPrimaryKey('id');

        // created/modified
        $this->addBehavior('Timestamp');

        // Only set column types if the column exists in the DB.
        // (Prevents "can be checked using hasColumn()" errors.)
        $schema = $this->getSchema();

        if ($schema->hasColumn('image_url')) {
            $schema->setColumnType('image_url', 'json');
        }

        if ($schema->hasColumn('threshold')) {
            $schema->setColumnType('threshold', 'integer');
        }

        if ($schema->hasColumn('archived')) {
            $schema->setColumnType('archived', 'string');
        }
    }

    public function validationDefault(Validator $v): Validator
    {
        $v->scalar('name')->requirePresence('name', 'create')->notEmptyString('name');

        $v->numeric('price', 'Price must be a number')
          ->requirePresence('price', 'create')
          ->notEmptyString('price');

        $v->numeric('sale_price', 'Sale price must be a number')->allowEmptyString('sale_price');

        $v->scalar('description')->allowEmptyString('description');

        // image_url is a plain string in this DB
        $v->allowEmptyString('image_url');

        $v->scalar('category')->allowEmptyString('category');

        return $v;
    }
}


