CREATE OR REPLACE FUNCTION public.search_cccontracts(search text)
 RETURNS SETOF cccontracts
 LANGUAGE plpgsql
 STABLE
AS $function$
BEGIN
	IF search = '' THEN
		RETURN query
		SELECT
			*
		FROM
			cccontracts c;
	ELSE
		RETURN query
		SELECT
			contracts.*
		FROM
		courtesycars cars,
			jobs jobs,
			cccontracts contracts
		WHERE (jobs.ro_number ILIKE '%' || search || '%'
			OR jobs.ownr_fn ILIKE '%' || search || '%'
			OR jobs.ownr_ln ILIKE '%' || search || '%'
			OR jobs.ownr_co_nm ILIKE '%' || search || '%'
			OR (cast(contracts.agreementnumber as text)) ILIKE '%' || search || '%'
			OR contracts.driver_fn ILIKE '%' || search || '%'
			OR contracts.driver_ln ILIKE '%' || search || '%'
			OR cars.fleetnumber ILIKE '%' || search || '%'
			OR cars.make ILIKE '%' || search || '%'
			OR cars.model ILIKE '%' || search || '%'
			OR cars.plate ILIKE '%' || search || '%')
			AND contracts.jobid = jobs.id
			AND contracts.courtesycarid = cars.id;
	END IF;
END
$function$;
