<?php

use Mtc\Shop\CustomField;
use Mtc\Shop\CustomFieldSet;
use Mtc\Shop\CustomFieldSetField;
use Mtc\Shop\PropertyType;

/**
 * Custom Fields Helper
 *
 * @version 10/05/2015
 * @author Alan Reid
 * @copyright MTC Media Ltd
 *
 */
class CustomFieldsHelper
{

    /**
     * Gets proprerty list name
     *
     * @param int $id
     * @return string
     */
    public static function getPropertyListName($id): string
    {
        if ($propertyType = PropertyType::query()->find($id)) {
            return $propertyType->name;
        }
        return '';
    }


    /**
     * Gets custom field name
     *
     * @param int $id
     * @return string
     */
    public static function getCustomFieldName($id)
    {
        if ($customField = CustomField::query()->find($id)) {
            return $customField->name;
        }
        return '';
    }


    /**
     * Gets custom field data
     *
     * @param int $id
     * @return array<mixed>
     */
    public static function getCustomFieldData($id)
    {
        if ($customField = CustomField::query()->find($id)) {
            return $customField->toArray();
        }
        return [];
    }

    /**
     * Gets custom field Name from database_field
     */
    public static function getCustomFieldNameFromDBName(string $database_field): string
    {
        if ($customField = CustomField::query()->where('database_field', $database_field)->first()) {
            return $customField->name;
        }
        return '';
    }

    /**
     * @param $database_field
     * @return int|null
     * @throws Exception
     */
    public static function getCustomFieldIDFromDBName($database_field): ?int
    {
        if ($customField = CustomField::query()->where('database_field', $database_field)->first()) {
            return (int)$customField->id;
        }
        return null;
    }


    /**
     * Generates the html for a form for a set of custom fields
     *
     * @param int $set_id
     * @param string $type
     * @param array<mixed> $values
     * @return string
     */
    public static function displaySet($set_id, $type, $values, $custom_folders = false)
    {
        $fields = CustomFieldSetField::query()
            ->select('custom_fields_sets_fields.*')
            ->leftJoin('custom_fields', 'custom_fields.id', '=', 'custom_fields_sets_fields.custom_field_id')
            ->where('custom_fields_sets_fields.set_id', $set_id)
            ->when($type === 'item', function ($query) {
                $query->where('custom_fields_sets_fields.items', 1);
            })
            ->when($type === 'variations', function ($query) {
                $query->where('custom_fields_sets_fields.variations', 1);
            })
            ->orderBy('custom_fields.sort')
            ->get();


        foreach ($fields as $field) {
            $data = $field->toArray();
            $custom_field_data = CustomFieldsHelper::getCustomFieldData($data['custom_field_id']);
            ?>

            <div class="row">
                <label>

                    <?= clean_page($custom_field_data['name']) ?>

                    <?php
                    if ($data['required']) {
                        ?>
                        <span style="color:red;">*</span>
                        <?php
                    }
                    ?>

                </label>

                <?php
                include('../../../shop/admin/customfields/templates/' . $custom_field_data['type'] . '.php');
                ?>

            </div>

            <?php
        }
    }

    /**
     * Get an array of all the database fields used by a set
     *
     * @param int $set_id
     * @param string $type
     * @param integer $multiple
     * @return array<string>
     */
    public static function getSetDatabaseFields($set_id, $type, $multiple = '')
    {
        $database_fields = [];


        $fields = CustomFieldSetField::query()
            ->leftJoin('custom_fields', 'custom_fields.id', '=', 'custom_fields_sets_fields.custom_field_id')
            ->where('custom_fields_sets_fields.set_id', $set_id)
            ->when($type === 'item', function ($query) {
                $query->where('custom_fields_sets_fields.items', 1);
            })
            ->when($type === 'variations', function ($query) {
                $query->where('custom_fields_sets_fields.variations', 1);
            })
            ->where('custom_fields.multiple', $multiple)
            ->get();


        foreach ($fields as $field) {
            $custom_field_data = CustomFieldsHelper::getCustomFieldData($field->custom_field_id);


            $database_fields[] = $custom_field_data['database_field'];

        }

        return $database_fields;

    }

    /**
     * Validate the form input
     *
     * @param int $set_id
     * @param string $type
     * @param array<mixed> $values
     * @return array<string>
     */
    public static function validateCustomFields($set_id, $type, $values)
    {

        $errors = [];

        $fields = CustomFieldSetField::query()
            ->where('set_id', $set_id)
            ->when($type === 'item', function ($query) {
                $query->where('items', 1);
            })
            ->when($type === 'variations', function ($query) {
                $query->where('variations', 1);
            })
            ->get();

        foreach ($fields as $field) {
            $data = $field->toArray();
            $custom_field_data = CustomFieldsHelper::getCustomFieldData($data['custom_field_id']);

            if ($data['required'] && empty(trim($values[$custom_field_data['database_field']]))) {
                if ($custom_field_data['type'] == 'dropdown') {
                    $errors[$custom_field_data['database_field']] = 'Please select an option for ' . $custom_field_data['name'];
                } else {
                    $errors[$custom_field_data['database_field']] = 'Please enter a value for ' . $custom_field_data['name'];
                }
            }

        }

        return $errors;

    }


    /**
     * Get the id of the detault set to be used on products.
     *
     * @return int|null ID of the default set
     */

    public static function getDefaultSet(): ?int
    {
        if ($customFieldSet = CustomFieldSet::query()->where('default', 1)->first()) {
            return (int)$customFieldSet->id;
        }
        return null;
    }

    /**
     * Get property set for a category, defaulting to parent category's set if defined
     *
     * @param string|int $category_id
     * @return int
     */
    public static function getCategorySet($category_id)
    {
        do {
            $category_data = category_data($category_id);
            $set_id = $category_data['custom_field_set_id'];
            $category_id = $category_data['sub_id'];
        } while ($set_id == 0 && $category_data['sub_id']);
        return (int)$set_id;
    }
}
