<?php

namespace App\Controllers\Admin;

use App\Models\Magento\VentesFiltresModel;
use CodeIgniter\HTTP\ResponseInterface;

class VentesFiltres extends \App\Controllers\BaseController
{
    public function index()
    {
        return view('admin/ventesfiltres/index', [
            'title' => 'Filtres ventes clients',
        ]);
    }

    public function searchCriteria(): ResponseInterface
    {
        $query = trim($this->request->getGet('q') ?? '');
        $target = strtolower(trim((string)($this->request->getGet('target') ?? 'all')));
        $model = new VentesFiltresModel();

        $products = [];
        $brands = [];

        if ($target === 'product' || $target === 'all') {
            $products = $model->searchProducts($query);
        }
        if ($target === 'brand' || $target === 'all') {
            $brands = $model->searchBrands($query);
        }

        return $this->response->setJSON([
            'products' => $products,
            'brands' => $brands,
        ]);
    }

    public function getCompanies(): ResponseInterface
    {
        $model = new VentesFiltresModel();
        $query = trim((string)($this->request->getGet('q') ?? ''));
        return $this->response->setJSON(['items' => $model->getCompanies($query)]);
    }

    public function getResults(): ResponseInterface
    {
        $dateFrom = trim((string)($this->request->getGet('date_from') ?? ''));
        $dateTo = trim((string)($this->request->getGet('date_to') ?? ''));

        $companyValues = $this->request->getGet('company_values') ?? [];
        if (is_string($companyValues)) {
            $companyValues = $companyValues === '' ? [] : explode(',', $companyValues);
        }
        $companyValues = array_values(array_filter($companyValues, static fn ($v) => (string)$v !== ''));

        $conditions = $this->request->getGet('conditions') ?? [];
        if (is_string($conditions)) {
            $decoded = json_decode($conditions, true);
            $conditions = is_array($decoded) ? $decoded : [];
        }

        $model = new VentesFiltresModel();
        $items = $model->findCustomersByConditions($dateFrom, $dateTo, $conditions, $companyValues);

        return $this->response->setJSON([
            'items' => $items,
            'count' => count($items),
            'message' => empty($items) ? 'Aucun client trouvé pour ces filtres.' : '',
        ]);
    }
}
