<?php

namespace Koneko\VuexyContacts\Services;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class ContactCatalogService
{
    protected $catalogs = [
        'users' => [
            'table' => 'users',
            'key' => 'id',
            'value' => "CONCAT(name, ' ', COALESCE(last_name, ''), ' - ', email) as item",
            'search_columns' => ['name', 'last_name', 'email', 'rfc'],
            'order_by' => 'name',
            'limit' => 20,
        ],
        'contacts' => [
            'table' => 'users',
            'key' => 'id',
            'value' => "CONCAT(name, ' ', COALESCE(last_name, '')) as item",
            'search_columns' => ['name', 'last_name', 'rfc', 'company'],
            'extra_conditions' => ['is_customer' => true],
            'order_by' => 'name',
            'limit' => 20,
        ],
        'providers' => [
            'table' => 'users',
            'key' => 'id',
            'value' => "CONCAT(name, ' ', COALESCE(last_name, '')) as item",
            'search_columns' => ['name', 'last_name', 'rfc', 'company'],
            'extra_conditions' => ['is_provider' => true],
            'order_by' => 'name',
            'limit' => 20,
        ],
        'addresses' => [
            'table' => 'contactable_addresses',
            'key' => 'id',
            'value' => "CONCAT(direccion, ' #', num_ext, ' ', COALESCE(num_int, ''), ', ', c_codigo_postal) as item",
            'search_columns' => ['direccion', 'num_ext', 'c_codigo_postal'],
            'extra_conditions' => ['contactable_id', 'contactable_type'],
            'order_by' => 'direccion',
            'limit' => 10,
        ],
        'emails' => [
            'table' => 'contactable_items',
            'key' => 'id',
            'value' => 'data_contact as item',
            'search_columns' => ['data_contact'],
            'extra_conditions' => ['contactable_id', 'contactable_type', 'type' => 1], // 1 = email
            'order_by' => 'data_contact',
            'limit' => 10,
        ],
    ];

    /**
     * Método para obtener datos de catálogos con filtrado flexible.
     *
     * @param string $catalog
     * @param string|null $searchTerm
     * @param array $options
     * @return array
     */
    public function searchCatalog(string $catalog, ?string $searchTerm = '', array $options = []): array
    {
        if (!isset($this->catalogs[$catalog])) {
            return [];
        }

        $config = $this->catalogs[$catalog];
        $query = DB::table($config['table']);

        // Selección de columnas
        $query->selectRaw("{$config['key']}, {$config['value']}");

        // Aplicar condiciones extra
        if (!empty($config['extra_conditions'])) {
            foreach ($config['extra_conditions'] as $column => $value) {
                if (isset($options[$column])) {
                    $query->where($column, $options[$column]);
                }
            }
        }

        // Búsqueda
        if ($searchTerm) {
            $query->where(function ($subQ) use ($config, $searchTerm) {
                foreach ($config['search_columns'] as $column) {
                    $subQ->orWhere($column, 'LIKE', "%{$searchTerm}%");
                }
            });
        }

        // Orden y límite
        $query->orderBy($config['order_by'] ?? $config['key'], 'asc');
        $query->limit($options['limit'] ?? $config['limit'] ?? 20);

        return $query->pluck('item', $config['key'])->toArray();
    }
}