<?php

namespace App\Http\Controllers;

use App\Models\Product;
use Illuminate\Http\Request;
use Response;

class JsonController extends Controller {

    public function getProducts( Request $request ) {
        $noneOption = [];
        if ( isset( $request->includeNoneOption ) && $request->includeNoneOption == 1 ) {
            $noneOption[0] = [
                'id'   => 0,
                'text' => __( 'Product' )
            ];
        } else if ( isset( $request->includeAllOption ) && $request->includeAllOption == 1 ) {
            $noneOption[0] = [
                'id'   => 0,
                'text' => __( 'All Products' )
            ];
        }

        $term = $request->term;

        return Response::json( [
            'results' => array_merge(
                $noneOption,
                Product::select( 'id', 'name' )->where( function ( $q ) use ( $term ) {
                    if ( strlen( $term ) >= 3 ) {
                        $q->where( 'name', 'LIKE', '%' . $term . '%' );
                    }
                } )->get()->map( function ( $item ) {
                    return [
                        'id'   => $item['id'],
                        'text' => '#' . $item['id'] . ' ' . $item['name'],
                    ];
                } )->toArray()
            )
        ] );
    }
}
