<?php
declare(strict_types=1);

namespace App\Models;

use Core\DB;
use Core\Model;

final class AssetTypeField extends Model
{
    protected string $table = 'asset_type_fields';
    protected string $primaryKey = 'field_id';

    public const TYPES = ['text','number','date','datetime','select','multiselect','textarea','boolean'];

    /**
     * Get the field schema for an asset type. Confirms the asset type belongs to
     * the tenant before returning fields, so callers only pass tenant_id + type_id.
     */
    public static function forType(int $tenantId, int $assetTypeId): array
    {
        return DB::all(
            'SELECT f.*
               FROM asset_type_fields f
               JOIN asset_types t ON t.asset_type_id = f.asset_type_id
              WHERE t.tenant_id = :t AND f.asset_type_id = :id AND t.deleted_at IS NULL
              ORDER BY f.sort_order, f.field_label',
            ['t' => $tenantId, 'id' => $assetTypeId]
        );
    }

    public static function findInTenant(int $tenantId, int $fieldId): ?array
    {
        return DB::one(
            'SELECT f.*
               FROM asset_type_fields f
               JOIN asset_types t ON t.asset_type_id = f.asset_type_id
              WHERE t.tenant_id = :t AND f.field_id = :id',
            ['t' => $tenantId, 'id' => $fieldId]
        );
    }

    public static function create(int $assetTypeId, array $data): int
    {
        return (int) DB::insert('asset_type_fields', [
            'asset_type_id' => $assetTypeId,
            'field_key'     => $data['field_key'],
            'field_label'   => $data['field_label'],
            'field_type'    => in_array($data['field_type'], self::TYPES, true) ? $data['field_type'] : 'text',
            'field_unit'    => $data['field_unit']    ?? null,
            'field_options' => !empty($data['field_options']) ? (string) $data['field_options'] : null,
            'field_section' => $data['field_section'] ?? 'General',
            'placeholder'   => $data['placeholder']   ?? null,
            'help_text'     => $data['help_text']     ?? null,
            'is_required'   => !empty($data['is_required']) ? 1 : 0,
            'sort_order'    => (int) ($data['sort_order'] ?? 0),
        ]);
    }

    public static function update(int $fieldId, array $data): void
    {
        $allowed = ['field_label','field_type','field_unit','field_options','field_section','placeholder','help_text','is_required','sort_order'];
        $set = [];
        $params = ['id' => $fieldId];
        foreach ($allowed as $col) {
            if (array_key_exists($col, $data)) {
                $val = $data[$col];
                if ($col === 'is_required') { $val = !empty($val) ? 1 : 0; }
                if ($col === 'sort_order')  { $val = (int) $val; }
                $set[] = "`{$col}` = :{$col}";
                $params[$col] = $val;
            }
        }
        if (!$set) return;
        DB::run(
            'UPDATE asset_type_fields SET ' . implode(', ', $set) . ' WHERE field_id = :id',
            $params
        );
    }

    public static function delete(int $fieldId): void
    {
        DB::run('DELETE FROM asset_type_fields WHERE field_id = :id', ['id' => $fieldId]);
    }
}
