<?php

namespace App\Http\Controllers;

use App\Services\OdooClient;
use Illuminate\Http\Request;

class OdooProductController extends Controller
{
    public function index(Request $request, OdooClient $odoo)
    {
        // Model: template (default) or variant
        $model = $request->get('model', 'product.template'); // or 'product.product'

        // --- Build domain (start with inbound domain if provided) ---
        $domain = json_decode($request->get('domain', '[]'), true) ?: [];

        // --- Multi-category by IDs ---
        // Accept: category_ids=1,2,3 OR category_ids=[1,2,3]
        $categoryIdsParam = $request->get('category_ids');
        $categoryIds = [];
        if ($categoryIdsParam) {
            if (is_string($categoryIdsParam) && str_starts_with(trim($categoryIdsParam), '[')) {
                $categoryIds = json_decode($categoryIdsParam, true) ?: [];
            } else {
                $categoryIds = array_filter(array_map(
                    fn ($v) => (int) trim($v),
                    explode(',', (string) $categoryIdsParam)
                ));
            }
        }

        // --- Multi-category by NAMES ---
        // Accept: categories=Office,Supplies,Furniture OR categories=["Office","Furniture"]
        $categoryNamesParam = $request->get('categories');
        $categoryNames = [];
        if ($categoryNamesParam) {
            if (is_string($categoryNamesParam) && str_starts_with(trim($categoryNamesParam), '[')) {
                $categoryNames = json_decode($categoryNamesParam, true) ?: [];
            } else {
                $categoryNames = array_filter(array_map('trim', explode(',', (string) $categoryNamesParam)));
            }
        }

        // If we have categories, choose IN or CHILD_OF per flag
        $includeChildren = $request->boolean('include_children', false);
        if (!empty($categoryIds)) {
            if ($includeChildren) {
                // all descendants of any given category id
                $domain[] = ['categ_id', 'child_of', $categoryIds];
            } else {
                $domain[] = ['categ_id', 'in', $categoryIds];
            }
        }

        // --- Fields / pagination ---
        $fields = $request->has('fields')
            ? array_values(array_filter(array_map('trim', explode(',', $request->get('fields')))))
            : ['id','name','list_price','standard_price','type','uom_id','categ_id','default_code','barcode','active'];

        $limit  = (int) $request->get('limit', 100);
        $offset = (int) $request->get('offset', 0);

        // --- Fetch ---
        if (!$request->boolean('all', false)) {
            $rows = $odoo->getProducts($model, $domain, $fields, $limit, $offset, [
                // 'order'   => 'name asc',
                // 'context' => ['lang' => 'en_US'],
            ]);
            return response()->json(['count' => count($rows), 'items' => $rows]);
        }

        $rows = $odoo->getAllProducts($model, $domain, $fields, 200, [
            // 'order'   => 'name asc',
            // 'context' => ['lang' => 'en_US'],
        ]);

        return response()->json(['count' => count($rows), 'items' => $rows]);
    }
}
